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