Add blinded path {metadata} fields to Path, but disallow paying blinded paths for now
[rust-lightning] / lightning / src / ln / payment_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
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
8 // licenses.
9
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.
13
14 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
15 use crate::chain::channelmonitor::{ANTI_REORG_DELAY, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
16 use crate::chain::keysinterface::EntropySource;
17 use crate::chain::transaction::OutPoint;
18 use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
19 use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
20 use crate::ln::channelmanager::{BREAKDOWN_TIMEOUT, ChannelManager, MPP_TIMEOUT_TICKS, MIN_CLTV_EXPIRY_DELTA, PaymentId, PaymentSendFailure, IDEMPOTENCY_TIMEOUT_TICKS, RecentPaymentDetails, RecipientOnionFields};
21 use crate::ln::features::InvoiceFeatures;
22 use crate::ln::msgs;
23 use crate::ln::msgs::ChannelMessageHandler;
24 use crate::ln::outbound_payment::Retry;
25 use crate::routing::gossip::{EffectiveCapacity, RoutingFees};
26 use crate::routing::router::{get_route, Path, PaymentParameters, Route, Router, RouteHint, RouteHintHop, RouteHop, RouteParameters};
27 use crate::routing::scoring::ChannelUsage;
28 use crate::util::test_utils;
29 use crate::util::errors::APIError;
30 use crate::util::ser::Writeable;
31 use crate::util::string::UntrustedString;
32
33 use bitcoin::{Block, BlockHeader, TxMerkleNode};
34 use bitcoin::hashes::Hash;
35 use bitcoin::network::constants::Network;
36
37 use crate::prelude::*;
38
39 use crate::ln::functional_test_utils::*;
40 use crate::routing::gossip::NodeId;
41 #[cfg(feature = "std")]
42 use {
43         crate::util::time::tests::SinceEpoch,
44         std::time::{SystemTime, Instant, Duration}
45 };
46
47 #[test]
48 fn mpp_failure() {
49         let chanmon_cfgs = create_chanmon_cfgs(4);
50         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
51         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
52         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
53
54         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
55         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
56         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
57         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
58
59         let (mut route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
60         let path = route.paths[0].clone();
61         route.paths.push(path);
62         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
63         route.paths[0].hops[0].short_channel_id = chan_1_id;
64         route.paths[0].hops[1].short_channel_id = chan_3_id;
65         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
66         route.paths[1].hops[0].short_channel_id = chan_2_id;
67         route.paths[1].hops[1].short_channel_id = chan_4_id;
68         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
69         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
70 }
71
72 #[test]
73 fn mpp_retry() {
74         let chanmon_cfgs = create_chanmon_cfgs(4);
75         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
76         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
77         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
78
79         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
80         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
81         let (chan_3_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
82         let (chan_4_update, _, chan_4_id, _) = create_announced_chan_between_nodes(&nodes, 3, 2);
83         // Rebalance
84         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
85
86         let amt_msat = 1_000_000;
87         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], amt_msat);
88         let path = route.paths[0].clone();
89         route.paths.push(path);
90         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
91         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
92         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
93         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
94         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
95         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
96
97         // Initiate the MPP payment.
98         let payment_id = PaymentId(payment_hash.0);
99         let mut route_params = RouteParameters {
100                 payment_params: route.payment_params.clone().unwrap(),
101                 final_value_msat: amt_msat,
102         };
103
104         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
105         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
106                 payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
107         check_added_monitors!(nodes[0], 2); // one monitor per path
108         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
109         assert_eq!(events.len(), 2);
110
111         // Pass half of the payment along the success path.
112         let success_path_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
113         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), success_path_msgs, false, None);
114
115         // Add the HTLC along the first hop.
116         let fail_path_msgs_1 = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
117         let (update_add, commitment_signed) = match fail_path_msgs_1 {
118                 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 } } => {
119                         assert_eq!(update_add_htlcs.len(), 1);
120                         assert!(update_fail_htlcs.is_empty());
121                         assert!(update_fulfill_htlcs.is_empty());
122                         assert!(update_fail_malformed_htlcs.is_empty());
123                         assert!(update_fee.is_none());
124                         (update_add_htlcs[0].clone(), commitment_signed.clone())
125                 },
126                 _ => panic!("Unexpected event"),
127         };
128         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
129         commitment_signed_dance!(nodes[2], nodes[0], commitment_signed, false);
130
131         // Attempt to forward the payment and complete the 2nd path's failure.
132         expect_pending_htlcs_forwardable!(&nodes[2]);
133         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 }]);
134         let htlc_updates = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
135         assert!(htlc_updates.update_add_htlcs.is_empty());
136         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
137         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
138         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
139         check_added_monitors!(nodes[2], 1);
140         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
141         commitment_signed_dance!(nodes[0], nodes[2], htlc_updates.commitment_signed, false);
142         let mut events = nodes[0].node.get_and_clear_pending_events();
143         match events[1] {
144                 Event::PendingHTLCsForwardable { .. } => {},
145                 _ => panic!("Unexpected event")
146         }
147         events.remove(1);
148         expect_payment_failed_conditions_event(events, payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain());
149
150         // Rebalance the channel so the second half of the payment can succeed.
151         send_payment(&nodes[3], &vec!(&nodes[2])[..], 1_500_000);
152
153         // Retry the second half of the payment and make sure it succeeds.
154         route.paths.remove(0);
155         route_params.final_value_msat = 1_000_000;
156         route_params.payment_params.previously_failed_channels.push(chan_4_update.contents.short_channel_id);
157         nodes[0].router.expect_find_route(route_params, Ok(route));
158         nodes[0].node.process_pending_htlc_forwards();
159         check_added_monitors!(nodes[0], 1);
160         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
161         assert_eq!(events.len(), 1);
162         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 2_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
163         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
164 }
165
166 fn do_mpp_receive_timeout(send_partial_mpp: bool) {
167         let chanmon_cfgs = create_chanmon_cfgs(4);
168         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
169         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
170         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
171
172         let (chan_1_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
173         let (chan_2_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 0, 2);
174         let (chan_3_update, _, chan_3_id, _) = create_announced_chan_between_nodes(&nodes, 1, 3);
175         let (chan_4_update, _, _, _) = create_announced_chan_between_nodes(&nodes, 2, 3);
176
177         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 100_000);
178         let path = route.paths[0].clone();
179         route.paths.push(path);
180         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
181         route.paths[0].hops[0].short_channel_id = chan_1_update.contents.short_channel_id;
182         route.paths[0].hops[1].short_channel_id = chan_3_update.contents.short_channel_id;
183         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
184         route.paths[1].hops[0].short_channel_id = chan_2_update.contents.short_channel_id;
185         route.paths[1].hops[1].short_channel_id = chan_4_update.contents.short_channel_id;
186
187         // Initiate the MPP payment.
188         nodes[0].node.send_payment_with_route(&route, payment_hash,
189                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
190         check_added_monitors!(nodes[0], 2); // one monitor per path
191         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
192         assert_eq!(events.len(), 2);
193
194         // Pass half of the payment along the first path.
195         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
196         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
197
198         if send_partial_mpp {
199                 // Time out the partial MPP
200                 for _ in 0..MPP_TIMEOUT_TICKS {
201                         nodes[3].node.timer_tick_occurred();
202                 }
203
204                 // Failed HTLC from node 3 -> 1
205                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash }]);
206                 let htlc_fail_updates_3_1 = get_htlc_update_msgs!(nodes[3], nodes[1].node.get_our_node_id());
207                 assert_eq!(htlc_fail_updates_3_1.update_fail_htlcs.len(), 1);
208                 nodes[1].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &htlc_fail_updates_3_1.update_fail_htlcs[0]);
209                 check_added_monitors!(nodes[3], 1);
210                 commitment_signed_dance!(nodes[1], nodes[3], htlc_fail_updates_3_1.commitment_signed, false);
211
212                 // Failed HTLC from node 1 -> 0
213                 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 }]);
214                 let htlc_fail_updates_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
215                 assert_eq!(htlc_fail_updates_1_0.update_fail_htlcs.len(), 1);
216                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates_1_0.update_fail_htlcs[0]);
217                 check_added_monitors!(nodes[1], 1);
218                 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates_1_0.commitment_signed, false);
219
220                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new().mpp_parts_remain().expected_htlc_error_data(23, &[][..]));
221         } else {
222                 // Pass half of the payment along the second path.
223                 let node_2_msgs = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
224                 pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 200_000, payment_hash, Some(payment_secret), node_2_msgs, true, None);
225
226                 // Even after MPP_TIMEOUT_TICKS we should not timeout the MPP if we have all the parts
227                 for _ in 0..MPP_TIMEOUT_TICKS {
228                         nodes[3].node.timer_tick_occurred();
229                 }
230
231                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
232         }
233 }
234
235 #[test]
236 fn mpp_receive_timeout() {
237         do_mpp_receive_timeout(true);
238         do_mpp_receive_timeout(false);
239 }
240
241 #[test]
242 fn no_pending_leak_on_initial_send_failure() {
243         // In an earlier version of our payment tracking, we'd have a retry entry even when the initial
244         // HTLC for payment failed to send due to local channel errors (e.g. peer disconnected). In this
245         // case, the user wouldn't have a PaymentId to retry the payment with, but we'd think we have a
246         // pending payment forever and never time it out.
247         // Here we test exactly that - retrying a payment when a peer was disconnected on the first
248         // try, and then check that no pending payment is being tracked.
249         let chanmon_cfgs = create_chanmon_cfgs(2);
250         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
251         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
252         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
253
254         create_announced_chan_between_nodes(&nodes, 0, 1);
255
256         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
257
258         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
259         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
260
261         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
262                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
263                 ), true, APIError::ChannelUnavailable { ref err },
264                 assert_eq!(err, "Peer for first hop currently disconnected"));
265
266         assert!(!nodes[0].node.has_pending_payments());
267 }
268
269 fn do_retry_with_no_persist(confirm_before_reload: bool) {
270         // If we send a pending payment and `send_payment` returns success, we should always either
271         // return a payment failure event or a payment success event, and on failure the payment should
272         // be retryable.
273         //
274         // In order to do so when the ChannelManager isn't immediately persisted (which is normal - its
275         // always persisted asynchronously), the ChannelManager has to reload some payment data from
276         // ChannelMonitor(s) in some cases. This tests that reloading.
277         //
278         // `confirm_before_reload` confirms the channel-closing commitment transaction on-chain prior
279         // to reloading the ChannelManager, increasing test coverage in ChannelMonitor HTLC tracking
280         // which has separate codepaths for "commitment transaction already confirmed" and not.
281         let chanmon_cfgs = create_chanmon_cfgs(3);
282         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
283         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
284         let persister: test_utils::TestPersister;
285         let new_chain_monitor: test_utils::TestChainMonitor;
286         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>;
287         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
288
289         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
290         let (_, _, chan_id_2, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
291
292         // Serialize the ChannelManager prior to sending payments
293         let nodes_0_serialized = nodes[0].node.encode();
294
295         // Send two payments - one which will get to nodes[2] and will be claimed, one which we'll time
296         // out and retry.
297         let amt_msat = 1_000_000;
298         let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
299         let (payment_preimage_1, payment_hash_1, _, payment_id_1) = send_along_route(&nodes[0], route.clone(), &[&nodes[1], &nodes[2]], 1_000_000);
300         let route_params = RouteParameters {
301                 payment_params: route.payment_params.clone().unwrap(),
302                 final_value_msat: amt_msat,
303         };
304         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
305                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
306         check_added_monitors!(nodes[0], 1);
307
308         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
309         assert_eq!(events.len(), 1);
310         let payment_event = SendEvent::from_event(events.pop().unwrap());
311         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
312
313         // We relay the payment to nodes[1] while its disconnected from nodes[2], causing the payment
314         // to be returned immediately to nodes[0], without having nodes[2] fail the inbound payment
315         // which would prevent retry.
316         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
317         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
318
319         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
320         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
321         // nodes[1] now immediately fails the HTLC as the next-hop channel is disconnected
322         let _ = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
323
324         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
325
326         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan_id)[0].clone();
327         if confirm_before_reload {
328                 mine_transaction(&nodes[0], &as_commitment_tx);
329                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
330         }
331
332         // The ChannelMonitor should always be the latest version, as we're required to persist it
333         // during the `commitment_signed_dance!()`.
334         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
335         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
336
337         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
338         // force-close the channel.
339         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
340         assert!(nodes[0].node.list_channels().is_empty());
341         assert!(nodes[0].node.has_pending_payments());
342         nodes[0].node.timer_tick_occurred();
343         if !confirm_before_reload {
344                 let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
345                 assert_eq!(as_broadcasted_txn.len(), 1);
346                 assert_eq!(as_broadcasted_txn[0], as_commitment_tx);
347         } else {
348                 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
349         }
350         check_added_monitors!(nodes[0], 1);
351
352         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
353         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
354         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
355
356         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
357         // error, as the channel has hit the chain.
358         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
359         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
360         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
361         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
362         assert_eq!(as_err.len(), 1);
363         match as_err[0] {
364                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
365                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
366                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
367                         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(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())) });
368                         check_added_monitors!(nodes[1], 1);
369                         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
370                 },
371                 _ => panic!("Unexpected event"),
372         }
373         check_closed_broadcast!(nodes[1], false);
374
375         // Now claim the first payment, which should allow nodes[1] to claim the payment on-chain when
376         // we close in a moment.
377         nodes[2].node.claim_funds(payment_preimage_1);
378         check_added_monitors!(nodes[2], 1);
379         expect_payment_claimed!(nodes[2], payment_hash_1, 1_000_000);
380
381         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
382         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
383         check_added_monitors!(nodes[1], 1);
384         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
385         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], None, false, false);
386
387         if confirm_before_reload {
388                 let best_block = nodes[0].blocks.lock().unwrap().last().unwrap().clone();
389                 nodes[0].node.best_block_updated(&best_block.0.header, best_block.1);
390         }
391
392         // Create a new channel on which to retry the payment before we fail the payment via the
393         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
394         // connecting several blocks while creating the channel (implying time has passed).
395         create_announced_chan_between_nodes(&nodes, 0, 1);
396         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
397
398         mine_transaction(&nodes[1], &as_commitment_tx);
399         let bs_htlc_claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
400         assert_eq!(bs_htlc_claim_txn.len(), 1);
401         check_spends!(bs_htlc_claim_txn[0], as_commitment_tx);
402
403         if !confirm_before_reload {
404                 mine_transaction(&nodes[0], &as_commitment_tx);
405         }
406         mine_transaction(&nodes[0], &bs_htlc_claim_txn[0]);
407         expect_payment_sent!(nodes[0], payment_preimage_1);
408         connect_blocks(&nodes[0], TEST_FINAL_CLTV*4 + 20);
409         let (first_htlc_timeout_tx, second_htlc_timeout_tx) = {
410                 let mut txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
411                 assert_eq!(txn.len(), 2);
412                 (txn.remove(0), txn.remove(0))
413         };
414         check_spends!(first_htlc_timeout_tx, as_commitment_tx);
415         check_spends!(second_htlc_timeout_tx, as_commitment_tx);
416         if first_htlc_timeout_tx.input[0].previous_output == bs_htlc_claim_txn[0].input[0].previous_output {
417                 confirm_transaction(&nodes[0], &second_htlc_timeout_tx);
418         } else {
419                 confirm_transaction(&nodes[0], &first_htlc_timeout_tx);
420         }
421         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
422         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
423
424         // Finally, retry the payment (which was reloaded from the ChannelMonitor when nodes[0] was
425         // reloaded) via a route over the new channel, which work without issue and eventually be
426         // received and claimed at the recipient just like any other payment.
427         let (mut new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], 1_000_000);
428
429         // Update the fee on the middle hop to ensure PaymentSent events have the correct (retried) fee
430         // and not the original fee. We also update node[1]'s relevant config as
431         // do_claim_payment_along_route expects us to never overpay.
432         {
433                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
434                 let mut peer_state = per_peer_state.get(&nodes[2].node.get_our_node_id())
435                         .unwrap().lock().unwrap();
436                 let mut channel = peer_state.channel_by_id.get_mut(&chan_id_2).unwrap();
437                 let mut new_config = channel.config();
438                 new_config.forwarding_fee_base_msat += 100_000;
439                 channel.update_config(&new_config);
440                 new_route.paths[0].hops[0].fee_msat += 100_000;
441         }
442
443         // Force expiration of the channel's previous config.
444         for _ in 0..EXPIRE_PREV_CONFIG_TICKS {
445                 nodes[1].node.timer_tick_occurred();
446         }
447
448         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash, // Shouldn't be allowed to retry a fulfilled payment
449                 RecipientOnionFields::secret_only(payment_secret), payment_id_1).is_err());
450         nodes[0].node.send_payment_with_route(&new_route, payment_hash,
451                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
452         check_added_monitors!(nodes[0], 1);
453         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
454         assert_eq!(events.len(), 1);
455         pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000, payment_hash, Some(payment_secret), events.pop().unwrap(), true, None);
456         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
457         expect_payment_sent!(nodes[0], payment_preimage, Some(new_route.paths[0].hops[0].fee_msat));
458 }
459
460 #[test]
461 fn retry_with_no_persist() {
462         do_retry_with_no_persist(true);
463         do_retry_with_no_persist(false);
464 }
465
466 fn do_test_completed_payment_not_retryable_on_reload(use_dust: bool) {
467         // Test that an off-chain completed payment is not retryable on restart. This was previously
468         // broken for dust payments, but we test for both dust and non-dust payments.
469         //
470         // `use_dust` switches to using a dust HTLC, which results in the HTLC not having an on-chain
471         // output at all.
472         let chanmon_cfgs = create_chanmon_cfgs(3);
473         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
474
475         let mut manually_accept_config = test_default_channel_config();
476         manually_accept_config.manually_accept_inbound_channels = true;
477
478         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(manually_accept_config), None]);
479
480         let first_persister: test_utils::TestPersister;
481         let first_new_chain_monitor: test_utils::TestChainMonitor;
482         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>;
483         let second_persister: test_utils::TestPersister;
484         let second_new_chain_monitor: test_utils::TestChainMonitor;
485         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>;
486         let third_persister: test_utils::TestPersister;
487         let third_new_chain_monitor: test_utils::TestChainMonitor;
488         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>;
489
490         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
491
492         // Because we set nodes[1] to manually accept channels, just open a 0-conf channel.
493         let (funding_tx, chan_id) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
494         confirm_transaction(&nodes[0], &funding_tx);
495         confirm_transaction(&nodes[1], &funding_tx);
496         // Ignore the announcement_signatures messages
497         nodes[0].node.get_and_clear_pending_msg_events();
498         nodes[1].node.get_and_clear_pending_msg_events();
499         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2).2;
500
501         // Serialize the ChannelManager prior to sending payments
502         let mut nodes_0_serialized = nodes[0].node.encode();
503
504         let route = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 }).0;
505         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 });
506
507         // The ChannelMonitor should always be the latest version, as we're required to persist it
508         // during the `commitment_signed_dance!()`.
509         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
510
511         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);
512         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
513
514         // On reload, the ChannelManager should realize it is stale compared to the ChannelMonitor and
515         // force-close the channel.
516         check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
517         nodes[0].node.timer_tick_occurred();
518         assert!(nodes[0].node.list_channels().is_empty());
519         assert!(nodes[0].node.has_pending_payments());
520         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
521         check_added_monitors!(nodes[0], 1);
522
523         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: nodes[1].node.init_features(), remote_network_address: None }, true).unwrap();
524         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
525
526         // Now nodes[1] should send a channel reestablish, which nodes[0] will respond to with an
527         // error, as the channel has hit the chain.
528         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: nodes[0].node.init_features(), remote_network_address: None }, false).unwrap();
529         let bs_reestablish = get_chan_reestablish_msgs!(nodes[1], nodes[0]).pop().unwrap();
530         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
531         let as_err = nodes[0].node.get_and_clear_pending_msg_events();
532         assert_eq!(as_err.len(), 1);
533         let bs_commitment_tx;
534         match as_err[0] {
535                 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
536                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
537                         nodes[1].node.handle_error(&nodes[0].node.get_our_node_id(), msg);
538                         check_closed_event!(nodes[1], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString(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())) });
539                         check_added_monitors!(nodes[1], 1);
540                         bs_commitment_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
541                 },
542                 _ => panic!("Unexpected event"),
543         }
544         check_closed_broadcast!(nodes[1], false);
545
546         // Now fail back the payment from nodes[2] to nodes[1]. This doesn't really matter as the
547         // previous hop channel is already on-chain, but it makes nodes[2] willing to see additional
548         // incoming HTLCs with the same payment hash later.
549         nodes[2].node.fail_htlc_backwards(&payment_hash);
550         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], [HTLCDestination::FailedPayment { payment_hash }]);
551         check_added_monitors!(nodes[2], 1);
552
553         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
554         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &htlc_fulfill_updates.update_fail_htlcs[0]);
555         commitment_signed_dance!(nodes[1], nodes[2], htlc_fulfill_updates.commitment_signed, false);
556         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
557                 [HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_id_2 }]);
558
559         // Connect the HTLC-Timeout transaction, timing out the HTLC on both nodes (but not confirming
560         // the HTLC-Timeout transaction beyond 1 conf). For dust HTLCs, the HTLC is considered resolved
561         // after the commitment transaction, so always connect the commitment transaction.
562         mine_transaction(&nodes[0], &bs_commitment_tx[0]);
563         mine_transaction(&nodes[1], &bs_commitment_tx[0]);
564         if !use_dust {
565                 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
566                 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1 + (MIN_CLTV_EXPIRY_DELTA as u32));
567                 let as_htlc_timeout = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
568                 check_spends!(as_htlc_timeout[0], bs_commitment_tx[0]);
569                 assert_eq!(as_htlc_timeout.len(), 1);
570
571                 mine_transaction(&nodes[0], &as_htlc_timeout[0]);
572                 // nodes[0] may rebroadcast (or RBF-bump) its HTLC-Timeout, so wipe the announced set.
573                 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
574                 mine_transaction(&nodes[1], &as_htlc_timeout[0]);
575         }
576
577         // Create a new channel on which to retry the payment before we fail the payment via the
578         // HTLC-Timeout transaction. This avoids ChannelManager timing out the payment due to us
579         // connecting several blocks while creating the channel (implying time has passed).
580         // We do this with a zero-conf channel to avoid connecting blocks as a side-effect.
581         let (_, chan_id_3) = open_zero_conf_channel(&nodes[0], &nodes[1], None);
582         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
583
584         // If we attempt to retry prior to the HTLC-Timeout (or commitment transaction, for dust HTLCs)
585         // confirming, we will fail as it's considered still-pending...
586         let (new_route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], if use_dust { 1_000 } else { 1_000_000 });
587         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
588                 Err(PaymentSendFailure::DuplicatePayment) => {},
589                 _ => panic!("Unexpected error")
590         }
591         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
592
593         // After ANTI_REORG_DELAY confirmations, the HTLC should be failed and we can try the payment
594         // again. We serialize the node first as we'll then test retrying the HTLC after a restart
595         // (which should also still work).
596         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
597         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
598         expect_payment_failed_conditions(&nodes[0], payment_hash, false, PaymentFailedConditions::new());
599
600         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
601         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
602         nodes_0_serialized = nodes[0].node.encode();
603
604         // After the payment failed, we're free to send it again.
605         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
606                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
607         assert!(!nodes[0].node.get_and_clear_pending_msg_events().is_empty());
608
609         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);
610         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
611
612         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
613
614         // Now resend the payment, delivering the HTLC and actually claiming it this time. This ensures
615         // the payment is not (spuriously) listed as still pending.
616         assert!(nodes[0].node.send_payment_with_route(&new_route, payment_hash,
617                 RecipientOnionFields::secret_only(payment_secret), payment_id).is_ok());
618         check_added_monitors!(nodes[0], 1);
619         pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], if use_dust { 1_000 } else { 1_000_000 }, payment_hash, payment_secret);
620         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
621
622         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
623                 Err(PaymentSendFailure::DuplicatePayment) => {},
624                 _ => panic!("Unexpected error")
625         }
626         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
627
628         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
629         let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_3).encode();
630         nodes_0_serialized = nodes[0].node.encode();
631
632         // Check that after reload we can send the payment again (though we shouldn't, since it was
633         // claimed previously).
634         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);
635         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
636
637         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
638
639         match nodes[0].node.send_payment_with_route(&new_route, payment_hash, RecipientOnionFields::secret_only(payment_secret), payment_id) {
640                 Err(PaymentSendFailure::DuplicatePayment) => {},
641                 _ => panic!("Unexpected error")
642         }
643         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
644 }
645
646 #[test]
647 fn test_completed_payment_not_retryable_on_reload() {
648         do_test_completed_payment_not_retryable_on_reload(true);
649         do_test_completed_payment_not_retryable_on_reload(false);
650 }
651
652
653 fn do_test_dup_htlc_onchain_fails_on_reload(persist_manager_post_event: bool, confirm_commitment_tx: bool, payment_timeout: bool) {
654         // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
655         // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
656         // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
657         // the ChannelMonitor tells it to.
658         //
659         // If, due to an on-chain event, an HTLC is failed/claimed, we should avoid providing the
660         // ChannelManager the HTLC event until after the monitor is re-persisted. This should prevent a
661         // duplicate HTLC fail/claim (e.g. via a PaymentPathFailed event).
662         let chanmon_cfgs = create_chanmon_cfgs(2);
663         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
664         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
665         let persister: test_utils::TestPersister;
666         let new_chain_monitor: test_utils::TestChainMonitor;
667         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>;
668         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
669
670         let (_, _, chan_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
671
672         // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
673         // nodes[0].
674         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000_000);
675         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
676         check_closed_broadcast!(nodes[0], true);
677         check_added_monitors!(nodes[0], 1);
678         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
679
680         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
681         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
682
683         // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
684         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
685         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
686         assert_eq!(node_txn.len(), 3);
687         assert_eq!(node_txn[0], node_txn[1]);
688         check_spends!(node_txn[1], funding_tx);
689         check_spends!(node_txn[2], node_txn[1]);
690         let timeout_txn = vec![node_txn[2].clone()];
691
692         nodes[1].node.claim_funds(payment_preimage);
693         check_added_monitors!(nodes[1], 1);
694         expect_payment_claimed!(nodes[1], payment_hash, 10_000_000);
695
696         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 };
697         connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()]});
698         check_closed_broadcast!(nodes[1], true);
699         check_added_monitors!(nodes[1], 1);
700         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
701         let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
702         assert_eq!(claim_txn.len(), 1);
703         check_spends!(claim_txn[0], node_txn[1]);
704
705         header.prev_blockhash = nodes[0].best_block_hash();
706         connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()]});
707
708         if confirm_commitment_tx {
709                 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
710         }
711
712         header.prev_blockhash = nodes[0].best_block_hash();
713         let claim_block = Block { header, txdata: if payment_timeout { timeout_txn } else { vec![claim_txn[0].clone()] } };
714
715         if payment_timeout {
716                 assert!(confirm_commitment_tx); // Otherwise we're spending below our CSV!
717                 connect_block(&nodes[0], &claim_block);
718                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 2);
719         }
720
721         // Now connect the HTLC claim transaction with the ChainMonitor-generated ChannelMonitor update
722         // returning InProgress. This should cause the claim event to never make its way to the
723         // ChannelManager.
724         chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap().clear();
725         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
726
727         if payment_timeout {
728                 connect_blocks(&nodes[0], 1);
729         } else {
730                 connect_block(&nodes[0], &claim_block);
731         }
732
733         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
734         let mon_updates: Vec<_> = chanmon_cfgs[0].persister.chain_sync_monitor_persistences.lock().unwrap()
735                 .get_mut(&funding_txo).unwrap().drain().collect();
736         // If we are using chain::Confirm instead of chain::Listen, we will get the same update twice.
737         // If we're testing connection idempotency we may get substantially more.
738         assert!(mon_updates.len() >= 1);
739         assert!(nodes[0].chain_monitor.release_pending_monitor_events().is_empty());
740         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
741
742         // If we persist the ChannelManager here, we should get the PaymentSent event after
743         // deserialization.
744         let mut chan_manager_serialized = Vec::new();
745         if !persist_manager_post_event {
746                 chan_manager_serialized = nodes[0].node.encode();
747         }
748
749         // Now persist the ChannelMonitor and inform the ChainMonitor that we're done, generating the
750         // payment sent event.
751         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
752         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
753         for update in mon_updates {
754                 nodes[0].chain_monitor.chain_monitor.channel_monitor_updated(funding_txo, update).unwrap();
755         }
756         if payment_timeout {
757                 expect_payment_failed!(nodes[0], payment_hash, false);
758         } else {
759                 expect_payment_sent!(nodes[0], payment_preimage);
760         }
761
762         // If we persist the ChannelManager after we get the PaymentSent event, we shouldn't get it
763         // twice.
764         if persist_manager_post_event {
765                 chan_manager_serialized = nodes[0].node.encode();
766         }
767
768         // Now reload nodes[0]...
769         reload_node!(nodes[0], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_0_deserialized);
770
771         if persist_manager_post_event {
772                 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
773         } else if payment_timeout {
774                 expect_payment_failed!(nodes[0], payment_hash, false);
775         } else {
776                 expect_payment_sent!(nodes[0], payment_preimage);
777         }
778
779         // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
780         // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
781         // payment events should kick in, leaving us with no pending events here.
782         let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
783         nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
784         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
785 }
786
787 #[test]
788 fn test_dup_htlc_onchain_fails_on_reload() {
789         do_test_dup_htlc_onchain_fails_on_reload(true, true, true);
790         do_test_dup_htlc_onchain_fails_on_reload(true, true, false);
791         do_test_dup_htlc_onchain_fails_on_reload(true, false, false);
792         do_test_dup_htlc_onchain_fails_on_reload(false, true, true);
793         do_test_dup_htlc_onchain_fails_on_reload(false, true, false);
794         do_test_dup_htlc_onchain_fails_on_reload(false, false, false);
795 }
796
797 #[test]
798 fn test_fulfill_restart_failure() {
799         // When we receive an update_fulfill_htlc message, we immediately consider the HTLC fully
800         // fulfilled. At this point, the peer can reconnect and decide to either fulfill the HTLC
801         // again, or fail it, giving us free money.
802         //
803         // Of course probably they won't fail it and give us free money, but because we have code to
804         // handle it, we should test the logic for it anyway. We do that here.
805         let chanmon_cfgs = create_chanmon_cfgs(2);
806         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
807         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
808         let persister: test_utils::TestPersister;
809         let new_chain_monitor: test_utils::TestChainMonitor;
810         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>;
811         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
812
813         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
814         let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
815
816         // The simplest way to get a failure after a fulfill is to reload nodes[1] from a state
817         // pre-fulfill, which we do by serializing it here.
818         let chan_manager_serialized = nodes[1].node.encode();
819         let chan_0_monitor_serialized = get_monitor!(nodes[1], chan_id).encode();
820
821         nodes[1].node.claim_funds(payment_preimage);
822         check_added_monitors!(nodes[1], 1);
823         expect_payment_claimed!(nodes[1], payment_hash, 100_000);
824
825         let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
826         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
827         expect_payment_sent_without_paths!(nodes[0], payment_preimage);
828
829         // Now reload nodes[1]...
830         reload_node!(nodes[1], &chan_manager_serialized, &[&chan_0_monitor_serialized], persister, new_chain_monitor, nodes_1_deserialized);
831
832         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
833         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
834
835         nodes[1].node.fail_htlc_backwards(&payment_hash);
836         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
837         check_added_monitors!(nodes[1], 1);
838         let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
839         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
840         commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, false);
841         // nodes[0] shouldn't generate any events here, while it just got a payment failure completion
842         // it had already considered the payment fulfilled, and now they just got free money.
843         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
844 }
845
846 #[test]
847 fn get_ldk_payment_preimage() {
848         // Ensure that `ChannelManager::get_payment_preimage` can successfully be used to claim a payment.
849         let chanmon_cfgs = create_chanmon_cfgs(2);
850         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
851         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
852         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
853         create_announced_chan_between_nodes(&nodes, 0, 1);
854
855         let amt_msat = 60_000;
856         let expiry_secs = 60 * 60;
857         let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(amt_msat), expiry_secs, None).unwrap();
858
859         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
860                 .with_features(nodes[1].node.invoice_features());
861         let scorer = test_utils::TestScorer::new();
862         let keys_manager = test_utils::TestKeysInterface::new(&[0u8; 32], Network::Testnet);
863         let random_seed_bytes = keys_manager.get_secure_random_bytes();
864         let route = get_route(
865                 &nodes[0].node.get_our_node_id(), &payment_params, &nodes[0].network_graph.read_only(),
866                 Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
867                 amt_msat, TEST_FINAL_CLTV, nodes[0].logger, &scorer, &random_seed_bytes).unwrap();
868         nodes[0].node.send_payment_with_route(&route, payment_hash,
869                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
870         check_added_monitors!(nodes[0], 1);
871
872         // Make sure to use `get_payment_preimage`
873         let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
874         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
875         assert_eq!(events.len(), 1);
876         pass_along_path(&nodes[0], &[&nodes[1]], amt_msat, payment_hash, Some(payment_secret), events.pop().unwrap(), true, Some(payment_preimage));
877         claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, payment_preimage);
878 }
879
880 #[test]
881 fn sent_probe_is_probe_of_sending_node() {
882         let chanmon_cfgs = create_chanmon_cfgs(3);
883         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
884         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
885         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
886
887         create_announced_chan_between_nodes(&nodes, 0, 1);
888         create_announced_chan_between_nodes(&nodes, 1, 2);
889
890         // First check we refuse to build a single-hop probe
891         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100_000);
892         assert!(nodes[0].node.send_probe(route.paths[0].clone()).is_err());
893
894         // Then build an actual two-hop probing path
895         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
896
897         match nodes[0].node.send_probe(route.paths[0].clone()) {
898                 Ok((payment_hash, payment_id)) => {
899                         assert!(nodes[0].node.payment_is_probe(&payment_hash, &payment_id));
900                         assert!(!nodes[1].node.payment_is_probe(&payment_hash, &payment_id));
901                         assert!(!nodes[2].node.payment_is_probe(&payment_hash, &payment_id));
902                 },
903                 _ => panic!(),
904         }
905
906         get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
907         check_added_monitors!(nodes[0], 1);
908 }
909
910 #[test]
911 fn successful_probe_yields_event() {
912         let chanmon_cfgs = create_chanmon_cfgs(3);
913         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
914         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
915         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
916
917         create_announced_chan_between_nodes(&nodes, 0, 1);
918         create_announced_chan_between_nodes(&nodes, 1, 2);
919
920         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], 100_000);
921
922         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
923
924         // node[0] -- update_add_htlcs -> node[1]
925         check_added_monitors!(nodes[0], 1);
926         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
927         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
928         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
929         check_added_monitors!(nodes[1], 0);
930         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
931         expect_pending_htlcs_forwardable!(nodes[1]);
932
933         // node[1] -- update_add_htlcs -> node[2]
934         check_added_monitors!(nodes[1], 1);
935         let updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
936         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
937         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &probe_event.msgs[0]);
938         check_added_monitors!(nodes[2], 0);
939         commitment_signed_dance!(nodes[2], nodes[1], probe_event.commitment_msg, true, true);
940
941         // node[1] <- update_fail_htlcs -- node[2]
942         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
943         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
944         check_added_monitors!(nodes[1], 0);
945         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, true);
946
947         // node[0] <- update_fail_htlcs -- node[1]
948         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
949         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
950         check_added_monitors!(nodes[0], 0);
951         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
952
953         let mut events = nodes[0].node.get_and_clear_pending_events();
954         assert_eq!(events.len(), 1);
955         match events.drain(..).next().unwrap() {
956                 crate::events::Event::ProbeSuccessful { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
957                         assert_eq!(payment_id, ev_pid);
958                         assert_eq!(payment_hash, ev_ph);
959                 },
960                 _ => panic!(),
961         };
962         assert!(!nodes[0].node.has_pending_payments());
963 }
964
965 #[test]
966 fn failed_probe_yields_event() {
967         let chanmon_cfgs = create_chanmon_cfgs(3);
968         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
969         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None, None]);
970         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
971
972         create_announced_chan_between_nodes(&nodes, 0, 1);
973         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 90000000);
974
975         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
976
977         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 9_998_000, 42);
978
979         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
980
981         // node[0] -- update_add_htlcs -> node[1]
982         check_added_monitors!(nodes[0], 1);
983         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
984         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
985         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
986         check_added_monitors!(nodes[1], 0);
987         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
988         expect_pending_htlcs_forwardable!(nodes[1]);
989
990         // node[0] <- update_fail_htlcs -- node[1]
991         check_added_monitors!(nodes[1], 1);
992         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
993         // Skip the PendingHTLCsForwardable event
994         let _events = nodes[1].node.get_and_clear_pending_events();
995         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
996         check_added_monitors!(nodes[0], 0);
997         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false);
998
999         let mut events = nodes[0].node.get_and_clear_pending_events();
1000         assert_eq!(events.len(), 1);
1001         match events.drain(..).next().unwrap() {
1002                 crate::events::Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1003                         assert_eq!(payment_id, ev_pid);
1004                         assert_eq!(payment_hash, ev_ph);
1005                 },
1006                 _ => panic!(),
1007         };
1008         assert!(!nodes[0].node.has_pending_payments());
1009 }
1010
1011 #[test]
1012 fn onchain_failed_probe_yields_event() {
1013         // Tests that an attempt to probe over a channel that is eventaully closed results in a failure
1014         // event.
1015         let chanmon_cfgs = create_chanmon_cfgs(3);
1016         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1017         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1018         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1019
1020         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1021         create_announced_chan_between_nodes(&nodes, 1, 2);
1022
1023         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 42);
1024
1025         // Send a dust HTLC, which will be treated as if it timed out once the channel hits the chain.
1026         let (route, _, _, _) = get_route_and_payment_hash!(&nodes[0], nodes[2], &payment_params, 1_000, 42);
1027         let (payment_hash, payment_id) = nodes[0].node.send_probe(route.paths[0].clone()).unwrap();
1028
1029         // node[0] -- update_add_htlcs -> node[1]
1030         check_added_monitors!(nodes[0], 1);
1031         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1032         let probe_event = SendEvent::from_commitment_update(nodes[1].node.get_our_node_id(), updates);
1033         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &probe_event.msgs[0]);
1034         check_added_monitors!(nodes[1], 0);
1035         commitment_signed_dance!(nodes[1], nodes[0], probe_event.commitment_msg, false);
1036         expect_pending_htlcs_forwardable!(nodes[1]);
1037
1038         check_added_monitors!(nodes[1], 1);
1039         let _ = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1040
1041         // Don't bother forwarding the HTLC onwards and just confirm the force-close transaction on
1042         // Node A, which after 6 confirmations should result in a probe failure event.
1043         let bs_txn = get_local_commitment_txn!(nodes[1], chan_id);
1044         confirm_transaction(&nodes[0], &bs_txn[0]);
1045         check_closed_broadcast!(&nodes[0], true);
1046         check_added_monitors!(nodes[0], 1);
1047
1048         let mut events = nodes[0].node.get_and_clear_pending_events();
1049         assert_eq!(events.len(), 2);
1050         let mut found_probe_failed = false;
1051         for event in events.drain(..) {
1052                 match event {
1053                         Event::ProbeFailed { payment_id: ev_pid, payment_hash: ev_ph, .. } => {
1054                                 assert_eq!(payment_id, ev_pid);
1055                                 assert_eq!(payment_hash, ev_ph);
1056                                 found_probe_failed = true;
1057                         },
1058                         Event::ChannelClosed { .. } => {},
1059                         _ => panic!(),
1060                 }
1061         }
1062         assert!(found_probe_failed);
1063         assert!(!nodes[0].node.has_pending_payments());
1064 }
1065
1066 #[test]
1067 fn claimed_send_payment_idempotent() {
1068         // Tests that `send_payment` (and friends) are (reasonably) idempotent.
1069         let chanmon_cfgs = create_chanmon_cfgs(2);
1070         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1071         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1072         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1073
1074         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1075
1076         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1077         let (first_payment_preimage, _, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1078
1079         macro_rules! check_send_rejected {
1080                 () => {
1081                         // If we try to resend a new payment with a different payment_hash but with the same
1082                         // payment_id, it should be rejected.
1083                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1084                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1085                         match send_result {
1086                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1087                                 _ => panic!("Unexpected send result: {:?}", send_result),
1088                         }
1089
1090                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1091                         // also be rejected.
1092                         let send_result = nodes[0].node.send_spontaneous_payment(
1093                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1094                         match send_result {
1095                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1096                                 _ => panic!("Unexpected send result: {:?}", send_result),
1097                         }
1098                 }
1099         }
1100
1101         check_send_rejected!();
1102
1103         // Claim the payment backwards, but note that the PaymentSent event is still pending and has
1104         // not been seen by the user. At this point, from the user perspective nothing has changed, so
1105         // we must remain just as idempotent as we were before.
1106         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1]]], false, first_payment_preimage);
1107
1108         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1109                 nodes[0].node.timer_tick_occurred();
1110         }
1111
1112         check_send_rejected!();
1113
1114         // Once the user sees and handles the `PaymentSent` event, we expect them to no longer call
1115         // `send_payment`, and our idempotency guarantees are off - they should have atomically marked
1116         // the payment complete. However, they could have called `send_payment` while the event was
1117         // being processed, leading to a race in our idempotency guarantees. Thus, even immediately
1118         // after the event is handled a duplicate payment should sitll be rejected.
1119         expect_payment_sent!(&nodes[0], first_payment_preimage, Some(0));
1120         check_send_rejected!();
1121
1122         // If relatively little time has passed, a duplicate payment should still fail.
1123         nodes[0].node.timer_tick_occurred();
1124         check_send_rejected!();
1125
1126         // However, after some time has passed (at least more than the one timer tick above), a
1127         // duplicate payment should go through, as ChannelManager should no longer have any remaining
1128         // references to the old payment data.
1129         for _ in 0..IDEMPOTENCY_TIMEOUT_TICKS {
1130                 nodes[0].node.timer_tick_occurred();
1131         }
1132
1133         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1134                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1135         check_added_monitors!(nodes[0], 1);
1136         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1137         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1138 }
1139
1140 #[test]
1141 fn abandoned_send_payment_idempotent() {
1142         // Tests that `send_payment` (and friends) allow duplicate PaymentIds immediately after
1143         // abandon_payment.
1144         let chanmon_cfgs = create_chanmon_cfgs(2);
1145         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1146         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1147         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1148
1149         create_announced_chan_between_nodes(&nodes, 0, 1).2;
1150
1151         let (route, second_payment_hash, second_payment_preimage, second_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
1152         let (_, first_payment_hash, _, payment_id) = send_along_route(&nodes[0], route.clone(), &[&nodes[1]], 100_000);
1153
1154         macro_rules! check_send_rejected {
1155                 () => {
1156                         // If we try to resend a new payment with a different payment_hash but with the same
1157                         // payment_id, it should be rejected.
1158                         let send_result = nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1159                                 RecipientOnionFields::secret_only(second_payment_secret), payment_id);
1160                         match send_result {
1161                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1162                                 _ => panic!("Unexpected send result: {:?}", send_result),
1163                         }
1164
1165                         // Further, if we try to send a spontaneous payment with the same payment_id it should
1166                         // also be rejected.
1167                         let send_result = nodes[0].node.send_spontaneous_payment(
1168                                 &route, None, RecipientOnionFields::spontaneous_empty(), payment_id);
1169                         match send_result {
1170                                 Err(PaymentSendFailure::DuplicatePayment) => {},
1171                                 _ => panic!("Unexpected send result: {:?}", send_result),
1172                         }
1173                 }
1174         }
1175
1176         check_send_rejected!();
1177
1178         nodes[1].node.fail_htlc_backwards(&first_payment_hash);
1179         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
1180
1181         // Until we abandon the payment upon path failure, no matter how many timer ticks pass, we still cannot reuse the
1182         // PaymentId.
1183         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1184                 nodes[0].node.timer_tick_occurred();
1185         }
1186         check_send_rejected!();
1187
1188         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, first_payment_hash, PaymentFailureReason::RecipientRejected);
1189
1190         // However, we can reuse the PaymentId immediately after we `abandon_payment` upon passing the
1191         // failed payment back.
1192         nodes[0].node.send_payment_with_route(&route, second_payment_hash,
1193                 RecipientOnionFields::secret_only(second_payment_secret), payment_id).unwrap();
1194         check_added_monitors!(nodes[0], 1);
1195         pass_along_route(&nodes[0], &[&[&nodes[1]]], 100_000, second_payment_hash, second_payment_secret);
1196         claim_payment(&nodes[0], &[&nodes[1]], second_payment_preimage);
1197 }
1198
1199 #[derive(PartialEq)]
1200 enum InterceptTest {
1201         Forward,
1202         Fail,
1203         Timeout,
1204 }
1205
1206 #[test]
1207 fn test_trivial_inflight_htlc_tracking(){
1208         // In this test, we test three scenarios:
1209         // (1) Sending + claiming a payment successfully should return `None` when querying InFlightHtlcs
1210         // (2) Sending a payment without claiming it should return the payment's value (500000) when querying InFlightHtlcs
1211         // (3) After we claim the payment sent in (2), InFlightHtlcs should return `None` for the query.
1212         let chanmon_cfgs = create_chanmon_cfgs(3);
1213         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1214         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1215         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1216
1217         let (_, _, chan_1_id, _) = create_announced_chan_between_nodes(&nodes, 0, 1);
1218         let (_, _, chan_2_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
1219
1220         // Send and claim the payment. Inflight HTLCs should be empty.
1221         let payment_hash = send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000).1;
1222         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1223         {
1224                 let mut node_0_per_peer_lock;
1225                 let mut node_0_peer_state_lock;
1226                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1227
1228                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1229                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1230                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1231                         channel_1.get_short_channel_id().unwrap()
1232                 );
1233                 assert_eq!(chan_1_used_liquidity, None);
1234         }
1235         {
1236                 let mut node_1_per_peer_lock;
1237                 let mut node_1_peer_state_lock;
1238                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1239
1240                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1241                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1242                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1243                         channel_2.get_short_channel_id().unwrap()
1244                 );
1245
1246                 assert_eq!(chan_2_used_liquidity, None);
1247         }
1248         let pending_payments = nodes[0].node.list_recent_payments();
1249         assert_eq!(pending_payments.len(), 1);
1250         assert_eq!(pending_payments[0], RecentPaymentDetails::Fulfilled { payment_hash: Some(payment_hash) });
1251
1252         // Remove fulfilled payment
1253         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1254                 nodes[0].node.timer_tick_occurred();
1255         }
1256
1257         // Send the payment, but do not claim it. Our inflight HTLCs should contain the pending payment.
1258         let (payment_preimage, payment_hash,  _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 500000);
1259         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1260         {
1261                 let mut node_0_per_peer_lock;
1262                 let mut node_0_peer_state_lock;
1263                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1264
1265                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1266                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1267                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1268                         channel_1.get_short_channel_id().unwrap()
1269                 );
1270                 // First hop accounts for expected 1000 msat fee
1271                 assert_eq!(chan_1_used_liquidity, Some(501000));
1272         }
1273         {
1274                 let mut node_1_per_peer_lock;
1275                 let mut node_1_peer_state_lock;
1276                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1277
1278                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1279                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1280                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1281                         channel_2.get_short_channel_id().unwrap()
1282                 );
1283
1284                 assert_eq!(chan_2_used_liquidity, Some(500000));
1285         }
1286         let pending_payments = nodes[0].node.list_recent_payments();
1287         assert_eq!(pending_payments.len(), 1);
1288         assert_eq!(pending_payments[0], RecentPaymentDetails::Pending { payment_hash, total_msat: 500000 });
1289
1290         // Now, let's claim the payment. This should result in the used liquidity to return `None`.
1291         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1292
1293         // Remove fulfilled payment
1294         for _ in 0..=IDEMPOTENCY_TIMEOUT_TICKS {
1295                 nodes[0].node.timer_tick_occurred();
1296         }
1297
1298         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1299         {
1300                 let mut node_0_per_peer_lock;
1301                 let mut node_0_peer_state_lock;
1302                 let channel_1 =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1_id);
1303
1304                 let chan_1_used_liquidity = inflight_htlcs.used_liquidity_msat(
1305                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1306                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1307                         channel_1.get_short_channel_id().unwrap()
1308                 );
1309                 assert_eq!(chan_1_used_liquidity, None);
1310         }
1311         {
1312                 let mut node_1_per_peer_lock;
1313                 let mut node_1_peer_state_lock;
1314                 let channel_2 =  get_channel_ref!(&nodes[1], nodes[2], node_1_per_peer_lock, node_1_peer_state_lock, chan_2_id);
1315
1316                 let chan_2_used_liquidity = inflight_htlcs.used_liquidity_msat(
1317                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()) ,
1318                         &NodeId::from_pubkey(&nodes[2].node.get_our_node_id()),
1319                         channel_2.get_short_channel_id().unwrap()
1320                 );
1321                 assert_eq!(chan_2_used_liquidity, None);
1322         }
1323
1324         let pending_payments = nodes[0].node.list_recent_payments();
1325         assert_eq!(pending_payments.len(), 0);
1326 }
1327
1328 #[test]
1329 fn test_holding_cell_inflight_htlcs() {
1330         let chanmon_cfgs = create_chanmon_cfgs(2);
1331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1334         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1335
1336         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
1337         let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
1338
1339         // Queue up two payments - one will be delivered right away, one immediately goes into the
1340         // holding cell as nodes[0] is AwaitingRAA.
1341         {
1342                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
1343                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
1344                 check_added_monitors!(nodes[0], 1);
1345                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1346                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1347                 check_added_monitors!(nodes[0], 0);
1348         }
1349
1350         let inflight_htlcs = node_chanmgrs[0].compute_inflight_htlcs();
1351
1352         {
1353                 let mut node_0_per_peer_lock;
1354                 let mut node_0_peer_state_lock;
1355                 let channel =  get_channel_ref!(&nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, channel_id);
1356
1357                 let used_liquidity = inflight_htlcs.used_liquidity_msat(
1358                         &NodeId::from_pubkey(&nodes[0].node.get_our_node_id()) ,
1359                         &NodeId::from_pubkey(&nodes[1].node.get_our_node_id()),
1360                         channel.get_short_channel_id().unwrap()
1361                 );
1362
1363                 assert_eq!(used_liquidity, Some(2000000));
1364         }
1365
1366         // Clear pending events so test doesn't throw a "Had excess message on node..." error
1367         nodes[0].node.get_and_clear_pending_msg_events();
1368 }
1369
1370 #[test]
1371 fn intercepted_payment() {
1372         // Test that detecting an intercept scid on payment forward will signal LDK to generate an
1373         // intercept event, which the LSP can then use to either (a) open a JIT channel to forward the
1374         // payment or (b) fail the payment.
1375         do_test_intercepted_payment(InterceptTest::Forward);
1376         do_test_intercepted_payment(InterceptTest::Fail);
1377         // Make sure that intercepted payments will be automatically failed back if too many blocks pass.
1378         do_test_intercepted_payment(InterceptTest::Timeout);
1379 }
1380
1381 fn do_test_intercepted_payment(test: InterceptTest) {
1382         let chanmon_cfgs = create_chanmon_cfgs(3);
1383         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1384
1385         let mut zero_conf_chan_config = test_default_channel_config();
1386         zero_conf_chan_config.manually_accept_inbound_channels = true;
1387         let mut intercept_forwards_config = test_default_channel_config();
1388         intercept_forwards_config.accept_intercept_htlcs = true;
1389         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(intercept_forwards_config), Some(zero_conf_chan_config)]);
1390
1391         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1392         let scorer = test_utils::TestScorer::new();
1393         let random_seed_bytes = chanmon_cfgs[0].keys_manager.get_secure_random_bytes();
1394
1395         let _ = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1396
1397         let amt_msat = 100_000;
1398         let intercept_scid = nodes[1].node.get_intercept_scid();
1399         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1400                 .with_route_hints(vec![
1401                         RouteHint(vec![RouteHintHop {
1402                                 src_node_id: nodes[1].node.get_our_node_id(),
1403                                 short_channel_id: intercept_scid,
1404                                 fees: RoutingFees {
1405                                         base_msat: 1000,
1406                                         proportional_millionths: 0,
1407                                 },
1408                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
1409                                 htlc_minimum_msat: None,
1410                                 htlc_maximum_msat: None,
1411                         }])
1412                 ])
1413                 .with_features(nodes[2].node.invoice_features());
1414         let route_params = RouteParameters {
1415                 payment_params,
1416                 final_value_msat: amt_msat,
1417         };
1418         let route = get_route(
1419                 &nodes[0].node.get_our_node_id(), &route_params.payment_params,
1420                 &nodes[0].network_graph.read_only(), None, route_params.final_value_msat,
1421                 route_params.payment_params.final_cltv_expiry_delta, nodes[0].logger, &scorer,
1422                 &random_seed_bytes,
1423         ).unwrap();
1424
1425         let (payment_hash, payment_secret) = nodes[2].node.create_inbound_payment(Some(amt_msat), 60 * 60, None).unwrap();
1426         nodes[0].node.send_payment_with_route(&route, payment_hash,
1427                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1428         let payment_event = {
1429                 {
1430                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1431                         assert_eq!(added_monitors.len(), 1);
1432                         added_monitors.clear();
1433                 }
1434                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1435                 assert_eq!(events.len(), 1);
1436                 SendEvent::from_event(events.remove(0))
1437         };
1438         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1439         commitment_signed_dance!(nodes[1], nodes[0], &payment_event.commitment_msg, false, true);
1440
1441         // Check that we generate the PaymentIntercepted event when an intercept forward is detected.
1442         let events = nodes[1].node.get_and_clear_pending_events();
1443         assert_eq!(events.len(), 1);
1444         let (intercept_id, expected_outbound_amount_msat) = match events[0] {
1445                 crate::events::Event::HTLCIntercepted {
1446                         intercept_id, expected_outbound_amount_msat, payment_hash: pmt_hash, inbound_amount_msat, requested_next_hop_scid: short_channel_id
1447                 } => {
1448                         assert_eq!(pmt_hash, payment_hash);
1449                         assert_eq!(inbound_amount_msat, route.get_total_amount() + route.get_total_fees());
1450                         assert_eq!(short_channel_id, intercept_scid);
1451                         (intercept_id, expected_outbound_amount_msat)
1452                 },
1453                 _ => panic!()
1454         };
1455
1456         // Check for unknown channel id error.
1457         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();
1458         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()) });
1459
1460         if test == InterceptTest::Fail {
1461                 // Ensure we can fail the intercepted payment back.
1462                 nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap();
1463                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::UnknownNextHop { requested_forward_scid: intercept_scid }]);
1464                 nodes[1].node.process_pending_htlc_forwards();
1465                 let update_fail = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1466                 check_added_monitors!(&nodes[1], 1);
1467                 assert!(update_fail.update_fail_htlcs.len() == 1);
1468                 let fail_msg = update_fail.update_fail_htlcs[0].clone();
1469                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1470                 commitment_signed_dance!(nodes[0], nodes[1], update_fail.commitment_signed, false);
1471
1472                 // Ensure the payment fails with the expected error.
1473                 let fail_conditions = PaymentFailedConditions::new()
1474                         .blamed_scid(intercept_scid)
1475                         .blamed_chan_closed(true)
1476                         .expected_htlc_error_data(0x4000 | 10, &[]);
1477                 expect_payment_failed_conditions(&nodes[0], payment_hash, false, fail_conditions);
1478         } else if test == InterceptTest::Forward {
1479                 // Check that we'll fail as expected when sending to a channel that isn't in `ChannelReady` yet.
1480                 let temp_chan_id = nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 100_000, 0, 42, None).unwrap();
1481                 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();
1482                 assert_eq!(unusable_chan_err , APIError::ChannelUnavailable { err: format!("Channel with id {} not fully established", log_bytes!(temp_chan_id)) });
1483                 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
1484
1485                 // Open the just-in-time channel so the payment can then be forwarded.
1486                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1487
1488                 // Finally, forward the intercepted payment through and claim it.
1489                 nodes[1].node.forward_intercepted_htlc(intercept_id, &channel_id, nodes[2].node.get_our_node_id(), expected_outbound_amount_msat).unwrap();
1490                 expect_pending_htlcs_forwardable!(nodes[1]);
1491
1492                 let payment_event = {
1493                         {
1494                                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
1495                                 assert_eq!(added_monitors.len(), 1);
1496                                 added_monitors.clear();
1497                         }
1498                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1499                         assert_eq!(events.len(), 1);
1500                         SendEvent::from_event(events.remove(0))
1501                 };
1502                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
1503                 commitment_signed_dance!(nodes[2], nodes[1], &payment_event.commitment_msg, false, true);
1504                 expect_pending_htlcs_forwardable!(nodes[2]);
1505
1506                 let payment_preimage = nodes[2].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
1507                 expect_payment_claimable!(&nodes[2], payment_hash, payment_secret, amt_msat, Some(payment_preimage), nodes[2].node.get_our_node_id());
1508                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[1], &nodes[2])[..]), false, payment_preimage);
1509                 let events = nodes[0].node.get_and_clear_pending_events();
1510                 assert_eq!(events.len(), 2);
1511                 match events[0] {
1512                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1513                                 assert_eq!(payment_preimage, *ev_preimage);
1514                                 assert_eq!(payment_hash, *ev_hash);
1515                                 assert_eq!(fee_paid_msat, &Some(1000));
1516                         },
1517                         _ => panic!("Unexpected event")
1518                 }
1519                 match events[1] {
1520                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1521                                 assert_eq!(hash, Some(payment_hash));
1522                         },
1523                         _ => panic!("Unexpected event")
1524                 }
1525         } else if test == InterceptTest::Timeout {
1526                 let mut block = Block {
1527                         header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: TxMerkleNode::all_zeros(), time: 42, bits: 42, nonce: 42 },
1528                         txdata: vec![],
1529                 };
1530                 connect_block(&nodes[0], &block);
1531                 connect_block(&nodes[1], &block);
1532                 for _ in 0..TEST_FINAL_CLTV {
1533                         block.header.prev_blockhash = block.block_hash();
1534                         connect_block(&nodes[0], &block);
1535                         connect_block(&nodes[1], &block);
1536                 }
1537                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::InvalidForward { requested_forward_scid: intercept_scid }]);
1538                 check_added_monitors!(nodes[1], 1);
1539                 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1540                 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
1541                 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
1542                 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
1543                 assert!(htlc_timeout_updates.update_fee.is_none());
1544
1545                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
1546                 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
1547                 expect_payment_failed!(nodes[0], payment_hash, false, 0x2000 | 2, []);
1548
1549                 // Check for unknown intercept id error.
1550                 let (_, channel_id) = open_zero_conf_channel(&nodes[1], &nodes[2], None);
1551                 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();
1552                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1553                 let unknown_intercept_id_err = nodes[1].node.fail_intercepted_htlc(intercept_id).unwrap_err();
1554                 assert_eq!(unknown_intercept_id_err , APIError::APIMisuseError { err: format!("Payment with intercept id {} not found", log_bytes!(intercept_id.0)) });
1555         }
1556 }
1557
1558 #[derive(PartialEq)]
1559 enum AutoRetry {
1560         Success,
1561         Spontaneous,
1562         FailAttempts,
1563         FailTimeout,
1564         FailOnRestart,
1565         FailOnRetry,
1566 }
1567
1568 #[test]
1569 fn automatic_retries() {
1570         do_automatic_retries(AutoRetry::Success);
1571         do_automatic_retries(AutoRetry::Spontaneous);
1572         do_automatic_retries(AutoRetry::FailAttempts);
1573         do_automatic_retries(AutoRetry::FailTimeout);
1574         do_automatic_retries(AutoRetry::FailOnRestart);
1575         do_automatic_retries(AutoRetry::FailOnRetry);
1576 }
1577 fn do_automatic_retries(test: AutoRetry) {
1578         // Test basic automatic payment retries in ChannelManager. See individual `test` variant comments
1579         // below.
1580         let chanmon_cfgs = create_chanmon_cfgs(3);
1581         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1582         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1583
1584         let persister;
1585         let new_chain_monitor;
1586         let node_0_deserialized;
1587
1588         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1589         let channel_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1).2;
1590         let channel_id_2 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1591
1592         // Marshall data to send the payment
1593         #[cfg(feature = "std")]
1594         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1595         #[cfg(not(feature = "std"))]
1596         let payment_expiry_secs = 60 * 60;
1597         let amt_msat = 1000;
1598         let mut invoice_features = InvoiceFeatures::empty();
1599         invoice_features.set_variable_length_onion_required();
1600         invoice_features.set_payment_secret_required();
1601         invoice_features.set_basic_mpp_optional();
1602         let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1603                 .with_expiry_time(payment_expiry_secs as u64)
1604                 .with_features(invoice_features);
1605         let route_params = RouteParameters {
1606                 payment_params,
1607                 final_value_msat: amt_msat,
1608         };
1609         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat);
1610
1611         macro_rules! pass_failed_attempt_with_retry_along_path {
1612                 ($failing_channel_id: expr, $expect_pending_htlcs_forwardable: expr) => {
1613                         // Send a payment attempt that fails due to lack of liquidity on the second hop
1614                         check_added_monitors!(nodes[0], 1);
1615                         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1616                         let mut update_add = update_0.update_add_htlcs[0].clone();
1617                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add);
1618                         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
1619                         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1620                         nodes[1].node.process_pending_htlc_forwards();
1621                         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],
1622                                 vec![HTLCDestination::NextHopChannel {
1623                                         node_id: Some(nodes[2].node.get_our_node_id()),
1624                                         channel_id: $failing_channel_id,
1625                                 }]);
1626                         nodes[1].node.process_pending_htlc_forwards();
1627                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1628                         check_added_monitors!(&nodes[1], 1);
1629                         assert!(update_1.update_fail_htlcs.len() == 1);
1630                         let fail_msg = update_1.update_fail_htlcs[0].clone();
1631                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
1632                         commitment_signed_dance!(nodes[0], nodes[1], update_1.commitment_signed, false);
1633
1634                         // Ensure the attempt fails and a new PendingHTLCsForwardable event is generated for the retry
1635                         let mut events = nodes[0].node.get_and_clear_pending_events();
1636                         assert_eq!(events.len(), 2);
1637                         match events[0] {
1638                                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
1639                                         assert_eq!(payment_hash, ev_payment_hash);
1640                                         assert_eq!(payment_failed_permanently, false);
1641                                 },
1642                                 _ => panic!("Unexpected event"),
1643                         }
1644                         if $expect_pending_htlcs_forwardable {
1645                                 match events[1] {
1646                                         Event::PendingHTLCsForwardable { .. } => {},
1647                                         _ => panic!("Unexpected event"),
1648                                 }
1649                         } else {
1650                                 match events[1] {
1651                                         Event::PaymentFailed { payment_hash: ev_payment_hash, .. } => {
1652                                                 assert_eq!(payment_hash, ev_payment_hash);
1653                                         },
1654                                         _ => panic!("Unexpected event"),
1655                                 }
1656                         }
1657                 }
1658         }
1659
1660         if test == AutoRetry::Success {
1661                 // Test that we can succeed on the first retry.
1662                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1663                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1664                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1665
1666                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1667                 // attempt, since the initial second hop channel will be excluded from pathfinding
1668                 create_announced_chan_between_nodes(&nodes, 1, 2);
1669
1670                 // We retry payments in `process_pending_htlc_forwards`
1671                 nodes[0].node.process_pending_htlc_forwards();
1672                 check_added_monitors!(nodes[0], 1);
1673                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1674                 assert_eq!(msg_events.len(), 1);
1675                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, Some(payment_secret), msg_events.pop().unwrap(), true, None);
1676                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1677         } else if test == AutoRetry::Spontaneous {
1678                 nodes[0].node.send_spontaneous_payment_with_retry(Some(payment_preimage),
1679                         RecipientOnionFields::spontaneous_empty(), PaymentId(payment_hash.0), route_params,
1680                         Retry::Attempts(1)).unwrap();
1681                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1682
1683                 // Open a new channel with liquidity on the second hop so we can find a route for the retry
1684                 // attempt, since the initial second hop channel will be excluded from pathfinding
1685                 create_announced_chan_between_nodes(&nodes, 1, 2);
1686
1687                 // We retry payments in `process_pending_htlc_forwards`
1688                 nodes[0].node.process_pending_htlc_forwards();
1689                 check_added_monitors!(nodes[0], 1);
1690                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1691                 assert_eq!(msg_events.len(), 1);
1692                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[2]], amt_msat, payment_hash, None, msg_events.pop().unwrap(), true, Some(payment_preimage));
1693                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage);
1694         } else if test == AutoRetry::FailAttempts {
1695                 // Ensure ChannelManager will not retry a payment if it has run out of payment attempts.
1696                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1697                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1698                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1699
1700                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1701                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1702                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1703
1704                 // We retry payments in `process_pending_htlc_forwards`
1705                 nodes[0].node.process_pending_htlc_forwards();
1706                 pass_failed_attempt_with_retry_along_path!(channel_id_3, false);
1707
1708                 // Ensure we won't retry a second time.
1709                 nodes[0].node.process_pending_htlc_forwards();
1710                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1711                 assert_eq!(msg_events.len(), 0);
1712         } else if test == AutoRetry::FailTimeout {
1713                 #[cfg(not(feature = "no-std"))] {
1714                         // Ensure ChannelManager will not retry a payment if it times out due to Retry::Timeout.
1715                         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1716                                 PaymentId(payment_hash.0), route_params, Retry::Timeout(Duration::from_secs(60))).unwrap();
1717                         pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1718
1719                         // Advance the time so the second attempt fails due to timeout.
1720                         SinceEpoch::advance(Duration::from_secs(61));
1721
1722                         // Make sure we don't retry again.
1723                         nodes[0].node.process_pending_htlc_forwards();
1724                         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1725                         assert_eq!(msg_events.len(), 0);
1726
1727                         let mut events = nodes[0].node.get_and_clear_pending_events();
1728                         assert_eq!(events.len(), 1);
1729                         match events[0] {
1730                                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1731                                         assert_eq!(payment_hash, *ev_payment_hash);
1732                                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1733                                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1734                                 },
1735                                 _ => panic!("Unexpected event"),
1736                         }
1737                 }
1738         } else if test == AutoRetry::FailOnRestart {
1739                 // Ensure ChannelManager will not retry a payment after restart, even if there were retry
1740                 // attempts remaining prior to restart.
1741                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1742                         PaymentId(payment_hash.0), route_params, Retry::Attempts(2)).unwrap();
1743                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1744
1745                 // Open a new channel with no liquidity on the second hop so we can find a (bad) route for
1746                 // the retry attempt, since the initial second hop channel will be excluded from pathfinding
1747                 let channel_id_3 = create_announced_chan_between_nodes(&nodes, 2, 1).2;
1748
1749                 // Ensure the first retry attempt fails, with 1 retry attempt remaining
1750                 nodes[0].node.process_pending_htlc_forwards();
1751                 pass_failed_attempt_with_retry_along_path!(channel_id_3, true);
1752
1753                 // Restart the node and ensure that ChannelManager does not use its remaining retry attempt
1754                 let node_encoded = nodes[0].node.encode();
1755                 let chan_1_monitor_serialized = get_monitor!(nodes[0], channel_id_1).encode();
1756                 reload_node!(nodes[0], node_encoded, &[&chan_1_monitor_serialized], persister, new_chain_monitor, node_0_deserialized);
1757
1758                 let mut events = nodes[0].node.get_and_clear_pending_events();
1759                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events, true);
1760                 // Make sure we don't retry again.
1761                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1762                 assert_eq!(msg_events.len(), 0);
1763
1764                 let mut events = nodes[0].node.get_and_clear_pending_events();
1765                 assert_eq!(events.len(), 1);
1766                 match events[0] {
1767                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1768                                 assert_eq!(payment_hash, *ev_payment_hash);
1769                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1770                                 assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
1771                         },
1772                         _ => panic!("Unexpected event"),
1773                 }
1774         } else if test == AutoRetry::FailOnRetry {
1775                 nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1776                         PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
1777                 pass_failed_attempt_with_retry_along_path!(channel_id_2, true);
1778
1779                 // We retry payments in `process_pending_htlc_forwards`. Since our channel closed, we should
1780                 // fail to find a route.
1781                 nodes[0].node.process_pending_htlc_forwards();
1782                 let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1783                 assert_eq!(msg_events.len(), 0);
1784
1785                 let mut events = nodes[0].node.get_and_clear_pending_events();
1786                 assert_eq!(events.len(), 1);
1787                 match events[0] {
1788                         Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
1789                                 assert_eq!(payment_hash, *ev_payment_hash);
1790                                 assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
1791                                 assert_eq!(PaymentFailureReason::RouteNotFound, ev_reason.unwrap());
1792                         },
1793                         _ => panic!("Unexpected event"),
1794                 }
1795         }
1796 }
1797
1798 #[test]
1799 fn auto_retry_partial_failure() {
1800         // Test that we'll retry appropriately on send partial failure and retry partial failure.
1801         let chanmon_cfgs = create_chanmon_cfgs(2);
1802         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1803         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1804         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1805
1806         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1807         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1808         let chan_3_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
1809
1810         // Marshall data to send the payment
1811         let amt_msat = 20_000;
1812         let (_, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
1813         #[cfg(feature = "std")]
1814         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
1815         #[cfg(not(feature = "std"))]
1816         let payment_expiry_secs = 60 * 60;
1817         let mut invoice_features = InvoiceFeatures::empty();
1818         invoice_features.set_variable_length_onion_required();
1819         invoice_features.set_payment_secret_required();
1820         invoice_features.set_basic_mpp_optional();
1821         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
1822                 .with_expiry_time(payment_expiry_secs as u64)
1823                 .with_features(invoice_features);
1824         let route_params = RouteParameters {
1825                 payment_params,
1826                 final_value_msat: amt_msat,
1827         };
1828
1829         // Ensure the first monitor update (for the initial send path1 over chan_1) succeeds, but the
1830         // second (for the initial send path2 over chan_2) fails.
1831         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1832         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1833         // Ensure third monitor update (for the retry1's path1 over chan_1) succeeds, but the fourth (for
1834         // the retry1's path2 over chan_3) fails, and monitor updates succeed after that.
1835         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1836         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
1837         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::Completed);
1838
1839         // Configure the initial send, retry1 and retry2's paths.
1840         let send_route = Route {
1841                 paths: vec![
1842                         Path { hops: vec![RouteHop {
1843                                 pubkey: nodes[1].node.get_our_node_id(),
1844                                 node_features: nodes[1].node.node_features(),
1845                                 short_channel_id: chan_1_id,
1846                                 channel_features: nodes[1].node.channel_features(),
1847                                 fee_msat: amt_msat / 2,
1848                                 cltv_expiry_delta: 100,
1849                         }], blinded_tail: None },
1850                         Path { hops: vec![RouteHop {
1851                                 pubkey: nodes[1].node.get_our_node_id(),
1852                                 node_features: nodes[1].node.node_features(),
1853                                 short_channel_id: chan_2_id,
1854                                 channel_features: nodes[1].node.channel_features(),
1855                                 fee_msat: amt_msat / 2,
1856                                 cltv_expiry_delta: 100,
1857                         }], blinded_tail: None },
1858                 ],
1859                 payment_params: Some(route_params.payment_params.clone()),
1860         };
1861         let retry_1_route = Route {
1862                 paths: vec![
1863                         Path { hops: vec![RouteHop {
1864                                 pubkey: nodes[1].node.get_our_node_id(),
1865                                 node_features: nodes[1].node.node_features(),
1866                                 short_channel_id: chan_1_id,
1867                                 channel_features: nodes[1].node.channel_features(),
1868                                 fee_msat: amt_msat / 4,
1869                                 cltv_expiry_delta: 100,
1870                         }], blinded_tail: None },
1871                         Path { hops: vec![RouteHop {
1872                                 pubkey: nodes[1].node.get_our_node_id(),
1873                                 node_features: nodes[1].node.node_features(),
1874                                 short_channel_id: chan_3_id,
1875                                 channel_features: nodes[1].node.channel_features(),
1876                                 fee_msat: amt_msat / 4,
1877                                 cltv_expiry_delta: 100,
1878                         }], blinded_tail: None },
1879                 ],
1880                 payment_params: Some(route_params.payment_params.clone()),
1881         };
1882         let retry_2_route = Route {
1883                 paths: vec![
1884                         Path { hops: vec![RouteHop {
1885                                 pubkey: nodes[1].node.get_our_node_id(),
1886                                 node_features: nodes[1].node.node_features(),
1887                                 short_channel_id: chan_1_id,
1888                                 channel_features: nodes[1].node.channel_features(),
1889                                 fee_msat: amt_msat / 4,
1890                                 cltv_expiry_delta: 100,
1891                         }], blinded_tail: None },
1892                 ],
1893                 payment_params: Some(route_params.payment_params.clone()),
1894         };
1895         nodes[0].router.expect_find_route(route_params.clone(), Ok(send_route));
1896         let mut payment_params = route_params.payment_params.clone();
1897         payment_params.previously_failed_channels.push(chan_2_id);
1898         nodes[0].router.expect_find_route(RouteParameters {
1899                         payment_params, final_value_msat: amt_msat / 2,
1900                 }, Ok(retry_1_route));
1901         let mut payment_params = route_params.payment_params.clone();
1902         payment_params.previously_failed_channels.push(chan_3_id);
1903         nodes[0].router.expect_find_route(RouteParameters {
1904                         payment_params, final_value_msat: amt_msat / 4,
1905                 }, Ok(retry_2_route));
1906
1907         // Send a payment that will partially fail on send, then partially fail on retry, then succeed.
1908         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
1909                 PaymentId(payment_hash.0), route_params, Retry::Attempts(3)).unwrap();
1910         let closed_chan_events = nodes[0].node.get_and_clear_pending_events();
1911         assert_eq!(closed_chan_events.len(), 4);
1912         match closed_chan_events[0] {
1913                 Event::ChannelClosed { .. } => {},
1914                 _ => panic!("Unexpected event"),
1915         }
1916         match closed_chan_events[1] {
1917                 Event::PaymentPathFailed { .. } => {},
1918                 _ => panic!("Unexpected event"),
1919         }
1920         match closed_chan_events[2] {
1921                 Event::ChannelClosed { .. } => {},
1922                 _ => panic!("Unexpected event"),
1923         }
1924         match closed_chan_events[3] {
1925                 Event::PaymentPathFailed { .. } => {},
1926                 _ => panic!("Unexpected event"),
1927         }
1928
1929         // Pass the first part of the payment along the path.
1930         check_added_monitors!(nodes[0], 5); // three outbound channel updates succeeded, two permanently failed
1931         let mut msg_events = nodes[0].node.get_and_clear_pending_msg_events();
1932
1933         // First message is the first update_add, remaining messages are broadcasting channel updates and
1934         // errors for the permfailed channels
1935         assert_eq!(msg_events.len(), 5);
1936         let mut payment_event = SendEvent::from_event(msg_events.remove(0));
1937
1938         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1939         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
1940         check_added_monitors!(nodes[1], 1);
1941         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1942
1943         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1944         check_added_monitors!(nodes[0], 1);
1945         let as_second_htlc_updates = SendEvent::from_node(&nodes[0]);
1946
1947         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1948         check_added_monitors!(nodes[0], 1);
1949         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1950
1951         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1952         check_added_monitors!(nodes[1], 1);
1953
1954         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[0]);
1955         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.msgs[1]);
1956         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_htlc_updates.commitment_msg);
1957         check_added_monitors!(nodes[1], 1);
1958         let (bs_second_raa, bs_second_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1959
1960         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1961         check_added_monitors!(nodes[0], 1);
1962
1963         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_cs);
1964         check_added_monitors!(nodes[0], 1);
1965         let as_second_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1966
1967         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1968         check_added_monitors!(nodes[1], 1);
1969
1970         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
1971         nodes[1].node.process_pending_htlc_forwards();
1972         expect_payment_claimable!(nodes[1], payment_hash, payment_secret, amt_msat);
1973         nodes[1].node.claim_funds(payment_preimage);
1974         expect_payment_claimed!(nodes[1], payment_hash, amt_msat);
1975         let bs_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1976         assert_eq!(bs_claim_update.update_fulfill_htlcs.len(), 1);
1977
1978         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_claim_update.update_fulfill_htlcs[0]);
1979         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_claim_update.commitment_signed);
1980         check_added_monitors!(nodes[0], 1);
1981         let (as_third_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1982
1983         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1984         check_added_monitors!(nodes[1], 4);
1985         let bs_second_claim_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1986
1987         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1988         check_added_monitors!(nodes[1], 1);
1989         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1990
1991         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1992         check_added_monitors!(nodes[0], 1);
1993
1994         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[0]);
1995         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.update_fulfill_htlcs[1]);
1996         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_claim_update.commitment_signed);
1997         check_added_monitors!(nodes[0], 1);
1998         let (as_fourth_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1999
2000         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_fourth_raa);
2001         check_added_monitors!(nodes[1], 1);
2002
2003         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2004         check_added_monitors!(nodes[1], 1);
2005         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2006
2007         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2008         check_added_monitors!(nodes[0], 1);
2009         expect_payment_sent!(nodes[0], payment_preimage);
2010 }
2011
2012 #[test]
2013 fn auto_retry_zero_attempts_send_error() {
2014         let chanmon_cfgs = create_chanmon_cfgs(2);
2015         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2016         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2017         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2018
2019         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2020         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2021
2022         // Marshall data to send the payment
2023         let amt_msat = 20_000;
2024         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2025         #[cfg(feature = "std")]
2026         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2027         #[cfg(not(feature = "std"))]
2028         let payment_expiry_secs = 60 * 60;
2029         let mut invoice_features = InvoiceFeatures::empty();
2030         invoice_features.set_variable_length_onion_required();
2031         invoice_features.set_payment_secret_required();
2032         invoice_features.set_basic_mpp_optional();
2033         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2034                 .with_expiry_time(payment_expiry_secs as u64)
2035                 .with_features(invoice_features);
2036         let route_params = RouteParameters {
2037                 payment_params,
2038                 final_value_msat: amt_msat,
2039         };
2040
2041         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::PermanentFailure);
2042         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2043                 PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
2044         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 2); // channel close messages
2045         let events = nodes[0].node.get_and_clear_pending_events();
2046         assert_eq!(events.len(), 3);
2047         if let Event::ChannelClosed { .. } = events[0] { } else { panic!(); }
2048         if let Event::PaymentPathFailed { .. } = events[1] { } else { panic!(); }
2049         if let Event::PaymentFailed { .. } = events[2] { } else { panic!(); }
2050         check_added_monitors!(nodes[0], 2);
2051 }
2052
2053 #[test]
2054 fn fails_paying_after_rejected_by_payee() {
2055         let chanmon_cfgs = create_chanmon_cfgs(2);
2056         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2057         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2058         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2059
2060         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
2061
2062         // Marshall data to send the payment
2063         let amt_msat = 20_000;
2064         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2065         #[cfg(feature = "std")]
2066         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2067         #[cfg(not(feature = "std"))]
2068         let payment_expiry_secs = 60 * 60;
2069         let mut invoice_features = InvoiceFeatures::empty();
2070         invoice_features.set_variable_length_onion_required();
2071         invoice_features.set_payment_secret_required();
2072         invoice_features.set_basic_mpp_optional();
2073         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2074                 .with_expiry_time(payment_expiry_secs as u64)
2075                 .with_features(invoice_features);
2076         let route_params = RouteParameters {
2077                 payment_params,
2078                 final_value_msat: amt_msat,
2079         };
2080
2081         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2082                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2083         check_added_monitors!(nodes[0], 1);
2084         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2085         assert_eq!(events.len(), 1);
2086         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
2087         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2088         check_added_monitors!(nodes[1], 0);
2089         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2090         expect_pending_htlcs_forwardable!(nodes[1]);
2091         expect_payment_claimable!(&nodes[1], payment_hash, payment_secret, amt_msat);
2092
2093         nodes[1].node.fail_htlc_backwards(&payment_hash);
2094         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], [HTLCDestination::FailedPayment { payment_hash }]);
2095         pass_failed_payment_back(&nodes[0], &[&[&nodes[1]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2096 }
2097
2098 #[test]
2099 fn retry_multi_path_single_failed_payment() {
2100         // Tests that we can/will retry after a single path of an MPP payment failed immediately
2101         let chanmon_cfgs = create_chanmon_cfgs(2);
2102         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2103         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2104         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2105
2106         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2107         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2108
2109         let amt_msat = 100_010_000;
2110
2111         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2112         #[cfg(feature = "std")]
2113         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2114         #[cfg(not(feature = "std"))]
2115         let payment_expiry_secs = 60 * 60;
2116         let mut invoice_features = InvoiceFeatures::empty();
2117         invoice_features.set_variable_length_onion_required();
2118         invoice_features.set_payment_secret_required();
2119         invoice_features.set_basic_mpp_optional();
2120         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2121                 .with_expiry_time(payment_expiry_secs as u64)
2122                 .with_features(invoice_features);
2123         let route_params = RouteParameters {
2124                 payment_params: payment_params.clone(),
2125                 final_value_msat: amt_msat,
2126         };
2127
2128         let chans = nodes[0].node.list_usable_channels();
2129         let mut route = Route {
2130                 paths: vec![
2131                         Path { hops: vec![RouteHop {
2132                                 pubkey: nodes[1].node.get_our_node_id(),
2133                                 node_features: nodes[1].node.node_features(),
2134                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2135                                 channel_features: nodes[1].node.channel_features(),
2136                                 fee_msat: 10_000,
2137                                 cltv_expiry_delta: 100,
2138                         }], blinded_tail: None },
2139                         Path { hops: vec![RouteHop {
2140                                 pubkey: nodes[1].node.get_our_node_id(),
2141                                 node_features: nodes[1].node.node_features(),
2142                                 short_channel_id: chans[1].short_channel_id.unwrap(),
2143                                 channel_features: nodes[1].node.channel_features(),
2144                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2145                                 cltv_expiry_delta: 100,
2146                         }], blinded_tail: None },
2147                 ],
2148                 payment_params: Some(payment_params),
2149         };
2150         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2151         // On retry, split the payment across both channels.
2152         route.paths[0].hops[0].fee_msat = 50_000_001;
2153         route.paths[1].hops[0].fee_msat = 50_000_000;
2154         let mut pay_params = route.payment_params.clone().unwrap();
2155         pay_params.previously_failed_channels.push(chans[1].short_channel_id.unwrap());
2156         nodes[0].router.expect_find_route(RouteParameters {
2157                         payment_params: pay_params,
2158                         // Note that the second request here requests the amount we originally failed to send,
2159                         // not the amount remaining on the full payment, which should be changed.
2160                         final_value_msat: 100_000_001,
2161                 }, Ok(route.clone()));
2162
2163         {
2164                 let scorer = chanmon_cfgs[0].scorer.lock().unwrap();
2165                 // The initial send attempt, 2 paths
2166                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 10_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2167                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 100_000_001, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2168                 // The retry, 2 paths. Ensure that the in-flight HTLC amount is factored in.
2169                 scorer.expect_usage(chans[0].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_001, inflight_htlc_msat: 10_000, effective_capacity: EffectiveCapacity::Unknown });
2170                 scorer.expect_usage(chans[1].short_channel_id.unwrap(), ChannelUsage { amount_msat: 50_000_000, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown });
2171         }
2172
2173         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2174                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2175         let events = nodes[0].node.get_and_clear_pending_events();
2176         assert_eq!(events.len(), 1);
2177         match events[0] {
2178                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2179                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2180                         short_channel_id: Some(expected_scid), .. } =>
2181                 {
2182                         assert_eq!(payment_hash, ev_payment_hash);
2183                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2184                         assert!(err_msg.contains("max HTLC"));
2185                 },
2186                 _ => panic!("Unexpected event"),
2187         }
2188         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2189         assert_eq!(htlc_msgs.len(), 2);
2190         check_added_monitors!(nodes[0], 2);
2191 }
2192
2193 #[test]
2194 fn immediate_retry_on_failure() {
2195         // Tests that we can/will retry immediately after a failure
2196         let chanmon_cfgs = create_chanmon_cfgs(2);
2197         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2198         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2199         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2200
2201         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2202         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2203
2204         let amt_msat = 100_000_001;
2205         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2206         #[cfg(feature = "std")]
2207         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2208         #[cfg(not(feature = "std"))]
2209         let payment_expiry_secs = 60 * 60;
2210         let mut invoice_features = InvoiceFeatures::empty();
2211         invoice_features.set_variable_length_onion_required();
2212         invoice_features.set_payment_secret_required();
2213         invoice_features.set_basic_mpp_optional();
2214         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2215                 .with_expiry_time(payment_expiry_secs as u64)
2216                 .with_features(invoice_features);
2217         let route_params = RouteParameters {
2218                 payment_params,
2219                 final_value_msat: amt_msat,
2220         };
2221
2222         let chans = nodes[0].node.list_usable_channels();
2223         let mut route = Route {
2224                 paths: vec![
2225                         Path { hops: vec![RouteHop {
2226                                 pubkey: nodes[1].node.get_our_node_id(),
2227                                 node_features: nodes[1].node.node_features(),
2228                                 short_channel_id: chans[0].short_channel_id.unwrap(),
2229                                 channel_features: nodes[1].node.channel_features(),
2230                                 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2231                                 cltv_expiry_delta: 100,
2232                         }], blinded_tail: None },
2233                 ],
2234                 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)),
2235         };
2236         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2237         // On retry, split the payment across both channels.
2238         route.paths.push(route.paths[0].clone());
2239         route.paths[0].hops[0].short_channel_id = chans[1].short_channel_id.unwrap();
2240         route.paths[0].hops[0].fee_msat = 50_000_000;
2241         route.paths[1].hops[0].fee_msat = 50_000_001;
2242         let mut pay_params = route_params.payment_params.clone();
2243         pay_params.previously_failed_channels.push(chans[0].short_channel_id.unwrap());
2244         nodes[0].router.expect_find_route(RouteParameters {
2245                         payment_params: pay_params, final_value_msat: amt_msat,
2246                 }, Ok(route.clone()));
2247
2248         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2249                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2250         let events = nodes[0].node.get_and_clear_pending_events();
2251         assert_eq!(events.len(), 1);
2252         match events[0] {
2253                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently: false,
2254                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { err: ref err_msg }},
2255                         short_channel_id: Some(expected_scid), .. } =>
2256                 {
2257                         assert_eq!(payment_hash, ev_payment_hash);
2258                         assert_eq!(expected_scid, route.paths[1].hops[0].short_channel_id);
2259                         assert!(err_msg.contains("max HTLC"));
2260                 },
2261                 _ => panic!("Unexpected event"),
2262         }
2263         let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2264         assert_eq!(htlc_msgs.len(), 2);
2265         check_added_monitors!(nodes[0], 2);
2266 }
2267
2268 #[test]
2269 fn no_extra_retries_on_back_to_back_fail() {
2270         // In a previous release, we had a race where we may exceed the payment retry count if we
2271         // get two failures in a row with the second indicating that all paths had failed (this field,
2272         // `all_paths_failed`, has since been removed).
2273         // Generally, when we give up trying to retry a payment, we don't know for sure what the
2274         // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2275         // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2276         // pending which we will see later. Thus, when we previously removed the retry tracking map
2277         // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2278         // retry entry even though more events for the same payment were still pending. This led to
2279         // us retrying a payment again even though we'd already given up on it.
2280         //
2281         // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2282         // is used to remove the payment retry counter entries instead. This tests for the specific
2283         // excess-retry case while also testing `PaymentFailed` generation.
2284
2285         let chanmon_cfgs = create_chanmon_cfgs(3);
2286         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2287         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2288         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2289
2290         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2291         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2292
2293         let amt_msat = 200_000_000;
2294         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], amt_msat);
2295         #[cfg(feature = "std")]
2296         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2297         #[cfg(not(feature = "std"))]
2298         let payment_expiry_secs = 60 * 60;
2299         let mut invoice_features = InvoiceFeatures::empty();
2300         invoice_features.set_variable_length_onion_required();
2301         invoice_features.set_payment_secret_required();
2302         invoice_features.set_basic_mpp_optional();
2303         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2304                 .with_expiry_time(payment_expiry_secs as u64)
2305                 .with_features(invoice_features);
2306         let route_params = RouteParameters {
2307                 payment_params,
2308                 final_value_msat: amt_msat,
2309         };
2310
2311         let mut route = Route {
2312                 paths: vec![
2313                         Path { hops: vec![RouteHop {
2314                                 pubkey: nodes[1].node.get_our_node_id(),
2315                                 node_features: nodes[1].node.node_features(),
2316                                 short_channel_id: chan_1_scid,
2317                                 channel_features: nodes[1].node.channel_features(),
2318                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2319                                 cltv_expiry_delta: 100,
2320                         }, RouteHop {
2321                                 pubkey: nodes[2].node.get_our_node_id(),
2322                                 node_features: nodes[2].node.node_features(),
2323                                 short_channel_id: chan_2_scid,
2324                                 channel_features: nodes[2].node.channel_features(),
2325                                 fee_msat: 100_000_000,
2326                                 cltv_expiry_delta: 100,
2327                         }], blinded_tail: None },
2328                         Path { hops: vec![RouteHop {
2329                                 pubkey: nodes[1].node.get_our_node_id(),
2330                                 node_features: nodes[1].node.node_features(),
2331                                 short_channel_id: chan_1_scid,
2332                                 channel_features: nodes[1].node.channel_features(),
2333                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2334                                 cltv_expiry_delta: 100,
2335                         }, RouteHop {
2336                                 pubkey: nodes[2].node.get_our_node_id(),
2337                                 node_features: nodes[2].node.node_features(),
2338                                 short_channel_id: chan_2_scid,
2339                                 channel_features: nodes[2].node.channel_features(),
2340                                 fee_msat: 100_000_000,
2341                                 cltv_expiry_delta: 100,
2342                         }], blinded_tail: None }
2343                 ],
2344                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2345         };
2346         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2347         let mut second_payment_params = route_params.payment_params.clone();
2348         second_payment_params.previously_failed_channels = vec![chan_2_scid, chan_2_scid];
2349         // On retry, we'll only return one path
2350         route.paths.remove(1);
2351         route.paths[0].hops[1].fee_msat = amt_msat;
2352         nodes[0].router.expect_find_route(RouteParameters {
2353                         payment_params: second_payment_params,
2354                         final_value_msat: amt_msat,
2355                 }, Ok(route.clone()));
2356
2357         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2358                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2359         let htlc_updates = SendEvent::from_node(&nodes[0]);
2360         check_added_monitors!(nodes[0], 1);
2361         assert_eq!(htlc_updates.msgs.len(), 1);
2362
2363         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2364         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2365         check_added_monitors!(nodes[1], 1);
2366         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2367
2368         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2369         check_added_monitors!(nodes[0], 1);
2370         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2371
2372         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2373         check_added_monitors!(nodes[0], 1);
2374         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2375
2376         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2377         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2378         check_added_monitors!(nodes[1], 1);
2379         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2380
2381         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2382         check_added_monitors!(nodes[1], 1);
2383         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2384
2385         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2386         check_added_monitors!(nodes[0], 1);
2387
2388         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2389         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2390         check_added_monitors!(nodes[0], 1);
2391         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2392
2393         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2394         check_added_monitors!(nodes[1], 1);
2395         let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2396
2397         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2398         check_added_monitors!(nodes[1], 1);
2399         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2400
2401         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2402         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2403         check_added_monitors!(nodes[0], 1);
2404
2405         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2406         check_added_monitors!(nodes[0], 1);
2407         let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2408
2409         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2410         check_added_monitors!(nodes[1], 1);
2411         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2412         check_added_monitors!(nodes[1], 1);
2413         let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2414
2415         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2416         check_added_monitors!(nodes[0], 1);
2417
2418         // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2419         // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2420         // with it set.
2421         //
2422         // Previously, we retried payments in an event consumer, which would retry each
2423         // `PaymentPathFailed` individually. In that setup, we had retried the payment in response to
2424         // the first `PaymentPathFailed`, then seen the second `PaymentPathFailed` with
2425         // `all_paths_failed` set and assumed the payment was completely failed. We ultimately fixed it
2426         // by adding the `PaymentFailed` event.
2427         //
2428         // Because we now retry payments as a batch, we simply return a single-path route in the
2429         // second, batched, request, have that fail, ensure the payment was abandoned.
2430         let mut events = nodes[0].node.get_and_clear_pending_events();
2431         assert_eq!(events.len(), 3);
2432         match events[0] {
2433                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2434                         assert_eq!(payment_hash, ev_payment_hash);
2435                         assert_eq!(payment_failed_permanently, false);
2436                 },
2437                 _ => panic!("Unexpected event"),
2438         }
2439         match events[1] {
2440                 Event::PendingHTLCsForwardable { .. } => {},
2441                 _ => panic!("Unexpected event"),
2442         }
2443         match events[2] {
2444                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2445                         assert_eq!(payment_hash, ev_payment_hash);
2446                         assert_eq!(payment_failed_permanently, false);
2447                 },
2448                 _ => panic!("Unexpected event"),
2449         }
2450
2451         nodes[0].node.process_pending_htlc_forwards();
2452         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2453         check_added_monitors!(nodes[0], 1);
2454
2455         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2456         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2457         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2458         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2459         commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2460
2461         let mut events = nodes[0].node.get_and_clear_pending_events();
2462         assert_eq!(events.len(), 2);
2463         match events[0] {
2464                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2465                         assert_eq!(payment_hash, ev_payment_hash);
2466                         assert_eq!(payment_failed_permanently, false);
2467                 },
2468                 _ => panic!("Unexpected event"),
2469         }
2470         match events[1] {
2471                 Event::PaymentFailed { payment_hash: ref ev_payment_hash, payment_id: ref ev_payment_id, reason: ref ev_reason } => {
2472                         assert_eq!(payment_hash, *ev_payment_hash);
2473                         assert_eq!(PaymentId(payment_hash.0), *ev_payment_id);
2474                         assert_eq!(PaymentFailureReason::RetriesExhausted, ev_reason.unwrap());
2475                 },
2476                 _ => panic!("Unexpected event"),
2477         }
2478 }
2479
2480 #[test]
2481 fn test_simple_partial_retry() {
2482         // In the first version of the in-`ChannelManager` payment retries, retries were sent for the
2483         // full amount of the payment, rather than only the missing amount. Here we simply test for
2484         // this by sending a payment with two parts, failing one, and retrying the second. Note that
2485         // `TestRouter` will check that the `RouteParameters` (which contain the amount) matches the
2486         // request.
2487         let chanmon_cfgs = create_chanmon_cfgs(3);
2488         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2489         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2490         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2491
2492         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2493         let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2494
2495         let amt_msat = 200_000_000;
2496         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2497         #[cfg(feature = "std")]
2498         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2499         #[cfg(not(feature = "std"))]
2500         let payment_expiry_secs = 60 * 60;
2501         let mut invoice_features = InvoiceFeatures::empty();
2502         invoice_features.set_variable_length_onion_required();
2503         invoice_features.set_payment_secret_required();
2504         invoice_features.set_basic_mpp_optional();
2505         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2506                 .with_expiry_time(payment_expiry_secs as u64)
2507                 .with_features(invoice_features);
2508         let route_params = RouteParameters {
2509                 payment_params,
2510                 final_value_msat: amt_msat,
2511         };
2512
2513         let mut route = Route {
2514                 paths: vec![
2515                         Path { hops: vec![RouteHop {
2516                                 pubkey: nodes[1].node.get_our_node_id(),
2517                                 node_features: nodes[1].node.node_features(),
2518                                 short_channel_id: chan_1_scid,
2519                                 channel_features: nodes[1].node.channel_features(),
2520                                 fee_msat: 0, // nodes[1] will fail the payment as we don't pay its fee
2521                                 cltv_expiry_delta: 100,
2522                         }, RouteHop {
2523                                 pubkey: nodes[2].node.get_our_node_id(),
2524                                 node_features: nodes[2].node.node_features(),
2525                                 short_channel_id: chan_2_scid,
2526                                 channel_features: nodes[2].node.channel_features(),
2527                                 fee_msat: 100_000_000,
2528                                 cltv_expiry_delta: 100,
2529                         }], blinded_tail: None },
2530                         Path { hops: vec![RouteHop {
2531                                 pubkey: nodes[1].node.get_our_node_id(),
2532                                 node_features: nodes[1].node.node_features(),
2533                                 short_channel_id: chan_1_scid,
2534                                 channel_features: nodes[1].node.channel_features(),
2535                                 fee_msat: 100_000,
2536                                 cltv_expiry_delta: 100,
2537                         }, RouteHop {
2538                                 pubkey: nodes[2].node.get_our_node_id(),
2539                                 node_features: nodes[2].node.node_features(),
2540                                 short_channel_id: chan_2_scid,
2541                                 channel_features: nodes[2].node.channel_features(),
2542                                 fee_msat: 100_000_000,
2543                                 cltv_expiry_delta: 100,
2544                         }], blinded_tail: None }
2545                 ],
2546                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2547         };
2548         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2549         let mut second_payment_params = route_params.payment_params.clone();
2550         second_payment_params.previously_failed_channels = vec![chan_2_scid];
2551         // On retry, we'll only be asked for one path (or 100k sats)
2552         route.paths.remove(0);
2553         nodes[0].router.expect_find_route(RouteParameters {
2554                         payment_params: second_payment_params,
2555                         final_value_msat: amt_msat / 2,
2556                 }, Ok(route.clone()));
2557
2558         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2559                 PaymentId(payment_hash.0), route_params, Retry::Attempts(1)).unwrap();
2560         let htlc_updates = SendEvent::from_node(&nodes[0]);
2561         check_added_monitors!(nodes[0], 1);
2562         assert_eq!(htlc_updates.msgs.len(), 1);
2563
2564         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2565         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2566         check_added_monitors!(nodes[1], 1);
2567         let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2568
2569         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2570         check_added_monitors!(nodes[0], 1);
2571         let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2572
2573         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2574         check_added_monitors!(nodes[0], 1);
2575         let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2576
2577         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2578         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2579         check_added_monitors!(nodes[1], 1);
2580         let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2581
2582         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2583         check_added_monitors!(nodes[1], 1);
2584         let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2585
2586         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2587         check_added_monitors!(nodes[0], 1);
2588
2589         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2590         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2591         check_added_monitors!(nodes[0], 1);
2592         let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2593
2594         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2595         check_added_monitors!(nodes[1], 1);
2596
2597         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2598         check_added_monitors!(nodes[1], 1);
2599
2600         let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2601
2602         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2603         check_added_monitors!(nodes[0], 1);
2604
2605         let mut events = nodes[0].node.get_and_clear_pending_events();
2606         assert_eq!(events.len(), 2);
2607         match events[0] {
2608                 Event::PaymentPathFailed { payment_hash: ev_payment_hash, payment_failed_permanently, ..  } => {
2609                         assert_eq!(payment_hash, ev_payment_hash);
2610                         assert_eq!(payment_failed_permanently, false);
2611                 },
2612                 _ => panic!("Unexpected event"),
2613         }
2614         match events[1] {
2615                 Event::PendingHTLCsForwardable { .. } => {},
2616                 _ => panic!("Unexpected event"),
2617         }
2618
2619         nodes[0].node.process_pending_htlc_forwards();
2620         let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2621         check_added_monitors!(nodes[0], 1);
2622
2623         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2624         commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2625
2626         expect_pending_htlcs_forwardable!(nodes[1]);
2627         check_added_monitors!(nodes[1], 1);
2628
2629         let bs_forward_update = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
2630         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[0]);
2631         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &bs_forward_update.update_add_htlcs[1]);
2632         commitment_signed_dance!(nodes[2], nodes[1], &bs_forward_update.commitment_signed, false);
2633
2634         expect_pending_htlcs_forwardable!(nodes[2]);
2635         expect_payment_claimable!(nodes[2], payment_hash, payment_secret, amt_msat);
2636 }
2637
2638 #[test]
2639 #[cfg(feature = "std")]
2640 fn test_threaded_payment_retries() {
2641         // In the first version of the in-`ChannelManager` payment retries, retries weren't limited to
2642         // a single thread and would happily let multiple threads run retries at the same time. Because
2643         // retries are done by first calculating the amount we need to retry, then dropping the
2644         // relevant lock, then actually sending, we would happily let multiple threads retry the same
2645         // amount at the same time, overpaying our original HTLC!
2646         let chanmon_cfgs = create_chanmon_cfgs(4);
2647         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2648         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2649         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2650
2651         // There is one mitigating guardrail when retrying payments - we can never over-pay by more
2652         // than 10% of the original value. Thus, we want all our retries to be below that. In order to
2653         // keep things simple, we route one HTLC for 0.1% of the payment over channel 1 and the rest
2654         // out over channel 3+4. This will let us ignore 99% of the payment value and deal with only
2655         // our channel.
2656         let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2657         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000_000, 0);
2658         let chan_3_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000_000, 0).0.contents.short_channel_id;
2659         let chan_4_scid = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 10_000_000, 0).0.contents.short_channel_id;
2660
2661         let amt_msat = 100_000_000;
2662         let (_, payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[2], amt_msat);
2663         #[cfg(feature = "std")]
2664         let payment_expiry_secs = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() + 60 * 60;
2665         #[cfg(not(feature = "std"))]
2666         let payment_expiry_secs = 60 * 60;
2667         let mut invoice_features = InvoiceFeatures::empty();
2668         invoice_features.set_variable_length_onion_required();
2669         invoice_features.set_payment_secret_required();
2670         invoice_features.set_basic_mpp_optional();
2671         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
2672                 .with_expiry_time(payment_expiry_secs as u64)
2673                 .with_features(invoice_features);
2674         let mut route_params = RouteParameters {
2675                 payment_params,
2676                 final_value_msat: amt_msat,
2677         };
2678
2679         let mut route = Route {
2680                 paths: vec![
2681                         Path { hops: vec![RouteHop {
2682                                 pubkey: nodes[1].node.get_our_node_id(),
2683                                 node_features: nodes[1].node.node_features(),
2684                                 short_channel_id: chan_1_scid,
2685                                 channel_features: nodes[1].node.channel_features(),
2686                                 fee_msat: 0,
2687                                 cltv_expiry_delta: 100,
2688                         }, RouteHop {
2689                                 pubkey: nodes[3].node.get_our_node_id(),
2690                                 node_features: nodes[2].node.node_features(),
2691                                 short_channel_id: 42, // Set a random SCID which nodes[1] will fail as unknown
2692                                 channel_features: nodes[2].node.channel_features(),
2693                                 fee_msat: amt_msat / 1000,
2694                                 cltv_expiry_delta: 100,
2695                         }], blinded_tail: None },
2696                         Path { hops: vec![RouteHop {
2697                                 pubkey: nodes[2].node.get_our_node_id(),
2698                                 node_features: nodes[2].node.node_features(),
2699                                 short_channel_id: chan_3_scid,
2700                                 channel_features: nodes[2].node.channel_features(),
2701                                 fee_msat: 100_000,
2702                                 cltv_expiry_delta: 100,
2703                         }, RouteHop {
2704                                 pubkey: nodes[3].node.get_our_node_id(),
2705                                 node_features: nodes[3].node.node_features(),
2706                                 short_channel_id: chan_4_scid,
2707                                 channel_features: nodes[3].node.channel_features(),
2708                                 fee_msat: amt_msat - amt_msat / 1000,
2709                                 cltv_expiry_delta: 100,
2710                         }], blinded_tail: None }
2711                 ],
2712                 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)),
2713         };
2714         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2715
2716         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2717                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(0xdeadbeef)).unwrap();
2718         check_added_monitors!(nodes[0], 2);
2719         let mut send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2720         assert_eq!(send_msg_events.len(), 2);
2721         send_msg_events.retain(|msg|
2722                 if let MessageSendEvent::UpdateHTLCs { node_id, .. } = msg {
2723                         // Drop the commitment update for nodes[2], we can just let that one sit pending
2724                         // forever.
2725                         *node_id == nodes[1].node.get_our_node_id()
2726                 } else { panic!(); }
2727         );
2728
2729         // from here on out, the retry `RouteParameters` amount will be amt/1000
2730         route_params.final_value_msat /= 1000;
2731         route.paths.pop();
2732
2733         let end_time = Instant::now() + Duration::from_secs(1);
2734         macro_rules! thread_body { () => { {
2735                 // We really want std::thread::scope, but its not stable until 1.63. Until then, we get unsafe.
2736                 let node_ref = NodePtr::from_node(&nodes[0]);
2737                 move || {
2738                         let node_a = unsafe { &*node_ref.0 };
2739                         while Instant::now() < end_time {
2740                                 node_a.node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2741                                 // Ignore if we have any pending events, just always pretend we just got a
2742                                 // PendingHTLCsForwardable
2743                                 node_a.node.process_pending_htlc_forwards();
2744                         }
2745                 }
2746         } } }
2747         let mut threads = Vec::new();
2748         for _ in 0..16 { threads.push(std::thread::spawn(thread_body!())); }
2749
2750         // Back in the main thread, poll pending messages and make sure that we never have more than
2751         // one HTLC pending at a time. Note that the commitment_signed_dance will fail horribly if
2752         // there are HTLC messages shoved in while its running. This allows us to test that we never
2753         // generate an additional update_add_htlc until we've fully failed the first.
2754         let mut previously_failed_channels = Vec::new();
2755         loop {
2756                 assert_eq!(send_msg_events.len(), 1);
2757                 let send_event = SendEvent::from_event(send_msg_events.pop().unwrap());
2758                 assert_eq!(send_event.msgs.len(), 1);
2759
2760                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
2761                 commitment_signed_dance!(nodes[1], nodes[0], send_event.commitment_msg, false, true);
2762
2763                 // Note that we only push one route into `expect_find_route` at a time, because that's all
2764                 // the retries (should) need. If the bug is reintroduced "real" routes may be selected, but
2765                 // we should still ultimately fail for the same reason - because we're trying to send too
2766                 // many HTLCs at once.
2767                 let mut new_route_params = route_params.clone();
2768                 previously_failed_channels.push(route.paths[0].hops[1].short_channel_id);
2769                 new_route_params.payment_params.previously_failed_channels = previously_failed_channels.clone();
2770                 route.paths[0].hops[1].short_channel_id += 1;
2771                 nodes[0].router.expect_find_route(new_route_params, Ok(route.clone()));
2772
2773                 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2774                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
2775                 // The "normal" commitment_signed_dance delivers the final RAA and then calls
2776                 // `check_added_monitors` to ensure only the one RAA-generated monitor update was created.
2777                 // This races with our other threads which may generate an add-HTLCs commitment update via
2778                 // `process_pending_htlc_forwards`. Instead, we defer the monitor update check until after
2779                 // *we've* called `process_pending_htlc_forwards` when its guaranteed to have two updates.
2780                 let last_raa = commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true, false, true);
2781                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &last_raa);
2782
2783                 let cur_time = Instant::now();
2784                 if cur_time > end_time {
2785                         for thread in threads.drain(..) { thread.join().unwrap(); }
2786                 }
2787
2788                 // Make sure we have some events to handle when we go around...
2789                 nodes[0].node.get_and_clear_pending_events(); // wipe the PendingHTLCsForwardable
2790                 nodes[0].node.process_pending_htlc_forwards();
2791                 send_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
2792                 check_added_monitors!(nodes[0], 2);
2793
2794                 if cur_time > end_time {
2795                         break;
2796                 }
2797         }
2798 }
2799
2800 fn do_no_missing_sent_on_midpoint_reload(persist_manager_with_payment: bool) {
2801         // Test that if we reload in the middle of an HTLC claim commitment signed dance we'll still
2802         // receive the PaymentSent event even if the ChannelManager had no idea about the payment when
2803         // it was last persisted.
2804         let chanmon_cfgs = create_chanmon_cfgs(2);
2805         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2806         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2807         let (persister_a, persister_b, persister_c);
2808         let (chain_monitor_a, chain_monitor_b, chain_monitor_c);
2809         let (nodes_0_deserialized, nodes_0_deserialized_b, nodes_0_deserialized_c);
2810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2811
2812         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
2813
2814         let mut nodes_0_serialized = Vec::new();
2815         if !persist_manager_with_payment {
2816                 nodes_0_serialized = nodes[0].node.encode();
2817         }
2818
2819         let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
2820
2821         if persist_manager_with_payment {
2822                 nodes_0_serialized = nodes[0].node.encode();
2823         }
2824
2825         nodes[1].node.claim_funds(our_payment_preimage);
2826         check_added_monitors!(nodes[1], 1);
2827         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
2828
2829         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2830         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2831         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &updates.commitment_signed);
2832         check_added_monitors!(nodes[0], 1);
2833
2834         // The ChannelMonitor should always be the latest version, as we're required to persist it
2835         // during the commitment signed handling.
2836         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2837         reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized], persister_a, chain_monitor_a, nodes_0_deserialized);
2838
2839         let events = nodes[0].node.get_and_clear_pending_events();
2840         assert_eq!(events.len(), 2);
2841         if let Event::ChannelClosed { reason: ClosureReason::OutdatedChannelManager, .. } = events[0] {} else { panic!(); }
2842         if let Event::PaymentSent { payment_preimage, .. } = events[1] { assert_eq!(payment_preimage, our_payment_preimage); } else { panic!(); }
2843         // Note that we don't get a PaymentPathSuccessful here as we leave the HTLC pending to avoid
2844         // the double-claim that would otherwise appear at the end of this test.
2845         nodes[0].node.timer_tick_occurred();
2846         let as_broadcasted_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2847         assert_eq!(as_broadcasted_txn.len(), 1);
2848
2849         // Ensure that, even after some time, if we restart we still include *something* in the current
2850         // `ChannelManager` which prevents a `PaymentFailed` when we restart even if pending resolved
2851         // payments have since been timed out thanks to `IDEMPOTENCY_TIMEOUT_TICKS`.
2852         // A naive implementation of the fix here would wipe the pending payments set, causing a
2853         // failure event when we restart.
2854         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2855
2856         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2857         reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_b, chain_monitor_b, nodes_0_deserialized_b);
2858         let events = nodes[0].node.get_and_clear_pending_events();
2859         assert!(events.is_empty());
2860
2861         // Ensure that we don't generate any further events even after the channel-closing commitment
2862         // transaction is confirmed on-chain.
2863         confirm_transaction(&nodes[0], &as_broadcasted_txn[0]);
2864         for _ in 0..(IDEMPOTENCY_TIMEOUT_TICKS * 2) { nodes[0].node.timer_tick_occurred(); }
2865
2866         let events = nodes[0].node.get_and_clear_pending_events();
2867         assert!(events.is_empty());
2868
2869         let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
2870         reload_node!(nodes[0], test_default_channel_config(), &nodes[0].node.encode(), &[&chan_0_monitor_serialized], persister_c, chain_monitor_c, nodes_0_deserialized_c);
2871         let events = nodes[0].node.get_and_clear_pending_events();
2872         assert!(events.is_empty());
2873 }
2874
2875 #[test]
2876 fn no_missing_sent_on_midpoint_reload() {
2877         do_no_missing_sent_on_midpoint_reload(false);
2878         do_no_missing_sent_on_midpoint_reload(true);
2879 }
2880
2881 fn do_claim_from_closed_chan(fail_payment: bool) {
2882         // Previously, LDK would refuse to claim a payment if a channel on which the payment was
2883         // received had been closed between when the HTLC was received and when we went to claim it.
2884         // This makes sense in the payment case - why pay an on-chain fee to claim the HTLC when
2885         // presumably the sender may retry later. Long ago it also reduced total code in the claim
2886         // pipeline.
2887         //
2888         // However, this doesn't make sense if you're trying to do an atomic swap or some other
2889         // protocol that requires atomicity with some other action - if your money got claimed
2890         // elsewhere you need to be able to claim the HTLC in lightning no matter what. Further, this
2891         // is an over-optimization - there should be a very, very low likelihood that a channel closes
2892         // between when we receive the last HTLC for a payment and the user goes to claim the payment.
2893         // Since we now have code to handle this anyway we should allow it.
2894
2895         // Build 4 nodes and send an MPP payment across two paths. By building a route manually set the
2896         // CLTVs on the paths to different value resulting in a different claim deadline.
2897         let chanmon_cfgs = create_chanmon_cfgs(4);
2898         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
2899         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
2900         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
2901
2902         create_announced_chan_between_nodes(&nodes, 0, 1);
2903         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
2904         let chan_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
2905         create_announced_chan_between_nodes(&nodes, 2, 3);
2906
2907         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3]);
2908         let mut route_params = RouteParameters {
2909                 payment_params: PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
2910                         .with_features(nodes[1].node.invoice_features()),
2911                 final_value_msat: 10_000_000,
2912         };
2913         let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
2914                 None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
2915         // Make sure the route is ordered as the B->D path before C->D
2916         route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
2917                 std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
2918
2919         // Note that we add an extra 1 in the send pipeline to compensate for any blocks found while
2920         // the HTLC is being relayed.
2921         route.paths[0].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 8;
2922         route.paths[1].hops[1].cltv_expiry_delta = TEST_FINAL_CLTV + 12;
2923         let final_cltv = nodes[0].best_block_info().1 + TEST_FINAL_CLTV + 8 + 1;
2924
2925         nodes[0].router.expect_find_route(route_params.clone(), Ok(route.clone()));
2926         nodes[0].node.send_payment(payment_hash, RecipientOnionFields::secret_only(payment_secret),
2927                 PaymentId(payment_hash.0), route_params.clone(), Retry::Attempts(1)).unwrap();
2928         check_added_monitors(&nodes[0], 2);
2929         let mut send_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2930         send_msgs.sort_by(|a, _| {
2931                 let a_node_id =
2932                         if let MessageSendEvent::UpdateHTLCs { node_id, .. } = a { node_id } else { panic!() };
2933                 let node_b_id = nodes[1].node.get_our_node_id();
2934                 if *a_node_id == node_b_id { std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater }
2935         });
2936
2937         assert_eq!(send_msgs.len(), 2);
2938         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 10_000_000,
2939                 payment_hash, Some(payment_secret), send_msgs.remove(0), false, None);
2940         let receive_event = pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 10_000_000,
2941                 payment_hash, Some(payment_secret), send_msgs.remove(0), true, None);
2942
2943         match receive_event.unwrap() {
2944                 Event::PaymentClaimable { claim_deadline, .. } => {
2945                         assert_eq!(claim_deadline.unwrap(), final_cltv - HTLC_FAIL_BACK_BUFFER);
2946                 },
2947                 _ => panic!(),
2948         }
2949
2950         // Ensure that the claim_deadline is correct, with the payment failing at exactly the given
2951         // height.
2952         connect_blocks(&nodes[3], final_cltv - HTLC_FAIL_BACK_BUFFER - nodes[3].best_block_info().1
2953                 - if fail_payment { 0 } else { 2 });
2954         if fail_payment {
2955                 // We fail the HTLC on the A->B->D path first as it expires 4 blocks earlier. We go ahead
2956                 // and expire both immediately, though, by connecting another 4 blocks.
2957                 let reason = HTLCDestination::FailedPayment { payment_hash };
2958                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason.clone()]);
2959                 connect_blocks(&nodes[3], 4);
2960                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(&nodes[3], [reason]);
2961                 pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
2962         } else {
2963                 nodes[1].node.force_close_broadcasting_latest_txn(&chan_bd, &nodes[3].node.get_our_node_id()).unwrap();
2964                 check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false);
2965                 check_closed_broadcast(&nodes[1], 1, true);
2966                 let bs_tx = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2967                 assert_eq!(bs_tx.len(), 1);
2968
2969                 mine_transaction(&nodes[3], &bs_tx[0]);
2970                 check_added_monitors(&nodes[3], 1);
2971                 check_closed_broadcast(&nodes[3], 1, true);
2972                 check_closed_event(&nodes[3], 1, ClosureReason::CommitmentTxConfirmed, false);
2973
2974                 nodes[3].node.claim_funds(payment_preimage);
2975                 check_added_monitors(&nodes[3], 2);
2976                 expect_payment_claimed!(nodes[3], payment_hash, 10_000_000);
2977
2978                 let ds_tx = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2979                 assert_eq!(ds_tx.len(), 1);
2980                 check_spends!(&ds_tx[0], &bs_tx[0]);
2981
2982                 mine_transactions(&nodes[1], &[&bs_tx[0], &ds_tx[0]]);
2983                 check_added_monitors(&nodes[1], 1);
2984                 expect_payment_forwarded!(nodes[1], nodes[0], nodes[3], Some(1000), false, true);
2985
2986                 let bs_claims = nodes[1].node.get_and_clear_pending_msg_events();
2987                 check_added_monitors(&nodes[1], 1);
2988                 assert_eq!(bs_claims.len(), 1);
2989                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &bs_claims[0] {
2990                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
2991                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
2992                 } else { panic!(); }
2993
2994                 expect_payment_sent!(nodes[0], payment_preimage);
2995
2996                 let ds_claim_msgs = nodes[3].node.get_and_clear_pending_msg_events();
2997                 assert_eq!(ds_claim_msgs.len(), 1);
2998                 let cs_claim_msgs = if let MessageSendEvent::UpdateHTLCs { updates, .. } = &ds_claim_msgs[0] {
2999                         nodes[2].node.handle_update_fulfill_htlc(&nodes[3].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3000                         let cs_claim_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3001                         check_added_monitors(&nodes[2], 1);
3002                         commitment_signed_dance!(nodes[2], nodes[3], updates.commitment_signed, false, true);
3003                         expect_payment_forwarded!(nodes[2], nodes[0], nodes[3], Some(1000), false, false);
3004                         cs_claim_msgs
3005                 } else { panic!(); };
3006
3007                 assert_eq!(cs_claim_msgs.len(), 1);
3008                 if let MessageSendEvent::UpdateHTLCs { updates, .. } = &cs_claim_msgs[0] {
3009                         nodes[0].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
3010                         commitment_signed_dance!(nodes[0], nodes[2], updates.commitment_signed, false, true);
3011                 } else { panic!(); }
3012
3013                 expect_payment_path_successful!(nodes[0]);
3014         }
3015 }
3016
3017 #[test]
3018 fn claim_from_closed_chan() {
3019         do_claim_from_closed_chan(true);
3020         do_claim_from_closed_chan(false);
3021 }
3022
3023 fn do_test_payment_metadata_consistency(do_reload: bool, do_modify: bool) {
3024         // Check that a payment metadata received on one HTLC that doesn't match the one received on
3025         // another results in the HTLC being rejected.
3026         //
3027         // We first set up a diamond shaped network, allowing us to split a payment into two HTLCs, the
3028         // first of which we'll deliver and the second of which we'll fail and then re-send with
3029         // modified payment metadata, which will in turn result in it being failed by the recipient.
3030         let chanmon_cfgs = create_chanmon_cfgs(4);
3031         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3032         let mut config = test_default_channel_config();
3033         config.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
3034         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, Some(config), Some(config), Some(config)]);
3035
3036         let persister;
3037         let new_chain_monitor;
3038         let nodes_0_deserialized;
3039
3040         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3041
3042         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
3043         let chan_id_bd = create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 1_000_000, 0).2;
3044         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
3045         let chan_id_cd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3046
3047         // Pay more than half of each channel's max, requiring MPP
3048         let amt_msat = 750_000_000;
3049         let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[3], Some(amt_msat));
3050         let payment_id = PaymentId(payment_hash.0);
3051         let payment_metadata = vec![44, 49, 52, 142];
3052
3053         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
3054                 .with_features(nodes[1].node.invoice_features());
3055         let mut route_params = RouteParameters {
3056                 payment_params,
3057                 final_value_msat: amt_msat,
3058         };
3059
3060         // Send the MPP payment, delivering the updated commitment state to nodes[1].
3061         nodes[0].node.send_payment(payment_hash, RecipientOnionFields {
3062                         payment_secret: Some(payment_secret), payment_metadata: Some(payment_metadata),
3063                 }, payment_id, route_params.clone(), Retry::Attempts(1)).unwrap();
3064         check_added_monitors!(nodes[0], 2);
3065
3066         let mut send_events = nodes[0].node.get_and_clear_pending_msg_events();
3067         assert_eq!(send_events.len(), 2);
3068         let first_send = SendEvent::from_event(send_events.pop().unwrap());
3069         let second_send = SendEvent::from_event(send_events.pop().unwrap());
3070
3071         let (b_recv_ev, c_recv_ev) = if first_send.node_id == nodes[1].node.get_our_node_id() {
3072                 (&first_send, &second_send)
3073         } else {
3074                 (&second_send, &first_send)
3075         };
3076         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &b_recv_ev.msgs[0]);
3077         commitment_signed_dance!(nodes[1], nodes[0], b_recv_ev.commitment_msg, false, true);
3078
3079         expect_pending_htlcs_forwardable!(nodes[1]);
3080         check_added_monitors(&nodes[1], 1);
3081         let b_forward_ev = SendEvent::from_node(&nodes[1]);
3082         nodes[3].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &b_forward_ev.msgs[0]);
3083         commitment_signed_dance!(nodes[3], nodes[1], b_forward_ev.commitment_msg, false, true);
3084
3085         expect_pending_htlcs_forwardable!(nodes[3]);
3086
3087         // Before delivering the second MPP HTLC to nodes[2], disconnect nodes[2] and nodes[3], which
3088         // will result in nodes[2] failing the HTLC back.
3089         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3090         nodes[3].node.peer_disconnected(&nodes[2].node.get_our_node_id());
3091
3092         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &c_recv_ev.msgs[0]);
3093         commitment_signed_dance!(nodes[2], nodes[0], c_recv_ev.commitment_msg, false, true);
3094
3095         let cs_fail = get_htlc_update_msgs(&nodes[2], &nodes[0].node.get_our_node_id());
3096         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &cs_fail.update_fail_htlcs[0]);
3097         commitment_signed_dance!(nodes[0], nodes[2], cs_fail.commitment_signed, false, true);
3098
3099         let payment_fail_retryable_evs = nodes[0].node.get_and_clear_pending_events();
3100         assert_eq!(payment_fail_retryable_evs.len(), 2);
3101         if let Event::PaymentPathFailed { .. } = payment_fail_retryable_evs[0] {} else { panic!(); }
3102         if let Event::PendingHTLCsForwardable { .. } = payment_fail_retryable_evs[1] {} else { panic!(); }
3103
3104         // Before we allow the HTLC to be retried, optionally change the payment_metadata we have
3105         // stored for our payment.
3106         if do_modify {
3107                 nodes[0].node.test_set_payment_metadata(payment_id, Some(Vec::new()));
3108         }
3109
3110         // Optionally reload nodes[3] to check that the payment_metadata is properly serialized with
3111         // the payment state.
3112         if do_reload {
3113                 let mon_bd = get_monitor!(nodes[3], chan_id_bd).encode();
3114                 let mon_cd = get_monitor!(nodes[3], chan_id_cd).encode();
3115                 reload_node!(nodes[3], config, &nodes[3].node.encode(), &[&mon_bd, &mon_cd],
3116                         persister, new_chain_monitor, nodes_0_deserialized);
3117                 nodes[1].node.peer_disconnected(&nodes[3].node.get_our_node_id());
3118                 reconnect_nodes(&nodes[1], &nodes[3], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3119         }
3120         reconnect_nodes(&nodes[2], &nodes[3], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3121
3122         // Create a new channel between C and D as A will refuse to retry on the existing one because
3123         // it just failed.
3124         let chan_id_cd_2 = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).2;
3125
3126         // Now retry the failed HTLC.
3127         nodes[0].node.process_pending_htlc_forwards();
3128         check_added_monitors(&nodes[0], 1);
3129         let as_resend = SendEvent::from_node(&nodes[0]);
3130         nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resend.msgs[0]);
3131         commitment_signed_dance!(nodes[2], nodes[0], as_resend.commitment_msg, false, true);
3132
3133         expect_pending_htlcs_forwardable!(nodes[2]);
3134         check_added_monitors(&nodes[2], 1);
3135         let cs_forward = SendEvent::from_node(&nodes[2]);
3136         nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &cs_forward.msgs[0]);
3137         commitment_signed_dance!(nodes[3], nodes[2], cs_forward.commitment_msg, false, true);
3138
3139         // Finally, check that nodes[3] does the correct thing - either accepting the payment or, if
3140         // the payment metadata was modified, failing only the one modified HTLC and retaining the
3141         // other.
3142         if do_modify {
3143                 expect_pending_htlcs_forwardable_ignore!(nodes[3]);
3144                 nodes[3].node.process_pending_htlc_forwards();
3145                 expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
3146                         &[HTLCDestination::FailedPayment {payment_hash}]);
3147                 nodes[3].node.process_pending_htlc_forwards();
3148
3149                 check_added_monitors(&nodes[3], 1);
3150                 let ds_fail = get_htlc_update_msgs(&nodes[3], &nodes[2].node.get_our_node_id());
3151
3152                 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &ds_fail.update_fail_htlcs[0]);
3153                 commitment_signed_dance!(nodes[2], nodes[3], ds_fail.commitment_signed, false, true);
3154                 expect_pending_htlcs_forwardable_conditions(nodes[2].node.get_and_clear_pending_events(),
3155                         &[HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_id_cd_2 }]);
3156         } else {
3157                 expect_pending_htlcs_forwardable!(nodes[3]);
3158                 expect_payment_claimable!(nodes[3], payment_hash, payment_secret, amt_msat);
3159                 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
3160         }
3161 }
3162
3163 #[test]
3164 fn test_payment_metadata_consistency() {
3165         do_test_payment_metadata_consistency(true, true);
3166         do_test_payment_metadata_consistency(true, false);
3167         do_test_payment_metadata_consistency(false, true);
3168         do_test_payment_metadata_consistency(false, false);
3169 }