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