Rework auto retry send errors
[rust-lightning] / lightning / src / ln / outbound_payment.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 //! Utilities to send payments and manage outbound payment information.
11
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
15
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
18 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
19 use crate::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA as LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA;
20 use crate::ln::msgs::DecodeError;
21 use crate::ln::onion_utils::HTLCFailReason;
22 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
23 use crate::util::errors::APIError;
24 use crate::util::events;
25 use crate::util::logger::Logger;
26 use crate::util::time::Time;
27 #[cfg(all(not(feature = "no-std"), test))]
28 use crate::util::time::tests::SinceEpoch;
29
30 use core::cmp;
31 use core::fmt::{self, Display, Formatter};
32 use core::ops::Deref;
33
34 use crate::prelude::*;
35 use crate::sync::Mutex;
36
37 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
38 /// and later, also stores information for retrying the payment.
39 pub(crate) enum PendingOutboundPayment {
40         Legacy {
41                 session_privs: HashSet<[u8; 32]>,
42         },
43         Retryable {
44                 retry_strategy: Option<Retry>,
45                 attempts: PaymentAttempts,
46                 payment_params: Option<PaymentParameters>,
47                 session_privs: HashSet<[u8; 32]>,
48                 payment_hash: PaymentHash,
49                 payment_secret: Option<PaymentSecret>,
50                 keysend_preimage: Option<PaymentPreimage>,
51                 pending_amt_msat: u64,
52                 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
53                 pending_fee_msat: Option<u64>,
54                 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
55                 total_msat: u64,
56                 /// Our best known block height at the time this payment was initiated.
57                 starting_block_height: u32,
58         },
59         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
60         /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
61         /// and add a pending payment that was already fulfilled.
62         Fulfilled {
63                 session_privs: HashSet<[u8; 32]>,
64                 payment_hash: Option<PaymentHash>,
65                 timer_ticks_without_htlcs: u8,
66         },
67         /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
68         /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
69         /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
70         /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
71         /// downstream event handler as to when a payment has actually failed.
72         ///
73         /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
74         Abandoned {
75                 session_privs: HashSet<[u8; 32]>,
76                 payment_hash: PaymentHash,
77         },
78 }
79
80 impl PendingOutboundPayment {
81         fn increment_attempts(&mut self) {
82                 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
83                         attempts.count += 1;
84                 }
85         }
86         fn is_auto_retryable_now(&self) -> bool {
87                 match self {
88                         PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
89                                 strategy.is_retryable_now(&attempts)
90                         },
91                         _ => false,
92                 }
93         }
94         fn is_retryable_now(&self) -> bool {
95                 match self {
96                         PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
97                                 // We're handling retries manually, we can always retry.
98                                 true
99                         },
100                         PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
101                                 strategy.is_retryable_now(&attempts)
102                         },
103                         _ => false,
104                 }
105         }
106         fn payment_parameters(&mut self) -> Option<&mut PaymentParameters> {
107                 match self {
108                         PendingOutboundPayment::Retryable { payment_params: Some(ref mut params), .. } => {
109                                 Some(params)
110                         },
111                         _ => None,
112                 }
113         }
114         pub fn insert_previously_failed_scid(&mut self, scid: u64) {
115                 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
116                         params.previously_failed_channels.push(scid);
117                 }
118         }
119         pub(super) fn is_fulfilled(&self) -> bool {
120                 match self {
121                         PendingOutboundPayment::Fulfilled { .. } => true,
122                         _ => false,
123                 }
124         }
125         pub(super) fn abandoned(&self) -> bool {
126                 match self {
127                         PendingOutboundPayment::Abandoned { .. } => true,
128                         _ => false,
129                 }
130         }
131         fn get_pending_fee_msat(&self) -> Option<u64> {
132                 match self {
133                         PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
134                         _ => None,
135                 }
136         }
137
138         fn payment_hash(&self) -> Option<PaymentHash> {
139                 match self {
140                         PendingOutboundPayment::Legacy { .. } => None,
141                         PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
142                         PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
143                         PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
144                 }
145         }
146
147         fn mark_fulfilled(&mut self) {
148                 let mut session_privs = HashSet::new();
149                 core::mem::swap(&mut session_privs, match self {
150                         PendingOutboundPayment::Legacy { session_privs } |
151                                 PendingOutboundPayment::Retryable { session_privs, .. } |
152                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
153                                 PendingOutboundPayment::Abandoned { session_privs, .. }
154                         => session_privs,
155                 });
156                 let payment_hash = self.payment_hash();
157                 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
158         }
159
160         fn mark_abandoned(&mut self) -> Result<(), ()> {
161                 let mut session_privs = HashSet::new();
162                 let our_payment_hash;
163                 core::mem::swap(&mut session_privs, match self {
164                         PendingOutboundPayment::Legacy { .. } |
165                         PendingOutboundPayment::Fulfilled { .. } =>
166                                 return Err(()),
167                         PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
168                         PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
169                                 our_payment_hash = *payment_hash;
170                                 session_privs
171                         },
172                 });
173                 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
174                 Ok(())
175         }
176
177         /// panics if path is None and !self.is_fulfilled
178         fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
179                 let remove_res = match self {
180                         PendingOutboundPayment::Legacy { session_privs } |
181                                 PendingOutboundPayment::Retryable { session_privs, .. } |
182                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
183                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
184                                         session_privs.remove(session_priv)
185                                 }
186                 };
187                 if remove_res {
188                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
189                                 let path = path.expect("Fulfilling a payment should always come with a path");
190                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
191                                 *pending_amt_msat -= path_last_hop.fee_msat;
192                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
193                                         *fee_msat -= path.get_path_fees();
194                                 }
195                         }
196                 }
197                 remove_res
198         }
199
200         pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
201                 let insert_res = match self {
202                         PendingOutboundPayment::Legacy { session_privs } |
203                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
204                                         session_privs.insert(session_priv)
205                                 }
206                         PendingOutboundPayment::Fulfilled { .. } => false,
207                         PendingOutboundPayment::Abandoned { .. } => false,
208                 };
209                 if insert_res {
210                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
211                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
212                                 *pending_amt_msat += path_last_hop.fee_msat;
213                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
214                                         *fee_msat += path.get_path_fees();
215                                 }
216                         }
217                 }
218                 insert_res
219         }
220
221         pub(super) fn remaining_parts(&self) -> usize {
222                 match self {
223                         PendingOutboundPayment::Legacy { session_privs } |
224                                 PendingOutboundPayment::Retryable { session_privs, .. } |
225                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
226                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
227                                         session_privs.len()
228                                 }
229                 }
230         }
231 }
232
233 /// Strategies available to retry payment path failures.
234 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
235 pub enum Retry {
236         /// Max number of attempts to retry payment.
237         ///
238         /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
239         /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
240         /// were retried along a route from a single call to [`Router::find_route`].
241         Attempts(usize),
242         #[cfg(not(feature = "no-std"))]
243         /// Time elapsed before abandoning retries for a payment.
244         Timeout(core::time::Duration),
245 }
246
247 impl Retry {
248         pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
249                 match (self, attempts) {
250                         (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
251                                 max_retry_count > count
252                         },
253                         #[cfg(all(not(feature = "no-std"), not(test)))]
254                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
255                                 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
256                         #[cfg(all(not(feature = "no-std"), test))]
257                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
258                                 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
259                 }
260         }
261 }
262
263 #[cfg(feature = "std")]
264 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
265         if let Some(expiry_time) = route_params.payment_params.expiry_time {
266                 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
267                         return elapsed > core::time::Duration::from_secs(expiry_time)
268                 }
269         }
270         false
271 }
272
273 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
274
275 /// Storing minimal payment attempts information required for determining if a outbound payment can
276 /// be retried.
277 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
278         /// This count will be incremented only after the result of the attempt is known. When it's 0,
279         /// it means the result of the first attempt is not known yet.
280         pub(crate) count: usize,
281         /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
282         first_attempted_at: T
283 }
284
285 #[cfg(not(any(feature = "no-std", test)))]
286 type ConfiguredTime = std::time::Instant;
287 #[cfg(feature = "no-std")]
288 type ConfiguredTime = crate::util::time::Eternity;
289 #[cfg(all(not(feature = "no-std"), test))]
290 type ConfiguredTime = SinceEpoch;
291
292 impl<T: Time> PaymentAttemptsUsingTime<T> {
293         pub(crate) fn new() -> Self {
294                 PaymentAttemptsUsingTime {
295                         count: 0,
296                         first_attempted_at: T::now()
297                 }
298         }
299 }
300
301 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
302         fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
303                 #[cfg(feature = "no-std")]
304                 return write!(f, "attempts: {}", self.count);
305                 #[cfg(not(feature = "no-std"))]
306                 return write!(
307                         f,
308                         "attempts: {}, duration: {}s",
309                         self.count,
310                         T::now().duration_since(self.first_attempted_at).as_secs()
311                 );
312         }
313 }
314
315 /// Indicates an immediate error on [`ChannelManager::send_payment_with_retry`]. Further errors
316 /// may be surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
317 ///
318 /// [`ChannelManager::send_payment_with_retry`]: crate::ln::channelmanager::ChannelManager::send_payment_with_retry
319 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
320 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
321 #[derive(Clone, Debug)]
322 pub enum RetryableSendFailure {
323         /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
324         /// that this error is *not* caused by [`Retry::Timeout`].
325         ///
326         /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
327         PaymentExpired,
328         /// We were unable to find a route to the destination.
329         RouteNotFound,
330         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
331         /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
332         ///
333         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
334         /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
335         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
336         DuplicatePayment,
337 }
338
339 /// If a payment fails to send with [`ChannelManager::send_payment`], it can be in one of several
340 /// states. This enum is returned as the Err() type describing which state the payment is in, see
341 /// the description of individual enum states for more.
342 ///
343 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
344 #[derive(Clone, Debug)]
345 pub enum PaymentSendFailure {
346         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
347         /// send the payment at all.
348         ///
349         /// You can freely resend the payment in full (with the parameter error fixed).
350         ///
351         /// Because the payment failed outright, no payment tracking is done and no
352         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
353         ///
354         /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
355         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
356         ParameterError(APIError),
357         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
358         /// from attempting to send the payment at all.
359         ///
360         /// You can freely resend the payment in full (with the parameter error fixed).
361         ///
362         /// Because the payment failed outright, no payment tracking is done and no
363         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
364         ///
365         /// The results here are ordered the same as the paths in the route object which was passed to
366         /// send_payment.
367         ///
368         /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
369         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
370         PathParameterError(Vec<Result<(), APIError>>),
371         /// All paths which were attempted failed to send, with no channel state change taking place.
372         /// You can freely resend the payment in full (though you probably want to do so over different
373         /// paths than the ones selected).
374         ///
375         /// Because the payment failed outright, no payment tracking is done and no
376         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
377         ///
378         /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
379         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
380         AllFailedResendSafe(Vec<APIError>),
381         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
382         /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
383         ///
384         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
385         /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
386         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
387         DuplicatePayment,
388         /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
389         /// some paths have irrevocably committed to the HTLC.
390         ///
391         /// The results here are ordered the same as the paths in the route object that was passed to
392         /// send_payment.
393         ///
394         /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
395         /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
396         ///
397         /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
398         PartialFailure {
399                 /// The errors themselves, in the same order as the paths from the route.
400                 results: Vec<Result<(), APIError>>,
401                 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
402                 /// contain a [`RouteParameters`] object for the failing paths.
403                 failed_paths_retry: Option<RouteParameters>,
404                 /// The payment id for the payment, which is now at least partially pending.
405                 payment_id: PaymentId,
406         },
407 }
408
409 pub(super) struct OutboundPayments {
410         pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
411         pub(super) retry_lock: Mutex<()>,
412 }
413
414 impl OutboundPayments {
415         pub(super) fn new() -> Self {
416                 Self {
417                         pending_outbound_payments: Mutex::new(HashMap::new()),
418                         retry_lock: Mutex::new(()),
419                 }
420         }
421
422         pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
423                 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
424                 retry_strategy: Retry, route_params: RouteParameters, router: &R,
425                 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
426                 node_signer: &NS, best_block_height: u32, logger: &L,
427                 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
428         ) -> Result<(), RetryableSendFailure>
429         where
430                 R::Target: Router,
431                 ES::Target: EntropySource,
432                 NS::Target: NodeSigner,
433                 L::Target: Logger,
434                 IH: Fn() -> InFlightHtlcs,
435                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
436                          u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
437         {
438                 self.send_payment_internal(payment_id, payment_hash, payment_secret, None, retry_strategy,
439                         route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
440                         best_block_height, logger, pending_events, &send_payment_along_path)
441         }
442
443         pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
444                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
445                 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
446                 send_payment_along_path: F
447         ) -> Result<(), PaymentSendFailure>
448         where
449                 ES::Target: EntropySource,
450                 NS::Target: NodeSigner,
451                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
452                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
453         {
454                 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, None, route, None, None, entropy_source, best_block_height)?;
455                 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
456                         onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
457                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
458         }
459
460         pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
461                 &self, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
462                 retry_strategy: Retry, route_params: RouteParameters, router: &R,
463                 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
464                 node_signer: &NS, best_block_height: u32, logger: &L,
465                 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP
466         ) -> Result<PaymentHash, RetryableSendFailure>
467         where
468                 R::Target: Router,
469                 ES::Target: EntropySource,
470                 NS::Target: NodeSigner,
471                 L::Target: Logger,
472                 IH: Fn() -> InFlightHtlcs,
473                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
474                          u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
475         {
476                 let preimage = payment_preimage
477                         .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
478                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
479                 self.send_payment_internal(payment_id, payment_hash, &None, Some(preimage), retry_strategy,
480                         route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer,
481                         best_block_height, logger, pending_events, send_payment_along_path)
482                         .map(|()| payment_hash)
483         }
484
485         pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
486                 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
487                 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
488         ) -> Result<PaymentHash, PaymentSendFailure>
489         where
490                 ES::Target: EntropySource,
491                 NS::Target: NodeSigner,
492                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
493                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
494         {
495                 let preimage = payment_preimage
496                         .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
497                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
498                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
499
500                 match self.pay_route_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
501                         Ok(()) => Ok(payment_hash),
502                         Err(e) => {
503                                 self.remove_outbound_if_all_failed(payment_id, &e);
504                                 Err(e)
505                         }
506                 }
507         }
508
509         pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
510                 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
511                 best_block_height: u32, pending_events: &Mutex<Vec<events::Event>>, logger: &L,
512                 send_payment_along_path: SP,
513         )
514         where
515                 R::Target: Router,
516                 ES::Target: EntropySource,
517                 NS::Target: NodeSigner,
518                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
519                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
520                 IH: Fn() -> InFlightHtlcs,
521                 FH: Fn() -> Vec<ChannelDetails>,
522                 L::Target: Logger,
523         {
524                 let _single_thread = self.retry_lock.lock().unwrap();
525                 loop {
526                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
527                         let mut retry_id_route_params = None;
528                         for (pmt_id, pmt) in outbounds.iter_mut() {
529                                 if pmt.is_auto_retryable_now() {
530                                         if let PendingOutboundPayment::Retryable { payment_hash, pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
531                                                 if pending_amt_msat < total_msat {
532                                                         retry_id_route_params = Some((*pmt_id, *payment_hash, RouteParameters {
533                                                                 final_value_msat: *total_msat - *pending_amt_msat,
534                                                                 final_cltv_expiry_delta:
535                                                                         if let Some(delta) = params.final_cltv_expiry_delta { delta }
536                                                                         else {
537                                                                                 debug_assert!(false, "We always set the final_cltv_expiry_delta when a path fails");
538                                                                                 LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA.into()
539                                                                         },
540                                                                 payment_params: params.clone(),
541                                                         }));
542                                                         break
543                                                 }
544                                         }
545                                 }
546                         }
547                         core::mem::drop(outbounds);
548                         if let Some((payment_id, payment_hash, route_params)) = retry_id_route_params {
549                                 self.retry_payment_internal(payment_id, payment_hash, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
550                         } else { break }
551                 }
552
553                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
554                 outbounds.retain(|pmt_id, pmt| {
555                         let mut retain = true;
556                         if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
557                                 if pmt.mark_abandoned().is_ok() {
558                                         pending_events.lock().unwrap().push(events::Event::PaymentFailed {
559                                                 payment_id: *pmt_id,
560                                                 payment_hash: pmt.payment_hash().expect("PendingOutboundPayments::Retryable always has a payment hash set"),
561                                         });
562                                         retain = false;
563                                 }
564                         }
565                         retain
566                 });
567         }
568
569         pub(super) fn needs_abandon(&self) -> bool {
570                 let outbounds = self.pending_outbound_payments.lock().unwrap();
571                 outbounds.iter().any(|(_, pmt)|
572                         !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
573         }
574
575         /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
576         /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
577         ///
578         /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
579         /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
580         fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
581                 &self, payment_id: PaymentId, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
582                 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
583                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
584                 node_signer: &NS, best_block_height: u32, logger: &L,
585                 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
586         ) -> Result<(), RetryableSendFailure>
587         where
588                 R::Target: Router,
589                 ES::Target: EntropySource,
590                 NS::Target: NodeSigner,
591                 L::Target: Logger,
592                 IH: Fn() -> InFlightHtlcs,
593                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
594                     u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
595         {
596                 #[cfg(feature = "std")] {
597                         if has_expired(&route_params) {
598                                 return Err(RetryableSendFailure::PaymentExpired)
599                         }
600                 }
601
602                 let route = router.find_route(
603                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
604                         Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs()
605                 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
606
607                 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret,
608                         payment_id, keysend_preimage, &route, Some(retry_strategy),
609                         Some(route_params.payment_params.clone()), entropy_source, best_block_height)
610                         .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
611
612                 let res = self.pay_route_internal(&route, payment_hash, payment_secret, None, payment_id, None,
613                         onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
614                 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
615                 if let Err(e) = res {
616                         self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path);
617                 }
618                 Ok(())
619         }
620
621         fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
622                 &self, payment_id: PaymentId, payment_hash: PaymentHash, route_params: RouteParameters,
623                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
624                 node_signer: &NS, best_block_height: u32, logger: &L,
625                 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
626         )
627         where
628                 R::Target: Router,
629                 ES::Target: EntropySource,
630                 NS::Target: NodeSigner,
631                 L::Target: Logger,
632                 IH: Fn() -> InFlightHtlcs,
633                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
634                     u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
635         {
636                 #[cfg(feature = "std")] {
637                         if has_expired(&route_params) {
638                                 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
639                                 self.abandon_payment(payment_id, pending_events);
640                                 return
641                         }
642                 }
643
644                 let route = match router.find_route(
645                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
646                         Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs()
647                 ) {
648                         Ok(route) => route,
649                         Err(e) => {
650                                 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
651                                 self.abandon_payment(payment_id, pending_events);
652                                 return
653                         }
654                 };
655
656                 let res = self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer,
657                         best_block_height, send_payment_along_path);
658                 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
659                 if let Err(e) = res {
660                         self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
661                 }
662         }
663
664         fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
665                 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
666                 route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH,
667                 entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
668                 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
669         )
670         where
671                 R::Target: Router,
672                 ES::Target: EntropySource,
673                 NS::Target: NodeSigner,
674                 L::Target: Logger,
675                 IH: Fn() -> InFlightHtlcs,
676                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
677                     u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
678         {
679                 match err {
680                         PaymentSendFailure::AllFailedResendSafe(errs) => {
681                                 Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, errs.into_iter().map(|e| Err(e)), pending_events);
682                                 self.retry_payment_internal(payment_id, payment_hash, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
683                         },
684                         PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), results, .. } => {
685                                 Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, results.into_iter(), pending_events);
686                                 // Some paths were sent, even if we failed to send the full MPP value our recipient may
687                                 // misbehave and claim the funds, at which point we have to consider the payment sent, so
688                                 // return `Ok()` here, ignoring any retry errors.
689                                 self.retry_payment_internal(payment_id, payment_hash, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
690                         },
691                         PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
692                                 // This may happen if we send a payment and some paths fail, but only due to a temporary
693                                 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
694                                 // initial HTLC-Add messages yet.
695                         },
696                         PaymentSendFailure::PathParameterError(results) => {
697                                 Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, results.into_iter(), pending_events);
698                                 self.abandon_payment(payment_id, pending_events);
699                         },
700                         PaymentSendFailure::ParameterError(e) => {
701                                 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
702                                 self.abandon_payment(payment_id, pending_events);
703                         },
704                         PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
705                 }
706         }
707
708         fn push_payment_path_failed_evs<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>>(
709                 payment_id: PaymentId, payment_hash: PaymentHash, paths: Vec<Vec<RouteHop>>, path_results: I,
710                 pending_events: &Mutex<Vec<events::Event>>
711         ) {
712                 let mut events = pending_events.lock().unwrap();
713                 debug_assert_eq!(paths.len(), path_results.len());
714                 for (path, path_res) in paths.into_iter().zip(path_results) {
715                         if let Err(e) = path_res {
716                                 let failed_scid = if let APIError::InvalidRoute { .. } = e {
717                                         None
718                                 } else {
719                                         Some(path[0].short_channel_id)
720                                 };
721                                 events.push(events::Event::PaymentPathFailed {
722                                         payment_id: Some(payment_id),
723                                         payment_hash,
724                                         payment_failed_permanently: false,
725                                         network_update: None,
726                                         all_paths_failed: false,
727                                         path,
728                                         short_channel_id: failed_scid,
729                                         retry: None,
730                                         #[cfg(test)]
731                                         error_code: None,
732                                         #[cfg(test)]
733                                         error_data: None,
734                                 });
735                         }
736                 }
737         }
738
739         pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
740                 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
741                 send_payment_along_path: F
742         ) -> Result<(), PaymentSendFailure>
743         where
744                 ES::Target: EntropySource,
745                 NS::Target: NodeSigner,
746                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
747                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
748         {
749                 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
750                 for path in route.paths.iter() {
751                         if path.len() == 0 {
752                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
753                                         err: "length-0 path in route".to_string()
754                                 }))
755                         }
756                 }
757
758                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
759                 for _ in 0..route.paths.len() {
760                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
761                 }
762
763                 let (total_msat, payment_hash, payment_secret, keysend_preimage) = {
764                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
765                         match outbounds.get_mut(&payment_id) {
766                                 Some(payment) => {
767                                         let res = match payment {
768                                                 PendingOutboundPayment::Retryable {
769                                                         total_msat, payment_hash, keysend_preimage, payment_secret, pending_amt_msat, ..
770                                                 } => {
771                                                         let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
772                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
773                                                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
774                                                                         err: format!("retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat).to_string()
775                                                                 }))
776                                                         }
777                                                         (*total_msat, *payment_hash, *payment_secret, *keysend_preimage)
778                                                 },
779                                                 PendingOutboundPayment::Legacy { .. } => {
780                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
781                                                                 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
782                                                         }))
783                                                 },
784                                                 PendingOutboundPayment::Fulfilled { .. } => {
785                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
786                                                                 err: "Payment already completed".to_owned()
787                                                         }));
788                                                 },
789                                                 PendingOutboundPayment::Abandoned { .. } => {
790                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
791                                                                 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
792                                                         }));
793                                                 },
794                                         };
795                                         if !payment.is_retryable_now() {
796                                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
797                                                         err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
798                                                 }))
799                                         }
800                                         payment.increment_attempts();
801                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
802                                                 assert!(payment.insert(*session_priv_bytes, path));
803                                         }
804                                         res
805                                 },
806                                 None =>
807                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
808                                                 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
809                                         })),
810                         }
811                 };
812                 self.pay_route_internal(route, payment_hash, &payment_secret, keysend_preimage, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
813         }
814
815         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
816                 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
817                 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
818         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
819         where
820                 ES::Target: EntropySource,
821                 NS::Target: NodeSigner,
822                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
823                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
824         {
825                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
826
827                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
828
829                 if hops.len() < 2 {
830                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
831                                 err: "No need probing a path with less than two hops".to_string()
832                         }))
833                 }
834
835                 let route = Route { paths: vec![hops], payment_params: None };
836                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, None, &route, None, None, entropy_source, best_block_height)?;
837
838                 match self.pay_route_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
839                         Ok(()) => Ok((payment_hash, payment_id)),
840                         Err(e) => {
841                                 self.remove_outbound_if_all_failed(payment_id, &e);
842                                 Err(e)
843                         }
844                 }
845         }
846
847         #[cfg(test)]
848         pub(super) fn test_add_new_pending_payment<ES: Deref>(
849                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
850                 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
851         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
852                 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
853         }
854
855         pub(super) fn add_new_pending_payment<ES: Deref>(
856                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
857                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
858                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
859         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
860                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
861                 for _ in 0..route.paths.len() {
862                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
863                 }
864
865                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
866                 match pending_outbounds.entry(payment_id) {
867                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
868                         hash_map::Entry::Vacant(entry) => {
869                                 let payment = entry.insert(PendingOutboundPayment::Retryable {
870                                         retry_strategy,
871                                         attempts: PaymentAttempts::new(),
872                                         payment_params,
873                                         session_privs: HashSet::new(),
874                                         pending_amt_msat: 0,
875                                         pending_fee_msat: Some(0),
876                                         payment_hash,
877                                         payment_secret,
878                                         keysend_preimage,
879                                         starting_block_height: best_block_height,
880                                         total_msat: route.get_total_amount(),
881                                 });
882
883                                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
884                                         assert!(payment.insert(*session_priv_bytes, path));
885                                 }
886
887                                 Ok(onion_session_privs)
888                         },
889                 }
890         }
891
892         fn pay_route_internal<NS: Deref, F>(
893                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
894                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
895                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
896                 send_payment_along_path: &F
897         ) -> Result<(), PaymentSendFailure>
898         where
899                 NS::Target: NodeSigner,
900                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
901                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
902         {
903                 if route.paths.len() < 1 {
904                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
905                 }
906                 if payment_secret.is_none() && route.paths.len() > 1 {
907                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
908                 }
909                 let mut total_value = 0;
910                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
911                 let mut path_errs = Vec::with_capacity(route.paths.len());
912                 'path_check: for path in route.paths.iter() {
913                         if path.len() < 1 || path.len() > 20 {
914                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
915                                 continue 'path_check;
916                         }
917                         for (idx, hop) in path.iter().enumerate() {
918                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
919                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
920                                         continue 'path_check;
921                                 }
922                         }
923                         total_value += path.last().unwrap().fee_msat;
924                         path_errs.push(Ok(()));
925                 }
926                 if path_errs.iter().any(|e| e.is_err()) {
927                         return Err(PaymentSendFailure::PathParameterError(path_errs));
928                 }
929                 if let Some(amt_msat) = recv_value_msat {
930                         debug_assert!(amt_msat >= total_value);
931                         total_value = amt_msat;
932                 }
933
934                 let cur_height = best_block_height + 1;
935                 let mut results = Vec::new();
936                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
937                 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
938                         let mut path_res = send_payment_along_path(&path, &route.payment_params, &payment_hash, payment_secret, total_value, cur_height, payment_id, &keysend_preimage, session_priv);
939                         match path_res {
940                                 Ok(_) => {},
941                                 Err(APIError::MonitorUpdateInProgress) => {
942                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
943                                         // considered "in flight" and we shouldn't remove it from the
944                                         // PendingOutboundPayment set.
945                                 },
946                                 Err(_) => {
947                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
948                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
949                                                 let removed = payment.remove(&session_priv, Some(path));
950                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
951                                         } else {
952                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
953                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
954                                         }
955                                 }
956                         }
957                         results.push(path_res);
958                 }
959                 let mut has_ok = false;
960                 let mut has_err = false;
961                 let mut pending_amt_unsent = 0;
962                 let mut max_unsent_cltv_delta = 0;
963                 for (res, path) in results.iter().zip(route.paths.iter()) {
964                         if res.is_ok() { has_ok = true; }
965                         if res.is_err() { has_err = true; }
966                         if let &Err(APIError::MonitorUpdateInProgress) = res {
967                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
968                                 // PartialFailure.
969                                 has_err = true;
970                                 has_ok = true;
971                         } else if res.is_err() {
972                                 pending_amt_unsent += path.last().unwrap().fee_msat;
973                                 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
974                         }
975                 }
976                 if has_err && has_ok {
977                         Err(PaymentSendFailure::PartialFailure {
978                                 results,
979                                 payment_id,
980                                 failed_paths_retry: if pending_amt_unsent != 0 {
981                                         if let Some(payment_params) = &route.payment_params {
982                                                 Some(RouteParameters {
983                                                         payment_params: payment_params.clone(),
984                                                         final_value_msat: pending_amt_unsent,
985                                                         final_cltv_expiry_delta:
986                                                                 if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
987                                                                 else { max_unsent_cltv_delta },
988                                                 })
989                                         } else { None }
990                                 } else { None },
991                         })
992                 } else if has_err {
993                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
994                 } else {
995                         Ok(())
996                 }
997         }
998
999         #[cfg(test)]
1000         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1001                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
1002                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1003                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1004                 send_payment_along_path: F
1005         ) -> Result<(), PaymentSendFailure>
1006         where
1007                 NS::Target: NodeSigner,
1008                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
1009                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1010         {
1011                 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
1012                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1013                         &send_payment_along_path)
1014                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1015         }
1016
1017         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1018         // map as the payment is free to be resent.
1019         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1020                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1021                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1022                         debug_assert!(removed, "We should always have a pending payment to remove here");
1023                 }
1024         }
1025
1026         pub(super) fn claim_htlc<L: Deref>(
1027                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1028                 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1029         ) where L::Target: Logger {
1030                 let mut session_priv_bytes = [0; 32];
1031                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1032                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1033                 let mut pending_events = pending_events.lock().unwrap();
1034                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1035                         if !payment.get().is_fulfilled() {
1036                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1037                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1038                                 pending_events.push(
1039                                         events::Event::PaymentSent {
1040                                                 payment_id: Some(payment_id),
1041                                                 payment_preimage,
1042                                                 payment_hash,
1043                                                 fee_paid_msat,
1044                                         }
1045                                 );
1046                                 payment.get_mut().mark_fulfilled();
1047                         }
1048
1049                         if from_onchain {
1050                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1051                                 // This could potentially lead to removing a pending payment too early,
1052                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1053                                 // restart.
1054                                 // TODO: We should have a second monitor event that informs us of payments
1055                                 // irrevocably fulfilled.
1056                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1057                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1058                                         pending_events.push(
1059                                                 events::Event::PaymentPathSuccessful {
1060                                                         payment_id,
1061                                                         payment_hash,
1062                                                         path,
1063                                                 }
1064                                         );
1065                                 }
1066                         }
1067                 } else {
1068                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1069                 }
1070         }
1071
1072         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
1073                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1074                 let mut pending_events = pending_events.lock().unwrap();
1075                 for source in sources {
1076                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1077                                 let mut session_priv_bytes = [0; 32];
1078                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1079                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1080                                         assert!(payment.get().is_fulfilled());
1081                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1082                                                 pending_events.push(
1083                                                         events::Event::PaymentPathSuccessful {
1084                                                                 payment_id,
1085                                                                 payment_hash: payment.get().payment_hash(),
1086                                                                 path,
1087                                                         }
1088                                                 );
1089                                         }
1090                                 }
1091                         }
1092                 }
1093         }
1094
1095         pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
1096                 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1097                 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1098                 // this could race the user making a duplicate send_payment call and our idempotency
1099                 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1100                 // removal. This should be more than sufficient to ensure the idempotency of any
1101                 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1102                 // processed.
1103                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1104                 let pending_events = pending_events.lock().unwrap();
1105                 pending_outbound_payments.retain(|payment_id, payment| {
1106                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1107                                 let mut no_remaining_entries = session_privs.is_empty();
1108                                 if no_remaining_entries {
1109                                         for ev in pending_events.iter() {
1110                                                 match ev {
1111                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1112                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1113                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1114                                                                         if payment_id == ev_payment_id {
1115                                                                                 no_remaining_entries = false;
1116                                                                                 break;
1117                                                                         }
1118                                                                 },
1119                                                         _ => {},
1120                                                 }
1121                                         }
1122                                 }
1123                                 if no_remaining_entries {
1124                                         *timer_ticks_without_htlcs += 1;
1125                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1126                                 } else {
1127                                         *timer_ticks_without_htlcs = 0;
1128                                         true
1129                                 }
1130                         } else { true }
1131                 });
1132         }
1133
1134         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1135         pub(super) fn fail_htlc<L: Deref>(
1136                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1137                 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
1138                 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
1139                 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1140         ) -> bool where L::Target: Logger {
1141                 #[cfg(test)]
1142                 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1143                 #[cfg(not(test))]
1144                 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1145
1146                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1147                 let mut session_priv_bytes = [0; 32];
1148                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1149                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1150
1151                 // If any payments already need retry, there's no need to generate a redundant
1152                 // `PendingHTLCsForwardable`.
1153                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1154                         let mut awaiting_retry = false;
1155                         if pmt.is_auto_retryable_now() {
1156                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1157                                         if pending_amt_msat < total_msat {
1158                                                 awaiting_retry = true;
1159                                         }
1160                                 }
1161                         }
1162                         awaiting_retry
1163                 });
1164
1165                 let mut all_paths_failed = false;
1166                 let mut full_failure_ev = None;
1167                 let mut pending_retry_ev = false;
1168                 let mut retry = None;
1169                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1170                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1171                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1172                                 return false
1173                         }
1174                         if payment.get().is_fulfilled() {
1175                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1176                                 return false
1177                         }
1178                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1179                         if let Some(scid) = short_channel_id {
1180                                 payment.get_mut().insert_previously_failed_scid(scid);
1181                         }
1182
1183                         // We want to move towards only using the `PaymentParameters` in the outbound payments
1184                         // map. However, for backwards-compatibility, we still need to support passing the
1185                         // `PaymentParameters` data that was shoved in the HTLC (and given to us via
1186                         // `payment_params`) back to the user.
1187                         let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
1188                         if let Some(params) = payment.get_mut().payment_parameters() {
1189                                 if params.final_cltv_expiry_delta.is_none() {
1190                                         // This should be rare, but a user could provide None for the payment data, and
1191                                         // we need it when we go to retry the payment, so fill it in.
1192                                         params.final_cltv_expiry_delta = Some(path_last_hop.cltv_expiry_delta);
1193                                 }
1194                                 retry = Some(RouteParameters {
1195                                         payment_params: params.clone(),
1196                                         final_value_msat: path_last_hop.fee_msat,
1197                                         final_cltv_expiry_delta: params.final_cltv_expiry_delta.unwrap(),
1198                                 });
1199                         } else if let Some(params) = payment_params {
1200                                 retry = Some(RouteParameters {
1201                                         payment_params: params.clone(),
1202                                         final_value_msat: path_last_hop.fee_msat,
1203                                         final_cltv_expiry_delta:
1204                                                 if let Some(delta) = params.final_cltv_expiry_delta { delta }
1205                                                 else { path_last_hop.cltv_expiry_delta },
1206                                 });
1207                         }
1208
1209                         if payment_is_probe || !is_retryable_now || !payment_retryable || retry.is_none() {
1210                                 let _ = payment.get_mut().mark_abandoned(); // we'll only Err if it's a legacy payment
1211                                 is_retryable_now = false;
1212                         }
1213                         if payment.get().remaining_parts() == 0 {
1214                                 all_paths_failed = true;
1215                                 if payment.get().abandoned() {
1216                                         if !payment_is_probe {
1217                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1218                                                         payment_id: *payment_id,
1219                                                         payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1220                                                 });
1221                                         }
1222                                         payment.remove();
1223                                 }
1224                         }
1225                         is_retryable_now
1226                 } else {
1227                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1228                         return false
1229                 };
1230                 core::mem::drop(outbounds);
1231                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1232
1233                 let path_failure = {
1234                         if payment_is_probe {
1235                                 if !payment_retryable {
1236                                         events::Event::ProbeSuccessful {
1237                                                 payment_id: *payment_id,
1238                                                 payment_hash: payment_hash.clone(),
1239                                                 path: path.clone(),
1240                                         }
1241                                 } else {
1242                                         events::Event::ProbeFailed {
1243                                                 payment_id: *payment_id,
1244                                                 payment_hash: payment_hash.clone(),
1245                                                 path: path.clone(),
1246                                                 short_channel_id,
1247                                         }
1248                                 }
1249                         } else {
1250                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1251                                 // process_onion_failure we should close that channel as it implies our
1252                                 // next-hop is needlessly blaming us!
1253                                 if let Some(scid) = short_channel_id {
1254                                         retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1255                                 }
1256                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1257                                 // payment will sit in our outbounds forever.
1258                                 if attempts_remaining && !already_awaiting_retry {
1259                                         debug_assert!(full_failure_ev.is_none());
1260                                         pending_retry_ev = true;
1261                                 }
1262                                 events::Event::PaymentPathFailed {
1263                                         payment_id: Some(*payment_id),
1264                                         payment_hash: payment_hash.clone(),
1265                                         payment_failed_permanently: !payment_retryable,
1266                                         network_update,
1267                                         all_paths_failed,
1268                                         path: path.clone(),
1269                                         short_channel_id,
1270                                         retry,
1271                                         #[cfg(test)]
1272                                         error_code: onion_error_code,
1273                                         #[cfg(test)]
1274                                         error_data: onion_error_data
1275                                 }
1276                         }
1277                 };
1278                 let mut pending_events = pending_events.lock().unwrap();
1279                 pending_events.push(path_failure);
1280                 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1281                 pending_retry_ev
1282         }
1283
1284         pub(super) fn abandon_payment(
1285                 &self, payment_id: PaymentId, pending_events: &Mutex<Vec<events::Event>>
1286         ) {
1287                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1288                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1289                         if let Ok(()) = payment.get_mut().mark_abandoned() {
1290                                 if payment.get().remaining_parts() == 0 {
1291                                         pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1292                                                 payment_id,
1293                                                 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1294                                         });
1295                                         payment.remove();
1296                                 }
1297                         }
1298                 }
1299         }
1300
1301         #[cfg(test)]
1302         pub fn has_pending_payments(&self) -> bool {
1303                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1304         }
1305
1306         #[cfg(test)]
1307         pub fn clear_pending_payments(&self) {
1308                 self.pending_outbound_payments.lock().unwrap().clear()
1309         }
1310 }
1311
1312 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1313 /// payment probe.
1314 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1315         probing_cookie_secret: [u8; 32]) -> bool
1316 {
1317         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1318         target_payment_hash == *payment_hash
1319 }
1320
1321 /// Returns the 'probing cookie' for the given [`PaymentId`].
1322 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1323         let mut preimage = [0u8; 64];
1324         preimage[..32].copy_from_slice(&probing_cookie_secret);
1325         preimage[32..].copy_from_slice(&payment_id.0);
1326         PaymentHash(Sha256::hash(&preimage).into_inner())
1327 }
1328
1329 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1330         (0, Legacy) => {
1331                 (0, session_privs, required),
1332         },
1333         (1, Fulfilled) => {
1334                 (0, session_privs, required),
1335                 (1, payment_hash, option),
1336                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1337         },
1338         (2, Retryable) => {
1339                 (0, session_privs, required),
1340                 (1, pending_fee_msat, option),
1341                 (2, payment_hash, required),
1342                 (3, payment_params, option),
1343                 (4, payment_secret, option),
1344                 (5, keysend_preimage, option),
1345                 (6, total_msat, required),
1346                 (8, pending_amt_msat, required),
1347                 (10, starting_block_height, required),
1348                 (not_written, retry_strategy, (static_value, None)),
1349                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1350         },
1351         (3, Abandoned) => {
1352                 (0, session_privs, required),
1353                 (2, payment_hash, required),
1354         },
1355 );
1356
1357 #[cfg(test)]
1358 mod tests {
1359         use bitcoin::blockdata::constants::genesis_block;
1360         use bitcoin::network::constants::Network;
1361         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1362
1363         use crate::ln::PaymentHash;
1364         use crate::ln::channelmanager::PaymentId;
1365         use crate::ln::msgs::{ErrorAction, LightningError};
1366         use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1367         use crate::routing::gossip::NetworkGraph;
1368         use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
1369         use crate::sync::{Arc, Mutex};
1370         use crate::util::events::Event;
1371         use crate::util::test_utils;
1372
1373         #[test]
1374         #[cfg(feature = "std")]
1375         fn fails_paying_after_expiration() {
1376                 do_fails_paying_after_expiration(false);
1377                 do_fails_paying_after_expiration(true);
1378         }
1379         #[cfg(feature = "std")]
1380         fn do_fails_paying_after_expiration(on_retry: bool) {
1381                 let outbound_payments = OutboundPayments::new();
1382                 let logger = test_utils::TestLogger::new();
1383                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1384                 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1385                 let scorer = Mutex::new(test_utils::TestScorer::new());
1386                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1387                 let secp_ctx = Secp256k1::new();
1388                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1389
1390                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1391                 let payment_params = PaymentParameters::from_node_id(
1392                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1393                                 0
1394                         ).with_expiry_time(past_expiry_time);
1395                 let expired_route_params = RouteParameters {
1396                         payment_params,
1397                         final_value_msat: 0,
1398                         final_cltv_expiry_delta: 0,
1399                 };
1400                 let pending_events = Mutex::new(Vec::new());
1401                 if on_retry {
1402                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]), None,
1403                         &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
1404                         Some(expired_route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
1405                         outbound_payments.retry_payment_internal(
1406                                 PaymentId([0; 32]), PaymentHash([0; 32]), expired_route_params, &&router, vec![],
1407                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1408                                 &|_, _, _, _, _, _, _, _, _| Ok(()));
1409                         let events = pending_events.lock().unwrap();
1410                         assert_eq!(events.len(), 1);
1411                         if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1412                 } else {
1413                         let err = outbound_payments.send_payment(
1414                                 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1415                                 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1416                                 &pending_events, |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1417                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1418                 }
1419         }
1420
1421         #[test]
1422         fn find_route_error() {
1423                 do_find_route_error(false);
1424                 do_find_route_error(true);
1425         }
1426         fn do_find_route_error(on_retry: bool) {
1427                 let outbound_payments = OutboundPayments::new();
1428                 let logger = test_utils::TestLogger::new();
1429                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1430                 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1431                 let scorer = Mutex::new(test_utils::TestScorer::new());
1432                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1433                 let secp_ctx = Secp256k1::new();
1434                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1435
1436                 let payment_params = PaymentParameters::from_node_id(
1437                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1438                 let route_params = RouteParameters {
1439                         payment_params,
1440                         final_value_msat: 0,
1441                         final_cltv_expiry_delta: 0,
1442                 };
1443                 router.expect_find_route(route_params.clone(),
1444                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1445
1446                 let pending_events = Mutex::new(Vec::new());
1447                 if on_retry {
1448                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]), None,
1449                                 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
1450                                 Some(route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
1451                         outbound_payments.retry_payment_internal(
1452                                 PaymentId([0; 32]), PaymentHash([0; 32]), route_params, &&router, vec![],
1453                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1454                                 &|_, _, _, _, _, _, _, _, _| Ok(()));
1455                         let events = pending_events.lock().unwrap();
1456                         assert_eq!(events.len(), 1);
1457                         if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1458                 } else {
1459                         let err = outbound_payments.send_payment(
1460                                 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1461                                 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1462                                 &pending_events, |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1463                         if let RetryableSendFailure::RouteNotFound = err {
1464                         } else { panic!("Unexpected error"); }
1465                 }
1466         }
1467 }