636bc13a90b7adbe64facaadb253b7a4cfdf1c7e
[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, "length-0 path in route");
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 {
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                         for (idx, hop) in path.hops.iter().enumerate() {
1008                                 if idx != path.hops.len() - 1 && hop.pubkey == our_node_id {
1009                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1010                                         continue 'path_check;
1011                                 }
1012                         }
1013                         total_value += path.final_value_msat();
1014                         path_errs.push(Ok(()));
1015                 }
1016                 if path_errs.iter().any(|e| e.is_err()) {
1017                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1018                 }
1019                 if let Some(amt_msat) = recv_value_msat {
1020                         total_value = amt_msat;
1021                 }
1022
1023                 let cur_height = best_block_height + 1;
1024                 let mut results = Vec::new();
1025                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1026                 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1027                         let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
1028                                 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
1029                         match path_res {
1030                                 Ok(_) => {},
1031                                 Err(APIError::MonitorUpdateInProgress) => {
1032                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
1033                                         // considered "in flight" and we shouldn't remove it from the
1034                                         // PendingOutboundPayment set.
1035                                 },
1036                                 Err(_) => {
1037                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1038                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1039                                                 let removed = payment.remove(&session_priv, Some(path));
1040                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1041                                         } else {
1042                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
1043                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1044                                         }
1045                                 }
1046                         }
1047                         results.push(path_res);
1048                 }
1049                 let mut has_ok = false;
1050                 let mut has_err = false;
1051                 let mut pending_amt_unsent = 0;
1052                 for (res, path) in results.iter().zip(route.paths.iter()) {
1053                         if res.is_ok() { has_ok = true; }
1054                         if res.is_err() { has_err = true; }
1055                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1056                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1057                                 // PartialFailure.
1058                                 has_err = true;
1059                                 has_ok = true;
1060                         } else if res.is_err() {
1061                                 pending_amt_unsent += path.final_value_msat();
1062                         }
1063                 }
1064                 if has_err && has_ok {
1065                         Err(PaymentSendFailure::PartialFailure {
1066                                 results,
1067                                 payment_id,
1068                                 failed_paths_retry: if pending_amt_unsent != 0 {
1069                                         if let Some(payment_params) = &route.payment_params {
1070                                                 Some(RouteParameters {
1071                                                         payment_params: payment_params.clone(),
1072                                                         final_value_msat: pending_amt_unsent,
1073                                                 })
1074                                         } else { None }
1075                                 } else { None },
1076                         })
1077                 } else if has_err {
1078                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1079                 } else {
1080                         Ok(())
1081                 }
1082         }
1083
1084         #[cfg(test)]
1085         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1086                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1087                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1088                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1089                 send_payment_along_path: F
1090         ) -> Result<(), PaymentSendFailure>
1091         where
1092                 NS::Target: NodeSigner,
1093                 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1094                         &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1095         {
1096                 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1097                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1098                         &send_payment_along_path)
1099                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1100         }
1101
1102         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1103         // map as the payment is free to be resent.
1104         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1105                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1106                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1107                         debug_assert!(removed, "We should always have a pending payment to remove here");
1108                 }
1109         }
1110
1111         pub(super) fn claim_htlc<L: Deref>(
1112                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1113                 path: Path, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1114         ) where L::Target: Logger {
1115                 let mut session_priv_bytes = [0; 32];
1116                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1117                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1118                 let mut pending_events = pending_events.lock().unwrap();
1119                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1120                         if !payment.get().is_fulfilled() {
1121                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1122                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1123                                 pending_events.push(
1124                                         events::Event::PaymentSent {
1125                                                 payment_id: Some(payment_id),
1126                                                 payment_preimage,
1127                                                 payment_hash,
1128                                                 fee_paid_msat,
1129                                         }
1130                                 );
1131                                 payment.get_mut().mark_fulfilled();
1132                         }
1133
1134                         if from_onchain {
1135                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1136                                 // This could potentially lead to removing a pending payment too early,
1137                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1138                                 // restart.
1139                                 // TODO: We should have a second monitor event that informs us of payments
1140                                 // irrevocably fulfilled.
1141                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1142                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1143                                         pending_events.push(
1144                                                 events::Event::PaymentPathSuccessful {
1145                                                         payment_id,
1146                                                         payment_hash,
1147                                                         path,
1148                                                 }
1149                                         );
1150                                 }
1151                         }
1152                 } else {
1153                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1154                 }
1155         }
1156
1157         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
1158                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1159                 let mut pending_events = pending_events.lock().unwrap();
1160                 for source in sources {
1161                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1162                                 let mut session_priv_bytes = [0; 32];
1163                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1164                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1165                                         assert!(payment.get().is_fulfilled());
1166                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1167                                                 pending_events.push(
1168                                                         events::Event::PaymentPathSuccessful {
1169                                                                 payment_id,
1170                                                                 payment_hash: payment.get().payment_hash(),
1171                                                                 path,
1172                                                         }
1173                                                 );
1174                                         }
1175                                 }
1176                         }
1177                 }
1178         }
1179
1180         pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
1181                 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1182                 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1183                 // this could race the user making a duplicate send_payment call and our idempotency
1184                 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1185                 // removal. This should be more than sufficient to ensure the idempotency of any
1186                 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1187                 // processed.
1188                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1189                 let pending_events = pending_events.lock().unwrap();
1190                 pending_outbound_payments.retain(|payment_id, payment| {
1191                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1192                                 let mut no_remaining_entries = session_privs.is_empty();
1193                                 if no_remaining_entries {
1194                                         for ev in pending_events.iter() {
1195                                                 match ev {
1196                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1197                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1198                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1199                                                                         if payment_id == ev_payment_id {
1200                                                                                 no_remaining_entries = false;
1201                                                                                 break;
1202                                                                         }
1203                                                                 },
1204                                                         _ => {},
1205                                                 }
1206                                         }
1207                                 }
1208                                 if no_remaining_entries {
1209                                         *timer_ticks_without_htlcs += 1;
1210                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1211                                 } else {
1212                                         *timer_ticks_without_htlcs = 0;
1213                                         true
1214                                 }
1215                         } else { true }
1216                 });
1217         }
1218
1219         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1220         pub(super) fn fail_htlc<L: Deref>(
1221                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1222                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId, probing_cookie_secret: [u8; 32],
1223                 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1224         ) -> bool where L::Target: Logger {
1225                 #[cfg(test)]
1226                 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1227                 #[cfg(not(test))]
1228                 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1229
1230                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1231                 let mut session_priv_bytes = [0; 32];
1232                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1233                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1234
1235                 // If any payments already need retry, there's no need to generate a redundant
1236                 // `PendingHTLCsForwardable`.
1237                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1238                         let mut awaiting_retry = false;
1239                         if pmt.is_auto_retryable_now() {
1240                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1241                                         if pending_amt_msat < total_msat {
1242                                                 awaiting_retry = true;
1243                                         }
1244                                 }
1245                         }
1246                         awaiting_retry
1247                 });
1248
1249                 let mut full_failure_ev = None;
1250                 let mut pending_retry_ev = false;
1251                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1252                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1253                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1254                                 return false
1255                         }
1256                         if payment.get().is_fulfilled() {
1257                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1258                                 return false
1259                         }
1260                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1261                         if let Some(scid) = short_channel_id {
1262                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1263                                 // process_onion_failure we should close that channel as it implies our
1264                                 // next-hop is needlessly blaming us!
1265                                 payment.get_mut().insert_previously_failed_scid(scid);
1266                         }
1267
1268                         if payment_is_probe || !is_retryable_now || !payment_retryable {
1269                                 let reason = if !payment_retryable {
1270                                         PaymentFailureReason::RecipientRejected
1271                                 } else {
1272                                         PaymentFailureReason::RetriesExhausted
1273                                 };
1274                                 payment.get_mut().mark_abandoned(reason);
1275                                 is_retryable_now = false;
1276                         }
1277                         if payment.get().remaining_parts() == 0 {
1278                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1279                                         if !payment_is_probe {
1280                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1281                                                         payment_id: *payment_id,
1282                                                         payment_hash: *payment_hash,
1283                                                         reason: *reason,
1284                                                 });
1285                                         }
1286                                         payment.remove();
1287                                 }
1288                         }
1289                         is_retryable_now
1290                 } else {
1291                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1292                         return false
1293                 };
1294                 core::mem::drop(outbounds);
1295                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1296
1297                 let path_failure = {
1298                         if payment_is_probe {
1299                                 if !payment_retryable {
1300                                         events::Event::ProbeSuccessful {
1301                                                 payment_id: *payment_id,
1302                                                 payment_hash: payment_hash.clone(),
1303                                                 path: path.clone(),
1304                                         }
1305                                 } else {
1306                                         events::Event::ProbeFailed {
1307                                                 payment_id: *payment_id,
1308                                                 payment_hash: payment_hash.clone(),
1309                                                 path: path.clone(),
1310                                                 short_channel_id,
1311                                         }
1312                                 }
1313                         } else {
1314                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1315                                 // payment will sit in our outbounds forever.
1316                                 if attempts_remaining && !already_awaiting_retry {
1317                                         debug_assert!(full_failure_ev.is_none());
1318                                         pending_retry_ev = true;
1319                                 }
1320                                 events::Event::PaymentPathFailed {
1321                                         payment_id: Some(*payment_id),
1322                                         payment_hash: payment_hash.clone(),
1323                                         payment_failed_permanently: !payment_retryable,
1324                                         failure: events::PathFailure::OnPath { network_update },
1325                                         path: path.clone(),
1326                                         short_channel_id,
1327                                         #[cfg(test)]
1328                                         error_code: onion_error_code,
1329                                         #[cfg(test)]
1330                                         error_data: onion_error_data
1331                                 }
1332                         }
1333                 };
1334                 let mut pending_events = pending_events.lock().unwrap();
1335                 pending_events.push(path_failure);
1336                 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1337                 pending_retry_ev
1338         }
1339
1340         pub(super) fn abandon_payment(
1341                 &self, payment_id: PaymentId, reason: PaymentFailureReason, pending_events: &Mutex<Vec<events::Event>>
1342         ) {
1343                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1344                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1345                         payment.get_mut().mark_abandoned(reason);
1346                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1347                                 if payment.get().remaining_parts() == 0 {
1348                                         pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1349                                                 payment_id,
1350                                                 payment_hash: *payment_hash,
1351                                                 reason: *reason,
1352                                         });
1353                                         payment.remove();
1354                                 }
1355                         }
1356                 }
1357         }
1358
1359         #[cfg(test)]
1360         pub fn has_pending_payments(&self) -> bool {
1361                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1362         }
1363
1364         #[cfg(test)]
1365         pub fn clear_pending_payments(&self) {
1366                 self.pending_outbound_payments.lock().unwrap().clear()
1367         }
1368 }
1369
1370 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1371 /// payment probe.
1372 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1373         probing_cookie_secret: [u8; 32]) -> bool
1374 {
1375         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1376         target_payment_hash == *payment_hash
1377 }
1378
1379 /// Returns the 'probing cookie' for the given [`PaymentId`].
1380 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1381         let mut preimage = [0u8; 64];
1382         preimage[..32].copy_from_slice(&probing_cookie_secret);
1383         preimage[32..].copy_from_slice(&payment_id.0);
1384         PaymentHash(Sha256::hash(&preimage).into_inner())
1385 }
1386
1387 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1388         (0, Legacy) => {
1389                 (0, session_privs, required),
1390         },
1391         (1, Fulfilled) => {
1392                 (0, session_privs, required),
1393                 (1, payment_hash, option),
1394                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1395         },
1396         (2, Retryable) => {
1397                 (0, session_privs, required),
1398                 (1, pending_fee_msat, option),
1399                 (2, payment_hash, required),
1400                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1401                 // never see it - `payment_params` was added here after the field was added/required.
1402                 (3, payment_params, (option: ReadableArgs, 0)),
1403                 (4, payment_secret, option),
1404                 (5, keysend_preimage, option),
1405                 (6, total_msat, required),
1406                 (7, payment_metadata, option),
1407                 (8, pending_amt_msat, required),
1408                 (10, starting_block_height, required),
1409                 (not_written, retry_strategy, (static_value, None)),
1410                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1411         },
1412         (3, Abandoned) => {
1413                 (0, session_privs, required),
1414                 (1, reason, option),
1415                 (2, payment_hash, required),
1416         },
1417 );
1418
1419 #[cfg(test)]
1420 mod tests {
1421         use bitcoin::network::constants::Network;
1422         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1423
1424         use crate::events::{Event, PathFailure, PaymentFailureReason};
1425         use crate::ln::PaymentHash;
1426         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1427         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1428         use crate::ln::msgs::{ErrorAction, LightningError};
1429         use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1430         use crate::routing::gossip::NetworkGraph;
1431         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1432         use crate::sync::{Arc, Mutex};
1433         use crate::util::errors::APIError;
1434         use crate::util::test_utils;
1435
1436         #[test]
1437         #[cfg(feature = "std")]
1438         fn fails_paying_after_expiration() {
1439                 do_fails_paying_after_expiration(false);
1440                 do_fails_paying_after_expiration(true);
1441         }
1442         #[cfg(feature = "std")]
1443         fn do_fails_paying_after_expiration(on_retry: bool) {
1444                 let outbound_payments = OutboundPayments::new();
1445                 let logger = test_utils::TestLogger::new();
1446                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1447                 let scorer = Mutex::new(test_utils::TestScorer::new());
1448                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1449                 let secp_ctx = Secp256k1::new();
1450                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1451
1452                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1453                 let payment_params = PaymentParameters::from_node_id(
1454                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1455                                 0
1456                         ).with_expiry_time(past_expiry_time);
1457                 let expired_route_params = RouteParameters {
1458                         payment_params,
1459                         final_value_msat: 0,
1460                 };
1461                 let pending_events = Mutex::new(Vec::new());
1462                 if on_retry {
1463                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1464                                 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1465                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1466                                 &&keys_manager, 0).unwrap();
1467                         outbound_payments.retry_payment_internal(
1468                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1469                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1470                                 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1471                         let events = pending_events.lock().unwrap();
1472                         assert_eq!(events.len(), 1);
1473                         if let Event::PaymentFailed { ref reason, .. } = events[0] {
1474                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1475                         } else { panic!("Unexpected event"); }
1476                 } else {
1477                         let err = outbound_payments.send_payment(
1478                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1479                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1480                                 &&keys_manager, &&keys_manager, 0, &&logger,
1481                                 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1482                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1483                 }
1484         }
1485
1486         #[test]
1487         fn find_route_error() {
1488                 do_find_route_error(false);
1489                 do_find_route_error(true);
1490         }
1491         fn do_find_route_error(on_retry: bool) {
1492                 let outbound_payments = OutboundPayments::new();
1493                 let logger = test_utils::TestLogger::new();
1494                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1495                 let scorer = Mutex::new(test_utils::TestScorer::new());
1496                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1497                 let secp_ctx = Secp256k1::new();
1498                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1499
1500                 let payment_params = PaymentParameters::from_node_id(
1501                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1502                 let route_params = RouteParameters {
1503                         payment_params,
1504                         final_value_msat: 0,
1505                 };
1506                 router.expect_find_route(route_params.clone(),
1507                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1508
1509                 let pending_events = Mutex::new(Vec::new());
1510                 if on_retry {
1511                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1512                                 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1513                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1514                                 &&keys_manager, 0).unwrap();
1515                         outbound_payments.retry_payment_internal(
1516                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1517                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1518                                 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1519                         let events = pending_events.lock().unwrap();
1520                         assert_eq!(events.len(), 1);
1521                         if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1522                 } else {
1523                         let err = outbound_payments.send_payment(
1524                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1525                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1526                                 &&keys_manager, &&keys_manager, 0, &&logger,
1527                                 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1528                         if let RetryableSendFailure::RouteNotFound = err {
1529                         } else { panic!("Unexpected error"); }
1530                 }
1531         }
1532
1533         #[test]
1534         fn initial_send_payment_path_failed_evs() {
1535                 let outbound_payments = OutboundPayments::new();
1536                 let logger = test_utils::TestLogger::new();
1537                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1538                 let scorer = Mutex::new(test_utils::TestScorer::new());
1539                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1540                 let secp_ctx = Secp256k1::new();
1541                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1542
1543                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1544                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1545                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1546                 let route_params = RouteParameters {
1547                         payment_params: payment_params.clone(),
1548                         final_value_msat: 0,
1549                 };
1550                 let failed_scid = 42;
1551                 let route = Route {
1552                         paths: vec![Path { hops: vec![RouteHop {
1553                                 pubkey: receiver_pk,
1554                                 node_features: NodeFeatures::empty(),
1555                                 short_channel_id: failed_scid,
1556                                 channel_features: ChannelFeatures::empty(),
1557                                 fee_msat: 0,
1558                                 cltv_expiry_delta: 0,
1559                         }], blinded_tail: None }],
1560                         payment_params: Some(payment_params),
1561                 };
1562                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1563                 let mut route_params_w_failed_scid = route_params.clone();
1564                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1565                 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1566                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1567                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1568
1569                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1570                 // PaymentPathFailed event.
1571                 let pending_events = Mutex::new(Vec::new());
1572                 outbound_payments.send_payment(
1573                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1574                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1575                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1576                         |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1577                         .unwrap();
1578                 let mut events = pending_events.lock().unwrap();
1579                 assert_eq!(events.len(), 2);
1580                 if let Event::PaymentPathFailed {
1581                         short_channel_id,
1582                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0]
1583                 {
1584                         assert_eq!(short_channel_id, Some(failed_scid));
1585                 } else { panic!("Unexpected event"); }
1586                 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
1587                 events.clear();
1588                 core::mem::drop(events);
1589
1590                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1591                 outbound_payments.send_payment(
1592                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1593                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1594                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1595                         |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1596                 assert_eq!(pending_events.lock().unwrap().len(), 0);
1597
1598                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1599                 outbound_payments.send_payment(
1600                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1601                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1602                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1603                         |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1604                         .unwrap();
1605                 let events = pending_events.lock().unwrap();
1606                 assert_eq!(events.len(), 2);
1607                 if let Event::PaymentPathFailed {
1608                         short_channel_id,
1609                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0]
1610                 {
1611                         assert_eq!(short_channel_id, None);
1612                 } else { panic!("Unexpected event"); }
1613                 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
1614         }
1615 }