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