e4158a89ada4287bebdfce1689e88442629e848f
[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::sign::{EntropySource, NodeSigner, Recipient};
17 use crate::events::{self, PaymentFailureReason};
18 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::channelmanager::{ChannelDetails, EventCompletionAction, HTLCSource, PaymentId};
20 use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
21 use crate::offers::invoice::Bolt12Invoice;
22 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
23 use crate::util::errors::APIError;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(not(feature = "no-std"), test))]
27 use crate::util::time::tests::SinceEpoch;
28 use crate::util::ser::ReadableArgs;
29
30 use core::fmt::{self, Display, Formatter};
31 use core::ops::Deref;
32 use core::time::Duration;
33
34 use crate::prelude::*;
35 use crate::sync::Mutex;
36
37 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
38 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
39 ///
40 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
41 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
42
43 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
44 /// and later, also stores information for retrying the payment.
45 pub(crate) enum PendingOutboundPayment {
46         Legacy {
47                 session_privs: HashSet<[u8; 32]>,
48         },
49         AwaitingInvoice {
50                 expiration: StaleExpiration,
51                 retry_strategy: Retry,
52                 max_total_routing_fee_msat: Option<u64>,
53         },
54         InvoiceReceived {
55                 payment_hash: PaymentHash,
56                 retry_strategy: Retry,
57                 // Note this field is currently just replicated from AwaitingInvoice but not actually
58                 // used anywhere.
59                 max_total_routing_fee_msat: Option<u64>,
60         },
61         Retryable {
62                 retry_strategy: Option<Retry>,
63                 attempts: PaymentAttempts,
64                 payment_params: Option<PaymentParameters>,
65                 session_privs: HashSet<[u8; 32]>,
66                 payment_hash: PaymentHash,
67                 payment_secret: Option<PaymentSecret>,
68                 payment_metadata: Option<Vec<u8>>,
69                 keysend_preimage: Option<PaymentPreimage>,
70                 custom_tlvs: Vec<(u64, Vec<u8>)>,
71                 pending_amt_msat: u64,
72                 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
73                 pending_fee_msat: Option<u64>,
74                 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
75                 total_msat: u64,
76                 /// Our best known block height at the time this payment was initiated.
77                 starting_block_height: u32,
78                 remaining_max_total_routing_fee_msat: Option<u64>,
79         },
80         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
81         /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
82         /// and add a pending payment that was already fulfilled.
83         Fulfilled {
84                 session_privs: HashSet<[u8; 32]>,
85                 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
86                 payment_hash: Option<PaymentHash>,
87                 timer_ticks_without_htlcs: u8,
88         },
89         /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
90         /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
91         Abandoned {
92                 session_privs: HashSet<[u8; 32]>,
93                 payment_hash: PaymentHash,
94                 /// Will be `None` if the payment was serialized before 0.0.115.
95                 reason: Option<PaymentFailureReason>,
96         },
97 }
98
99 impl PendingOutboundPayment {
100         fn increment_attempts(&mut self) {
101                 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
102                         attempts.count += 1;
103                 }
104         }
105         fn is_auto_retryable_now(&self) -> bool {
106                 match self {
107                         PendingOutboundPayment::Retryable {
108                                 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
109                         } => {
110                                 strategy.is_retryable_now(&attempts)
111                         },
112                         _ => false,
113                 }
114         }
115         fn is_retryable_now(&self) -> bool {
116                 match self {
117                         PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
118                                 // We're handling retries manually, we can always retry.
119                                 true
120                         },
121                         PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
122                                 strategy.is_retryable_now(&attempts)
123                         },
124                         _ => false,
125                 }
126         }
127         pub fn insert_previously_failed_scid(&mut self, scid: u64) {
128                 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
129                         params.previously_failed_channels.push(scid);
130                 }
131         }
132         fn is_awaiting_invoice(&self) -> bool {
133                 match self {
134                         PendingOutboundPayment::AwaitingInvoice { .. } => true,
135                         _ => false,
136                 }
137         }
138         pub(super) fn is_fulfilled(&self) -> bool {
139                 match self {
140                         PendingOutboundPayment::Fulfilled { .. } => true,
141                         _ => false,
142                 }
143         }
144         pub(super) fn abandoned(&self) -> bool {
145                 match self {
146                         PendingOutboundPayment::Abandoned { .. } => true,
147                         _ => false,
148                 }
149         }
150         fn get_pending_fee_msat(&self) -> Option<u64> {
151                 match self {
152                         PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
153                         _ => None,
154                 }
155         }
156
157         fn payment_hash(&self) -> Option<PaymentHash> {
158                 match self {
159                         PendingOutboundPayment::Legacy { .. } => None,
160                         PendingOutboundPayment::AwaitingInvoice { .. } => None,
161                         PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
162                         PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
163                         PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
164                         PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
165                 }
166         }
167
168         fn mark_fulfilled(&mut self) {
169                 let mut session_privs = HashSet::new();
170                 core::mem::swap(&mut session_privs, match self {
171                         PendingOutboundPayment::Legacy { session_privs } |
172                                 PendingOutboundPayment::Retryable { session_privs, .. } |
173                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
174                                 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
175                         PendingOutboundPayment::AwaitingInvoice { .. } |
176                                 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
177                 });
178                 let payment_hash = self.payment_hash();
179                 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
180         }
181
182         fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
183                 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
184                         let mut our_session_privs = HashSet::new();
185                         core::mem::swap(&mut our_session_privs, session_privs);
186                         *self = PendingOutboundPayment::Abandoned {
187                                 session_privs: our_session_privs,
188                                 payment_hash: *payment_hash,
189                                 reason: Some(reason)
190                         };
191                 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash, .. } = self {
192                         *self = PendingOutboundPayment::Abandoned {
193                                 session_privs: HashSet::new(),
194                                 payment_hash: *payment_hash,
195                                 reason: Some(reason)
196                         };
197                 }
198         }
199
200         /// panics if path is None and !self.is_fulfilled
201         fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
202                 let remove_res = match self {
203                         PendingOutboundPayment::Legacy { session_privs } |
204                                 PendingOutboundPayment::Retryable { session_privs, .. } |
205                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
206                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
207                                         session_privs.remove(session_priv)
208                                 },
209                         PendingOutboundPayment::AwaitingInvoice { .. } |
210                                 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
211                 };
212                 if remove_res {
213                         if let PendingOutboundPayment::Retryable {
214                                 ref mut pending_amt_msat, ref mut pending_fee_msat,
215                                 ref mut remaining_max_total_routing_fee_msat, ..
216                         } = self {
217                                 let path = path.expect("Removing a failed payment should always come with a path");
218                                 *pending_amt_msat -= path.final_value_msat();
219                                 let path_fee_msat = path.fee_msat();
220                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
221                                         *fee_msat -= path_fee_msat;
222                                 }
223
224                                 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
225                                         *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
226                                 }
227                         }
228                 }
229                 remove_res
230         }
231
232         pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
233                 let insert_res = match self {
234                         PendingOutboundPayment::Legacy { session_privs } |
235                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
236                                         session_privs.insert(session_priv)
237                                 },
238                         PendingOutboundPayment::AwaitingInvoice { .. } |
239                                 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
240                         PendingOutboundPayment::Fulfilled { .. } => false,
241                         PendingOutboundPayment::Abandoned { .. } => false,
242                 };
243                 if insert_res {
244                         if let PendingOutboundPayment::Retryable {
245                                 ref mut pending_amt_msat, ref mut pending_fee_msat,
246                                 ref mut remaining_max_total_routing_fee_msat, ..
247                         } = self {
248                                         *pending_amt_msat += path.final_value_msat();
249                                         let path_fee_msat = path.fee_msat();
250                                         if let Some(fee_msat) = pending_fee_msat.as_mut() {
251                                                 *fee_msat += path_fee_msat;
252                                         }
253
254                                         if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
255                                                 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
256                                         }
257                         }
258                 }
259                 insert_res
260         }
261
262         pub(super) fn remaining_parts(&self) -> usize {
263                 match self {
264                         PendingOutboundPayment::Legacy { session_privs } |
265                                 PendingOutboundPayment::Retryable { session_privs, .. } |
266                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
267                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
268                                         session_privs.len()
269                                 },
270                         PendingOutboundPayment::AwaitingInvoice { .. } => 0,
271                         PendingOutboundPayment::InvoiceReceived { .. } => 0,
272                 }
273         }
274 }
275
276 /// Strategies available to retry payment path failures.
277 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
278 pub enum Retry {
279         /// Max number of attempts to retry payment.
280         ///
281         /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
282         /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
283         /// were retried along a route from a single call to [`Router::find_route_with_id`].
284         Attempts(u32),
285         #[cfg(not(feature = "no-std"))]
286         /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
287         /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
288         ///
289         /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
290         Timeout(core::time::Duration),
291 }
292
293 #[cfg(feature = "no-std")]
294 impl_writeable_tlv_based_enum!(Retry,
295         ;
296         (0, Attempts)
297 );
298
299 #[cfg(not(feature = "no-std"))]
300 impl_writeable_tlv_based_enum!(Retry,
301         ;
302         (0, Attempts),
303         (2, Timeout)
304 );
305
306 impl Retry {
307         pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
308                 match (self, attempts) {
309                         (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
310                                 max_retry_count > count
311                         },
312                         #[cfg(all(not(feature = "no-std"), not(test)))]
313                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
314                                 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
315                         #[cfg(all(not(feature = "no-std"), test))]
316                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
317                                 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
318                 }
319         }
320 }
321
322 #[cfg(feature = "std")]
323 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
324         if let Some(expiry_time) = route_params.payment_params.expiry_time {
325                 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
326                         return elapsed > core::time::Duration::from_secs(expiry_time)
327                 }
328         }
329         false
330 }
331
332 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
333
334 /// Storing minimal payment attempts information required for determining if a outbound payment can
335 /// be retried.
336 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
337         /// This count will be incremented only after the result of the attempt is known. When it's 0,
338         /// it means the result of the first attempt is not known yet.
339         pub(crate) count: u32,
340         /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
341         #[cfg(not(feature = "no-std"))]
342         first_attempted_at: T,
343         #[cfg(feature = "no-std")]
344         phantom: core::marker::PhantomData<T>,
345
346 }
347
348 #[cfg(not(any(feature = "no-std", test)))]
349 type ConfiguredTime = crate::util::time::MonotonicTime;
350 #[cfg(feature = "no-std")]
351 type ConfiguredTime = crate::util::time::Eternity;
352 #[cfg(all(not(feature = "no-std"), test))]
353 type ConfiguredTime = SinceEpoch;
354
355 impl<T: Time> PaymentAttemptsUsingTime<T> {
356         pub(crate) fn new() -> Self {
357                 PaymentAttemptsUsingTime {
358                         count: 0,
359                         #[cfg(not(feature = "no-std"))]
360                         first_attempted_at: T::now(),
361                         #[cfg(feature = "no-std")]
362                         phantom: core::marker::PhantomData,
363                 }
364         }
365 }
366
367 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
368         fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
369                 #[cfg(feature = "no-std")]
370                 return write!(f, "attempts: {}", self.count);
371                 #[cfg(not(feature = "no-std"))]
372                 return write!(
373                         f,
374                         "attempts: {}, duration: {}s",
375                         self.count,
376                         T::now().duration_since(self.first_attempted_at).as_secs()
377                 );
378         }
379 }
380
381 /// How long before a [`PendingOutboundPayment::AwaitingInvoice`] should be considered stale and
382 /// candidate for removal in [`OutboundPayments::remove_stale_payments`].
383 #[derive(Clone, Copy)]
384 pub(crate) enum StaleExpiration {
385         /// Number of times [`OutboundPayments::remove_stale_payments`] is called.
386         TimerTicks(u64),
387         /// Duration since the Unix epoch.
388         AbsoluteTimeout(core::time::Duration),
389 }
390
391 impl_writeable_tlv_based_enum!(StaleExpiration,
392         ;
393         (0, TimerTicks),
394         (2, AbsoluteTimeout)
395 );
396
397 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
398 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
399 ///
400 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
401 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
402 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
403 #[derive(Clone, Debug, PartialEq, Eq)]
404 pub enum RetryableSendFailure {
405         /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
406         /// that this error is *not* caused by [`Retry::Timeout`].
407         ///
408         /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
409         PaymentExpired,
410         /// We were unable to find a route to the destination.
411         RouteNotFound,
412         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
413         /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
414         ///
415         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
416         /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
417         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
418         DuplicatePayment,
419 }
420
421 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
422 /// of several states. This enum is returned as the Err() type describing which state the payment
423 /// is in, see the description of individual enum states for more.
424 ///
425 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
426 #[derive(Clone, Debug, PartialEq, Eq)]
427 pub enum PaymentSendFailure {
428         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
429         /// send the payment at all.
430         ///
431         /// You can freely resend the payment in full (with the parameter error fixed).
432         ///
433         /// Because the payment failed outright, no payment tracking is done and no
434         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
435         ///
436         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
437         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
438         ParameterError(APIError),
439         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
440         /// from attempting to send the payment at all.
441         ///
442         /// You can freely resend the payment in full (with the parameter error fixed).
443         ///
444         /// Because the payment failed outright, no payment tracking is done and no
445         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
446         ///
447         /// The results here are ordered the same as the paths in the route object which was passed to
448         /// send_payment.
449         ///
450         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
451         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
452         PathParameterError(Vec<Result<(), APIError>>),
453         /// All paths which were attempted failed to send, with no channel state change taking place.
454         /// You can freely resend the payment in full (though you probably want to do so over different
455         /// paths than the ones selected).
456         ///
457         /// Because the payment failed outright, no payment tracking is done and no
458         /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
459         ///
460         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
461         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
462         AllFailedResendSafe(Vec<APIError>),
463         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
464         /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
465         ///
466         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
467         /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
468         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
469         DuplicatePayment,
470         /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
471         /// some paths have irrevocably committed to the HTLC.
472         ///
473         /// The results here are ordered the same as the paths in the route object that was passed to
474         /// send_payment.
475         ///
476         /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
477         /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
478         ///
479         /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
480         PartialFailure {
481                 /// The errors themselves, in the same order as the paths from the route.
482                 results: Vec<Result<(), APIError>>,
483                 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
484                 /// contain a [`RouteParameters`] object for the failing paths.
485                 failed_paths_retry: Option<RouteParameters>,
486                 /// The payment id for the payment, which is now at least partially pending.
487                 payment_id: PaymentId,
488         },
489 }
490
491 /// An error when attempting to pay a BOLT 12 invoice.
492 #[derive(Clone, Debug, PartialEq, Eq)]
493 pub(super) enum Bolt12PaymentError {
494         /// The invoice was not requested.
495         UnexpectedInvoice,
496         /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
497         DuplicateInvoice,
498 }
499
500 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
501 /// [`Event::ProbeFailed`].
502 ///
503 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
504 #[derive(Clone, Debug, PartialEq, Eq)]
505 pub enum ProbeSendFailure {
506         /// We were unable to find a route to the destination.
507         RouteNotFound,
508         /// We failed to send the payment probes.
509         SendingFailed(PaymentSendFailure),
510 }
511
512 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
513 ///
514 /// This should generally be constructed with data communicated to us from the recipient (via a
515 /// BOLT11 or BOLT12 invoice).
516 #[derive(Clone, Debug, PartialEq, Eq)]
517 pub struct RecipientOnionFields {
518         /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
519         /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
520         /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
521         /// attacks.
522         ///
523         /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
524         /// multi-path payments require a recipient-provided secret.
525         ///
526         /// Some implementations may reject spontaneous payments with payment secrets, so you may only
527         /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
528         /// recipient will not reject it.
529         pub payment_secret: Option<PaymentSecret>,
530         /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
531         /// arbitrary length. This gives recipients substantially more flexibility to receive
532         /// additional data.
533         ///
534         /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
535         /// scheme to authenticate received payments against expected payments and invoices, this field
536         /// is not used in LDK for received payments, and can be used to store arbitrary data in
537         /// invoices which will be received with the payment.
538         ///
539         /// Note that this field was added to the lightning specification more recently than
540         /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
541         /// may not be supported as universally.
542         pub payment_metadata: Option<Vec<u8>>,
543         /// See [`Self::custom_tlvs`] for more info.
544         pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
545 }
546
547 impl_writeable_tlv_based!(RecipientOnionFields, {
548         (0, payment_secret, option),
549         (1, custom_tlvs, optional_vec),
550         (2, payment_metadata, option),
551 });
552
553 impl RecipientOnionFields {
554         /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
555         /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
556         /// but do not require or provide any further data.
557         pub fn secret_only(payment_secret: PaymentSecret) -> Self {
558                 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
559         }
560
561         /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
562         /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
563         /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
564         /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
565         /// instead want to use [`RecipientOnionFields::secret_only`].
566         ///
567         /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
568         /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
569         pub fn spontaneous_empty() -> Self {
570                 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
571         }
572
573         /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
574         /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
575         /// respectively. TLV type numbers must be unique and within the range
576         /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
577         ///
578         /// This method will also error for types in the experimental range which have been
579         /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
580         ///
581         /// See [`Self::custom_tlvs`] for more info.
582         pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
583                 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
584                 let mut prev_type = None;
585                 for (typ, _) in custom_tlvs.iter() {
586                         if *typ < 1 << 16 { return Err(()); }
587                         if *typ == 5482373484 { return Err(()); } // keysend
588                         match prev_type {
589                                 Some(prev) if prev >= *typ => return Err(()),
590                                 _ => {},
591                         }
592                         prev_type = Some(*typ);
593                 }
594                 self.custom_tlvs = custom_tlvs;
595                 Ok(self)
596         }
597
598         /// Gets the custom TLVs that will be sent or have been received.
599         ///
600         /// Custom TLVs allow sending extra application-specific data with a payment. They provide
601         /// additional flexibility on top of payment metadata, as while other implementations may
602         /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
603         /// do not have this restriction.
604         ///
605         /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
606         /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
607         /// This is validated when setting this field using [`Self::with_custom_tlvs`].
608         #[cfg(not(c_bindings))]
609         pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
610                 &self.custom_tlvs
611         }
612
613         /// Gets the custom TLVs that will be sent or have been received.
614         ///
615         /// Custom TLVs allow sending extra application-specific data with a payment. They provide
616         /// additional flexibility on top of payment metadata, as while other implementations may
617         /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
618         /// do not have this restriction.
619         ///
620         /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
621         /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
622         /// This is validated when setting this field using [`Self::with_custom_tlvs`].
623         #[cfg(c_bindings)]
624         pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
625                 self.custom_tlvs.clone()
626         }
627
628         /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
629         /// have to make sure that some fields match exactly across the parts. For those that aren't
630         /// required to match, if they don't match we should remove them so as to not expose data
631         /// that's dependent on the HTLC receive order to users.
632         ///
633         /// Here we implement this, first checking compatibility then mutating two objects and then
634         /// dropping any remaining non-matching fields from both.
635         pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
636                 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
637                 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
638
639                 let tlvs = &mut self.custom_tlvs;
640                 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
641
642                 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
643                 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
644                 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
645
646                 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
647                 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
648
649                 Ok(())
650         }
651 }
652
653 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
654 pub(super) struct SendAlongPathArgs<'a> {
655         pub path: &'a Path,
656         pub payment_hash: &'a PaymentHash,
657         pub recipient_onion: RecipientOnionFields,
658         pub total_value: u64,
659         pub cur_height: u32,
660         pub payment_id: PaymentId,
661         pub keysend_preimage: &'a Option<PaymentPreimage>,
662         pub session_priv_bytes: [u8; 32],
663 }
664
665 pub(super) struct OutboundPayments {
666         pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
667         pub(super) retry_lock: Mutex<()>,
668 }
669
670 impl OutboundPayments {
671         pub(super) fn new() -> Self {
672                 Self {
673                         pending_outbound_payments: Mutex::new(HashMap::new()),
674                         retry_lock: Mutex::new(()),
675                 }
676         }
677
678         pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
679                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
680                 retry_strategy: Retry, route_params: RouteParameters, router: &R,
681                 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
682                 node_signer: &NS, best_block_height: u32, logger: &L,
683                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
684         ) -> Result<(), RetryableSendFailure>
685         where
686                 R::Target: Router,
687                 ES::Target: EntropySource,
688                 NS::Target: NodeSigner,
689                 L::Target: Logger,
690                 IH: Fn() -> InFlightHtlcs,
691                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
692         {
693                 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
694                         route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
695                         best_block_height, logger, pending_events, &send_payment_along_path)
696         }
697
698         pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
699                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
700                 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
701                 send_payment_along_path: F
702         ) -> Result<(), PaymentSendFailure>
703         where
704                 ES::Target: EntropySource,
705                 NS::Target: NodeSigner,
706                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
707         {
708                 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)?;
709                 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
710                         onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
711                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
712         }
713
714         pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
715                 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
716                 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
717                 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
718                 node_signer: &NS, best_block_height: u32, logger: &L,
719                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
720         ) -> Result<PaymentHash, RetryableSendFailure>
721         where
722                 R::Target: Router,
723                 ES::Target: EntropySource,
724                 NS::Target: NodeSigner,
725                 L::Target: Logger,
726                 IH: Fn() -> InFlightHtlcs,
727                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
728         {
729                 let preimage = payment_preimage
730                         .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
731                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
732                 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
733                         retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
734                         node_signer, best_block_height, logger, pending_events, send_payment_along_path)
735                         .map(|()| payment_hash)
736         }
737
738         pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
739                 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
740                 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
741                 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
742         ) -> Result<PaymentHash, PaymentSendFailure>
743         where
744                 ES::Target: EntropySource,
745                 NS::Target: NodeSigner,
746                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
747         {
748                 let preimage = payment_preimage
749                         .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
750                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
751                 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
752                         payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
753
754                 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
755                         payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
756                 ) {
757                         Ok(()) => Ok(payment_hash),
758                         Err(e) => {
759                                 self.remove_outbound_if_all_failed(payment_id, &e);
760                                 Err(e)
761                         }
762                 }
763         }
764
765         pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
766                 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
767                 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
768                 best_block_height: u32, logger: &L,
769                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
770                 send_payment_along_path: SP,
771         ) -> Result<(), Bolt12PaymentError>
772         where
773                 R::Target: Router,
774                 ES::Target: EntropySource,
775                 NS::Target: NodeSigner,
776                 L::Target: Logger,
777                 IH: Fn() -> InFlightHtlcs,
778                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
779         {
780                 let payment_hash = invoice.payment_hash();
781                 let max_total_routing_fee_msat;
782                 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
783                         hash_map::Entry::Occupied(entry) => match entry.get() {
784                                 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
785                                         max_total_routing_fee_msat = *max_total_fee;
786                                         *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
787                                                 payment_hash,
788                                                 retry_strategy: *retry_strategy,
789                                                 max_total_routing_fee_msat,
790                                         };
791                                 },
792                                 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
793                         },
794                         hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
795                 };
796
797                 let pay_params = PaymentParameters::from_bolt12_invoice(&invoice);
798                 let amount_msat = invoice.amount_msats();
799                 let mut route_params = RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
800                 if let Some(max_fee_msat) = max_total_routing_fee_msat {
801                         route_params.max_total_routing_fee_msat = Some(max_fee_msat);
802                 }
803
804                 self.find_route_and_send_payment(
805                         payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
806                         entropy_source, node_signer, best_block_height, logger, pending_events,
807                         &send_payment_along_path
808                 );
809
810                 Ok(())
811         }
812
813         pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
814                 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
815                 best_block_height: u32,
816                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
817                 send_payment_along_path: SP,
818         )
819         where
820                 R::Target: Router,
821                 ES::Target: EntropySource,
822                 NS::Target: NodeSigner,
823                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
824                 IH: Fn() -> InFlightHtlcs,
825                 FH: Fn() -> Vec<ChannelDetails>,
826                 L::Target: Logger,
827         {
828                 let _single_thread = self.retry_lock.lock().unwrap();
829                 loop {
830                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
831                         let mut retry_id_route_params = None;
832                         for (pmt_id, pmt) in outbounds.iter_mut() {
833                                 if pmt.is_auto_retryable_now() {
834                                         if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
835                                                 if pending_amt_msat < total_msat {
836                                                         retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
837                                                                 final_value_msat: *total_msat - *pending_amt_msat,
838                                                                 payment_params: params.clone(),
839                                                                 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
840                                                         }));
841                                                         break
842                                                 }
843                                         } else { debug_assert!(false); }
844                                 }
845                         }
846                         core::mem::drop(outbounds);
847                         if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
848                                 self.find_route_and_send_payment(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)
849                         } else { break }
850                 }
851
852                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
853                 outbounds.retain(|pmt_id, pmt| {
854                         let mut retain = true;
855                         if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
856                                 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
857                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
858                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
859                                                 payment_id: *pmt_id,
860                                                 payment_hash: *payment_hash,
861                                                 reason: *reason,
862                                         }, None));
863                                         retain = false;
864                                 }
865                         }
866                         retain
867                 });
868         }
869
870         pub(super) fn needs_abandon(&self) -> bool {
871                 let outbounds = self.pending_outbound_payments.lock().unwrap();
872                 outbounds.iter().any(|(_, pmt)|
873                         !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
874                         !pmt.is_awaiting_invoice())
875         }
876
877         /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
878         /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
879         ///
880         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
881         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
882         fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
883                 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
884                 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
885                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
886                 node_signer: &NS, best_block_height: u32, logger: &L,
887                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
888         ) -> Result<(), RetryableSendFailure>
889         where
890                 R::Target: Router,
891                 ES::Target: EntropySource,
892                 NS::Target: NodeSigner,
893                 L::Target: Logger,
894                 IH: Fn() -> InFlightHtlcs,
895                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
896         {
897                 #[cfg(feature = "std")] {
898                         if has_expired(&route_params) {
899                                 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
900                                         payment_id, payment_hash);
901                                 return Err(RetryableSendFailure::PaymentExpired)
902                         }
903                 }
904
905                 let mut route = router.find_route_with_id(
906                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
907                         Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
908                         payment_hash, payment_id,
909                 ).map_err(|_| {
910                         log_error!(logger, "Failed to find route for payment with id {} and hash {}",
911                                 payment_id, payment_hash);
912                         RetryableSendFailure::RouteNotFound
913                 })?;
914
915                 if route.route_params.as_ref() != Some(&route_params) {
916                         debug_assert!(false,
917                                 "Routers are expected to return a Route which includes the requested RouteParameters");
918                         route.route_params = Some(route_params.clone());
919                 }
920
921                 let onion_session_privs = self.add_new_pending_payment(payment_hash,
922                         recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
923                         Some(route_params.payment_params.clone()), entropy_source, best_block_height)
924                         .map_err(|_| {
925                                 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
926                                         payment_id, payment_hash);
927                                 RetryableSendFailure::DuplicatePayment
928                         })?;
929
930                 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
931                         onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
932                 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
933                         payment_id, payment_hash, res);
934                 if let Err(e) = res {
935                         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);
936                 }
937                 Ok(())
938         }
939
940         fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
941                 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
942                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
943                 node_signer: &NS, best_block_height: u32, logger: &L,
944                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
945         )
946         where
947                 R::Target: Router,
948                 ES::Target: EntropySource,
949                 NS::Target: NodeSigner,
950                 L::Target: Logger,
951                 IH: Fn() -> InFlightHtlcs,
952                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
953         {
954                 #[cfg(feature = "std")] {
955                         if has_expired(&route_params) {
956                                 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
957                                 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
958                                 return
959                         }
960                 }
961
962                 let mut route = match router.find_route_with_id(
963                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
964                         Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
965                         payment_hash, payment_id,
966                 ) {
967                         Ok(route) => route,
968                         Err(e) => {
969                                 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
970                                 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
971                                 return
972                         }
973                 };
974
975                 if route.route_params.as_ref() != Some(&route_params) {
976                         debug_assert!(false,
977                                 "Routers are expected to return a Route which includes the requested RouteParameters");
978                         route.route_params = Some(route_params.clone());
979                 }
980
981                 for path in route.paths.iter() {
982                         if path.hops.len() == 0 {
983                                 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
984                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
985                                 return
986                         }
987                 }
988
989                 macro_rules! abandon_with_entry {
990                         ($payment: expr, $reason: expr) => {
991                                 $payment.get_mut().mark_abandoned($reason);
992                                 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
993                                         if $payment.get().remaining_parts() == 0 {
994                                                 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
995                                                         payment_id,
996                                                         payment_hash,
997                                                         reason: *reason,
998                                                 }, None));
999                                                 $payment.remove();
1000                                         }
1001                                 }
1002                         }
1003                 }
1004                 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
1005                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1006                         match outbounds.entry(payment_id) {
1007                                 hash_map::Entry::Occupied(mut payment) => {
1008                                         match payment.get() {
1009                                                 PendingOutboundPayment::Retryable {
1010                                                         total_msat, keysend_preimage, payment_secret, payment_metadata,
1011                                                         custom_tlvs, pending_amt_msat, ..
1012                                                 } => {
1013                                                         const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1014                                                         let retry_amt_msat = route.get_total_amount();
1015                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1016                                                                 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);
1017                                                                 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1018                                                                 return
1019                                                         }
1020
1021                                                         if !payment.get().is_retryable_now() {
1022                                                                 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1023                                                                 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1024                                                                 return
1025                                                         }
1026
1027                                                         let total_msat = *total_msat;
1028                                                         let recipient_onion = RecipientOnionFields {
1029                                                                 payment_secret: *payment_secret,
1030                                                                 payment_metadata: payment_metadata.clone(),
1031                                                                 custom_tlvs: custom_tlvs.clone(),
1032                                                         };
1033                                                         let keysend_preimage = *keysend_preimage;
1034
1035                                                         let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1036                                                         for _ in 0..route.paths.len() {
1037                                                                 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1038                                                         }
1039
1040                                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1041                                                                 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1042                                                         }
1043
1044                                                         payment.get_mut().increment_attempts();
1045
1046                                                         (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1047                                                 },
1048                                                 PendingOutboundPayment::Legacy { .. } => {
1049                                                         log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1050                                                         return
1051                                                 },
1052                                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
1053                                                         log_error!(logger, "Payment not yet sent");
1054                                                         return
1055                                                 },
1056                                                 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1057                                                         let total_amount = route_params.final_value_msat;
1058                                                         let recipient_onion = RecipientOnionFields {
1059                                                                 payment_secret: None,
1060                                                                 payment_metadata: None,
1061                                                                 custom_tlvs: vec![],
1062                                                         };
1063                                                         let retry_strategy = Some(*retry_strategy);
1064                                                         let payment_params = Some(route_params.payment_params.clone());
1065                                                         let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1066                                                                 *payment_hash, recipient_onion.clone(), None, &route,
1067                                                                 retry_strategy, payment_params, entropy_source, best_block_height
1068                                                         );
1069                                                         *payment.into_mut() = retryable_payment;
1070                                                         (total_amount, recipient_onion, None, onion_session_privs)
1071                                                 },
1072                                                 PendingOutboundPayment::Fulfilled { .. } => {
1073                                                         log_error!(logger, "Payment already completed");
1074                                                         return
1075                                                 },
1076                                                 PendingOutboundPayment::Abandoned { .. } => {
1077                                                         log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1078                                                         return
1079                                                 },
1080                                         }
1081                                 },
1082                                 hash_map::Entry::Vacant(_) => {
1083                                         log_error!(logger, "Payment with ID {} not found", &payment_id);
1084                                         return
1085                                 }
1086                         }
1087                 };
1088                 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1089                         payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1090                         &send_payment_along_path);
1091                 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1092                 if let Err(e) = res {
1093                         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);
1094                 }
1095         }
1096
1097         fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1098                 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1099                 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1100                 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1101                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1102         )
1103         where
1104                 R::Target: Router,
1105                 ES::Target: EntropySource,
1106                 NS::Target: NodeSigner,
1107                 L::Target: Logger,
1108                 IH: Fn() -> InFlightHtlcs,
1109                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1110         {
1111                 match err {
1112                         PaymentSendFailure::AllFailedResendSafe(errs) => {
1113                                 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);
1114                                 self.find_route_and_send_payment(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);
1115                         },
1116                         PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1117                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1118                                 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1119                                 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1120                                 // return `Ok()` here, ignoring any retry errors.
1121                                 self.find_route_and_send_payment(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
1122                         },
1123                         PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1124                                 // This may happen if we send a payment and some paths fail, but only due to a temporary
1125                                 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1126                                 // initial HTLC-Add messages yet.
1127                         },
1128                         PaymentSendFailure::PathParameterError(results) => {
1129                                 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1130                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1131                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1132                         },
1133                         PaymentSendFailure::ParameterError(e) => {
1134                                 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1135                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1136                         },
1137                         PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1138                 }
1139         }
1140
1141         fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1142                 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1143                 paths: Vec<Path>, path_results: I, logger: &L,
1144                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1145         ) where L::Target: Logger {
1146                 let mut events = pending_events.lock().unwrap();
1147                 debug_assert_eq!(paths.len(), path_results.len());
1148                 for (path, path_res) in paths.into_iter().zip(path_results) {
1149                         if let Err(e) = path_res {
1150                                 if let APIError::MonitorUpdateInProgress = e { continue }
1151                                 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1152                                 let mut failed_scid = None;
1153                                 if let APIError::ChannelUnavailable { .. } = e {
1154                                         let scid = path.hops[0].short_channel_id;
1155                                         failed_scid = Some(scid);
1156                                         route_params.payment_params.previously_failed_channels.push(scid);
1157                                 }
1158                                 events.push_back((events::Event::PaymentPathFailed {
1159                                         payment_id: Some(payment_id),
1160                                         payment_hash,
1161                                         payment_failed_permanently: false,
1162                                         failure: events::PathFailure::InitialSend { err: e },
1163                                         path,
1164                                         short_channel_id: failed_scid,
1165                                         #[cfg(test)]
1166                                         error_code: None,
1167                                         #[cfg(test)]
1168                                         error_data: None,
1169                                 }, None));
1170                         }
1171                 }
1172         }
1173
1174         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1175                 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1176                 best_block_height: u32, send_payment_along_path: F
1177         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1178         where
1179                 ES::Target: EntropySource,
1180                 NS::Target: NodeSigner,
1181                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1182         {
1183                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1184                 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1185
1186                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1187
1188                 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1189                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1190                                 err: "No need probing a path with less than two hops".to_string()
1191                         }))
1192                 }
1193
1194                 let route = Route { paths: vec![path], route_params: None };
1195                 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1196                         RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1197                         entropy_source, best_block_height)?;
1198
1199                 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1200                         None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1201                 ) {
1202                         Ok(()) => Ok((payment_hash, payment_id)),
1203                         Err(e) => {
1204                                 self.remove_outbound_if_all_failed(payment_id, &e);
1205                                 Err(e)
1206                         }
1207                 }
1208         }
1209
1210         #[cfg(test)]
1211         pub(super) fn test_set_payment_metadata(
1212                 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1213         ) {
1214                 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1215                         PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1216                                 *payment_metadata = new_payment_metadata;
1217                         },
1218                         _ => panic!("Need a retryable payment to update metadata on"),
1219                 }
1220         }
1221
1222         #[cfg(test)]
1223         pub(super) fn test_add_new_pending_payment<ES: Deref>(
1224                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1225                 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1226         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1227                 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1228         }
1229
1230         pub(super) fn add_new_pending_payment<ES: Deref>(
1231                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1232                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1233                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1234         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1235                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1236                 match pending_outbounds.entry(payment_id) {
1237                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1238                         hash_map::Entry::Vacant(entry) => {
1239                                 let (payment, onion_session_privs) = self.create_pending_payment(
1240                                         payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1241                                         payment_params, entropy_source, best_block_height
1242                                 );
1243                                 entry.insert(payment);
1244                                 Ok(onion_session_privs)
1245                         },
1246                 }
1247         }
1248
1249         fn create_pending_payment<ES: Deref>(
1250                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1251                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1252                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1253         ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1254         where
1255                 ES::Target: EntropySource,
1256         {
1257                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1258                 for _ in 0..route.paths.len() {
1259                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
1260                 }
1261
1262                 let mut payment = PendingOutboundPayment::Retryable {
1263                         retry_strategy,
1264                         attempts: PaymentAttempts::new(),
1265                         payment_params,
1266                         session_privs: HashSet::new(),
1267                         pending_amt_msat: 0,
1268                         pending_fee_msat: Some(0),
1269                         payment_hash,
1270                         payment_secret: recipient_onion.payment_secret,
1271                         payment_metadata: recipient_onion.payment_metadata,
1272                         keysend_preimage,
1273                         custom_tlvs: recipient_onion.custom_tlvs,
1274                         starting_block_height: best_block_height,
1275                         total_msat: route.get_total_amount(),
1276                         remaining_max_total_routing_fee_msat:
1277                                 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1278                 };
1279
1280                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1281                         assert!(payment.insert(*session_priv_bytes, path));
1282                 }
1283
1284                 (payment, onion_session_privs)
1285         }
1286
1287         pub(super) fn add_new_awaiting_invoice(
1288                 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1289                 max_total_routing_fee_msat: Option<u64>
1290         ) -> Result<(), ()> {
1291                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1292                 match pending_outbounds.entry(payment_id) {
1293                         hash_map::Entry::Occupied(_) => Err(()),
1294                         hash_map::Entry::Vacant(entry) => {
1295                                 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1296                                         expiration,
1297                                         retry_strategy,
1298                                         max_total_routing_fee_msat,
1299                                 });
1300
1301                                 Ok(())
1302                         },
1303                 }
1304         }
1305
1306         fn pay_route_internal<NS: Deref, F>(
1307                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1308                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1309                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1310                 send_payment_along_path: &F
1311         ) -> Result<(), PaymentSendFailure>
1312         where
1313                 NS::Target: NodeSigner,
1314                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1315         {
1316                 if route.paths.len() < 1 {
1317                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1318                 }
1319                 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1320                         && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1321                 {
1322                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1323                 }
1324                 let mut total_value = 0;
1325                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1326                 let mut path_errs = Vec::with_capacity(route.paths.len());
1327                 'path_check: for path in route.paths.iter() {
1328                         if path.hops.len() < 1 || path.hops.len() > 20 {
1329                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1330                                 continue 'path_check;
1331                         }
1332                         let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1333                                 usize::max_value() } else { path.hops.len() - 1 };
1334                         for (idx, hop) in path.hops.iter().enumerate() {
1335                                 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1336                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1337                                         continue 'path_check;
1338                                 }
1339                         }
1340                         for (i, hop) in path.hops.iter().enumerate() {
1341                                 // Check for duplicate channel_id in the remaining hops of the path
1342                                 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1343                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1344                                         continue 'path_check;
1345                                 }
1346                         }
1347                         total_value += path.final_value_msat();
1348                         path_errs.push(Ok(()));
1349                 }
1350                 if path_errs.iter().any(|e| e.is_err()) {
1351                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1352                 }
1353                 if let Some(amt_msat) = recv_value_msat {
1354                         total_value = amt_msat;
1355                 }
1356
1357                 let cur_height = best_block_height + 1;
1358                 let mut results = Vec::new();
1359                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1360                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1361                         let mut path_res = send_payment_along_path(SendAlongPathArgs {
1362                                 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1363                                 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1364                         });
1365                         match path_res {
1366                                 Ok(_) => {},
1367                                 Err(APIError::MonitorUpdateInProgress) => {
1368                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
1369                                         // considered "in flight" and we shouldn't remove it from the
1370                                         // PendingOutboundPayment set.
1371                                 },
1372                                 Err(_) => {
1373                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1374                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1375                                                 let removed = payment.remove(&session_priv_bytes, Some(path));
1376                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1377                                         } else {
1378                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
1379                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1380                                         }
1381                                 }
1382                         }
1383                         results.push(path_res);
1384                 }
1385                 let mut has_ok = false;
1386                 let mut has_err = false;
1387                 let mut has_unsent = false;
1388                 let mut total_ok_fees_msat = 0;
1389                 let mut total_ok_amt_sent_msat = 0;
1390                 for (res, path) in results.iter().zip(route.paths.iter()) {
1391                         if res.is_ok() {
1392                                 has_ok = true;
1393                                 total_ok_fees_msat += path.fee_msat();
1394                                 total_ok_amt_sent_msat += path.final_value_msat();
1395                         }
1396                         if res.is_err() { has_err = true; }
1397                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1398                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1399                                 // PartialFailure.
1400                                 has_err = true;
1401                                 has_ok = true;
1402                                 total_ok_fees_msat += path.fee_msat();
1403                                 total_ok_amt_sent_msat += path.final_value_msat();
1404                         } else if res.is_err() {
1405                                 has_unsent = true;
1406                         }
1407                 }
1408                 if has_err && has_ok {
1409                         Err(PaymentSendFailure::PartialFailure {
1410                                 results,
1411                                 payment_id,
1412                                 failed_paths_retry: if has_unsent {
1413                                         if let Some(route_params) = &route.route_params {
1414                                                 let mut route_params = route_params.clone();
1415                                                 // We calculate the leftover fee budget we're allowed to spend by
1416                                                 // subtracting the used fee from the total fee budget.
1417                                                 route_params.max_total_routing_fee_msat = route_params
1418                                                         .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1419
1420                                                 // We calculate the remaining target amount by subtracting the succeded
1421                                                 // path values.
1422                                                 route_params.final_value_msat = route_params.final_value_msat
1423                                                         .saturating_sub(total_ok_amt_sent_msat);
1424                                                 Some(route_params)
1425                                         } else { None }
1426                                 } else { None },
1427                         })
1428                 } else if has_err {
1429                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1430                 } else {
1431                         Ok(())
1432                 }
1433         }
1434
1435         #[cfg(test)]
1436         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1437                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1438                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1439                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1440                 send_payment_along_path: F
1441         ) -> Result<(), PaymentSendFailure>
1442         where
1443                 NS::Target: NodeSigner,
1444                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1445         {
1446                 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1447                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1448                         &send_payment_along_path)
1449                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1450         }
1451
1452         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1453         // map as the payment is free to be resent.
1454         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1455                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1456                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1457                         debug_assert!(removed, "We should always have a pending payment to remove here");
1458                 }
1459         }
1460
1461         pub(super) fn claim_htlc<L: Deref>(
1462                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1463                 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1464                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1465                 logger: &L,
1466         ) where L::Target: Logger {
1467                 let mut session_priv_bytes = [0; 32];
1468                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1469                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1470                 let mut pending_events = pending_events.lock().unwrap();
1471                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1472                         if !payment.get().is_fulfilled() {
1473                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1474                                 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1475                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1476                                 pending_events.push_back((events::Event::PaymentSent {
1477                                         payment_id: Some(payment_id),
1478                                         payment_preimage,
1479                                         payment_hash,
1480                                         fee_paid_msat,
1481                                 }, Some(ev_completion_action.clone())));
1482                                 payment.get_mut().mark_fulfilled();
1483                         }
1484
1485                         if from_onchain {
1486                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1487                                 // This could potentially lead to removing a pending payment too early,
1488                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1489                                 // restart.
1490                                 // TODO: We should have a second monitor event that informs us of payments
1491                                 // irrevocably fulfilled.
1492                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1493                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1494                                         pending_events.push_back((events::Event::PaymentPathSuccessful {
1495                                                 payment_id,
1496                                                 payment_hash,
1497                                                 path,
1498                                         }, Some(ev_completion_action)));
1499                                 }
1500                         }
1501                 } else {
1502                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1503                 }
1504         }
1505
1506         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1507                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1508         {
1509                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1510                 let mut pending_events = pending_events.lock().unwrap();
1511                 for source in sources {
1512                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1513                                 let mut session_priv_bytes = [0; 32];
1514                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1515                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1516                                         assert!(payment.get().is_fulfilled());
1517                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1518                                                 let payment_hash = payment.get().payment_hash();
1519                                                 debug_assert!(payment_hash.is_some());
1520                                                 pending_events.push_back((events::Event::PaymentPathSuccessful {
1521                                                         payment_id,
1522                                                         payment_hash,
1523                                                         path,
1524                                                 }, None));
1525                                         }
1526                                 }
1527                         }
1528                 }
1529         }
1530
1531         pub(super) fn remove_stale_payments(
1532                 &self, duration_since_epoch: Duration,
1533                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1534         {
1535                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1536                 let mut pending_events = pending_events.lock().unwrap();
1537                 pending_outbound_payments.retain(|payment_id, payment| match payment {
1538                         // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1539                         // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1540                         // this could race the user making a duplicate send_payment call and our idempotency
1541                         // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1542                         // removal. This should be more than sufficient to ensure the idempotency of any
1543                         // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1544                         // processed.
1545                         PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1546                                 let mut no_remaining_entries = session_privs.is_empty();
1547                                 if no_remaining_entries {
1548                                         for (ev, _) in pending_events.iter() {
1549                                                 match ev {
1550                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1551                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1552                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1553                                                                         if payment_id == ev_payment_id {
1554                                                                                 no_remaining_entries = false;
1555                                                                                 break;
1556                                                                         }
1557                                                                 },
1558                                                         _ => {},
1559                                                 }
1560                                         }
1561                                 }
1562                                 if no_remaining_entries {
1563                                         *timer_ticks_without_htlcs += 1;
1564                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1565                                 } else {
1566                                         *timer_ticks_without_htlcs = 0;
1567                                         true
1568                                 }
1569                         },
1570                         PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1571                                 let is_stale = match expiration {
1572                                         StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1573                                                 *absolute_expiry <= duration_since_epoch
1574                                         },
1575                                         StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1576                                                 if *timer_ticks_remaining > 0 {
1577                                                         *timer_ticks_remaining -= 1;
1578                                                         false
1579                                                 } else {
1580                                                         true
1581                                                 }
1582                                         },
1583                                 };
1584                                 if is_stale {
1585                                         pending_events.push_back(
1586                                                 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1587                                         );
1588                                         false
1589                                 } else {
1590                                         true
1591                                 }
1592                         },
1593                         _ => true,
1594                 });
1595         }
1596
1597         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1598         pub(super) fn fail_htlc<L: Deref>(
1599                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1600                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1601                 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1602                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1603         ) -> bool where L::Target: Logger {
1604                 #[cfg(test)]
1605                 let DecodedOnionFailure {
1606                         network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1607                         onion_error_data, failed_within_blinded_path
1608                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1609                 #[cfg(not(test))]
1610                 let DecodedOnionFailure {
1611                         network_update, short_channel_id, payment_failed_permanently, failed_within_blinded_path
1612                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1613
1614                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1615                 let mut session_priv_bytes = [0; 32];
1616                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1617                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1618
1619                 // If any payments already need retry, there's no need to generate a redundant
1620                 // `PendingHTLCsForwardable`.
1621                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1622                         let mut awaiting_retry = false;
1623                         if pmt.is_auto_retryable_now() {
1624                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1625                                         if pending_amt_msat < total_msat {
1626                                                 awaiting_retry = true;
1627                                         }
1628                                 }
1629                         }
1630                         awaiting_retry
1631                 });
1632
1633                 let mut full_failure_ev = None;
1634                 let mut pending_retry_ev = false;
1635                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1636                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1637                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1638                                 return false
1639                         }
1640                         if payment.get().is_fulfilled() {
1641                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1642                                 return false
1643                         }
1644                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1645                         if let Some(scid) = short_channel_id {
1646                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1647                                 // process_onion_failure we should close that channel as it implies our
1648                                 // next-hop is needlessly blaming us!
1649                                 payment.get_mut().insert_previously_failed_scid(scid);
1650                         }
1651
1652                         if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1653                                 let reason = if payment_failed_permanently {
1654                                         PaymentFailureReason::RecipientRejected
1655                                 } else {
1656                                         PaymentFailureReason::RetriesExhausted
1657                                 };
1658                                 payment.get_mut().mark_abandoned(reason);
1659                                 is_retryable_now = false;
1660                         }
1661                         if payment.get().remaining_parts() == 0 {
1662                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1663                                         if !payment_is_probe {
1664                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1665                                                         payment_id: *payment_id,
1666                                                         payment_hash: *payment_hash,
1667                                                         reason: *reason,
1668                                                 });
1669                                         }
1670                                         payment.remove();
1671                                 }
1672                         }
1673                         is_retryable_now
1674                 } else {
1675                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1676                         return false
1677                 };
1678                 core::mem::drop(outbounds);
1679                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1680
1681                 let path_failure = {
1682                         if payment_is_probe {
1683                                 if payment_failed_permanently {
1684                                         events::Event::ProbeSuccessful {
1685                                                 payment_id: *payment_id,
1686                                                 payment_hash: payment_hash.clone(),
1687                                                 path: path.clone(),
1688                                         }
1689                                 } else {
1690                                         events::Event::ProbeFailed {
1691                                                 payment_id: *payment_id,
1692                                                 payment_hash: payment_hash.clone(),
1693                                                 path: path.clone(),
1694                                                 short_channel_id,
1695                                         }
1696                                 }
1697                         } else {
1698                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1699                                 // payment will sit in our outbounds forever.
1700                                 if attempts_remaining && !already_awaiting_retry {
1701                                         debug_assert!(full_failure_ev.is_none());
1702                                         pending_retry_ev = true;
1703                                 }
1704                                 events::Event::PaymentPathFailed {
1705                                         payment_id: Some(*payment_id),
1706                                         payment_hash: payment_hash.clone(),
1707                                         payment_failed_permanently,
1708                                         failure: events::PathFailure::OnPath { network_update },
1709                                         path: path.clone(),
1710                                         short_channel_id,
1711                                         #[cfg(test)]
1712                                         error_code: onion_error_code,
1713                                         #[cfg(test)]
1714                                         error_data: onion_error_data
1715                                 }
1716                         }
1717                 };
1718                 let mut pending_events = pending_events.lock().unwrap();
1719                 pending_events.push_back((path_failure, None));
1720                 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1721                 pending_retry_ev
1722         }
1723
1724         pub(super) fn abandon_payment(
1725                 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1726                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1727         ) {
1728                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1729                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1730                         payment.get_mut().mark_abandoned(reason);
1731                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1732                                 if payment.get().remaining_parts() == 0 {
1733                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1734                                                 payment_id,
1735                                                 payment_hash: *payment_hash,
1736                                                 reason: *reason,
1737                                         }, None));
1738                                         payment.remove();
1739                                 }
1740                         } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1741                                 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1742                                         payment_id,
1743                                 }, None));
1744                                 payment.remove();
1745                         }
1746                 }
1747         }
1748
1749         #[cfg(test)]
1750         pub fn has_pending_payments(&self) -> bool {
1751                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1752         }
1753
1754         #[cfg(test)]
1755         pub fn clear_pending_payments(&self) {
1756                 self.pending_outbound_payments.lock().unwrap().clear()
1757         }
1758 }
1759
1760 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1761 /// payment probe.
1762 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1763         probing_cookie_secret: [u8; 32]) -> bool
1764 {
1765         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1766         target_payment_hash == *payment_hash
1767 }
1768
1769 /// Returns the 'probing cookie' for the given [`PaymentId`].
1770 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1771         let mut preimage = [0u8; 64];
1772         preimage[..32].copy_from_slice(&probing_cookie_secret);
1773         preimage[32..].copy_from_slice(&payment_id.0);
1774         PaymentHash(Sha256::hash(&preimage).to_byte_array())
1775 }
1776
1777 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1778         (0, Legacy) => {
1779                 (0, session_privs, required),
1780         },
1781         (1, Fulfilled) => {
1782                 (0, session_privs, required),
1783                 (1, payment_hash, option),
1784                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1785         },
1786         (2, Retryable) => {
1787                 (0, session_privs, required),
1788                 (1, pending_fee_msat, option),
1789                 (2, payment_hash, required),
1790                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1791                 // never see it - `payment_params` was added here after the field was added/required.
1792                 (3, payment_params, (option: ReadableArgs, 0)),
1793                 (4, payment_secret, option),
1794                 (5, keysend_preimage, option),
1795                 (6, total_msat, required),
1796                 (7, payment_metadata, option),
1797                 (8, pending_amt_msat, required),
1798                 (9, custom_tlvs, optional_vec),
1799                 (10, starting_block_height, required),
1800                 (11, remaining_max_total_routing_fee_msat, option),
1801                 (not_written, retry_strategy, (static_value, None)),
1802                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1803         },
1804         (3, Abandoned) => {
1805                 (0, session_privs, required),
1806                 (1, reason, option),
1807                 (2, payment_hash, required),
1808         },
1809         (5, AwaitingInvoice) => {
1810                 (0, expiration, required),
1811                 (2, retry_strategy, required),
1812                 (4, max_total_routing_fee_msat, option),
1813         },
1814         (7, InvoiceReceived) => {
1815                 (0, payment_hash, required),
1816                 (2, retry_strategy, required),
1817                 (4, max_total_routing_fee_msat, option),
1818         },
1819 );
1820
1821 #[cfg(test)]
1822 mod tests {
1823         use bitcoin::network::constants::Network;
1824         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1825
1826         use core::time::Duration;
1827
1828         use crate::events::{Event, PathFailure, PaymentFailureReason};
1829         use crate::ln::PaymentHash;
1830         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1831         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1832         use crate::ln::msgs::{ErrorAction, LightningError};
1833         use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1834         #[cfg(feature = "std")]
1835         use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1836         use crate::offers::offer::OfferBuilder;
1837         use crate::offers::test_utils::*;
1838         use crate::routing::gossip::NetworkGraph;
1839         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1840         use crate::sync::{Arc, Mutex, RwLock};
1841         use crate::util::errors::APIError;
1842         use crate::util::test_utils;
1843
1844         use alloc::collections::VecDeque;
1845
1846         #[test]
1847         fn test_recipient_onion_fields_with_custom_tlvs() {
1848                 let onion_fields = RecipientOnionFields::spontaneous_empty();
1849
1850                 let bad_type_range_tlvs = vec![
1851                         (0, vec![42]),
1852                         (1, vec![42; 32]),
1853                 ];
1854                 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1855
1856                 let keysend_tlv = vec![
1857                         (5482373484, vec![42; 32]),
1858                 ];
1859                 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1860
1861                 let good_tlvs = vec![
1862                         ((1 << 16) + 1, vec![42]),
1863                         ((1 << 16) + 3, vec![42; 32]),
1864                 ];
1865                 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1866         }
1867
1868         #[test]
1869         #[cfg(feature = "std")]
1870         fn fails_paying_after_expiration() {
1871                 do_fails_paying_after_expiration(false);
1872                 do_fails_paying_after_expiration(true);
1873         }
1874         #[cfg(feature = "std")]
1875         fn do_fails_paying_after_expiration(on_retry: bool) {
1876                 let outbound_payments = OutboundPayments::new();
1877                 let logger = test_utils::TestLogger::new();
1878                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1879                 let scorer = RwLock::new(test_utils::TestScorer::new());
1880                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1881                 let secp_ctx = Secp256k1::new();
1882                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1883
1884                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1885                 let payment_params = PaymentParameters::from_node_id(
1886                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1887                                 0
1888                         ).with_expiry_time(past_expiry_time);
1889                 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1890                 let pending_events = Mutex::new(VecDeque::new());
1891                 if on_retry {
1892                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1893                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1894                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1895                                 &&keys_manager, 0).unwrap();
1896                         outbound_payments.find_route_and_send_payment(
1897                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1898                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1899                                 &|_| Ok(()));
1900                         let events = pending_events.lock().unwrap();
1901                         assert_eq!(events.len(), 1);
1902                         if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1903                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1904                         } else { panic!("Unexpected event"); }
1905                 } else {
1906                         let err = outbound_payments.send_payment(
1907                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1908                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1909                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1910                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1911                 }
1912         }
1913
1914         #[test]
1915         fn find_route_error() {
1916                 do_find_route_error(false);
1917                 do_find_route_error(true);
1918         }
1919         fn do_find_route_error(on_retry: bool) {
1920                 let outbound_payments = OutboundPayments::new();
1921                 let logger = test_utils::TestLogger::new();
1922                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1923                 let scorer = RwLock::new(test_utils::TestScorer::new());
1924                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1925                 let secp_ctx = Secp256k1::new();
1926                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1927
1928                 let payment_params = PaymentParameters::from_node_id(
1929                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1930                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1931                 router.expect_find_route(route_params.clone(),
1932                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1933
1934                 let pending_events = Mutex::new(VecDeque::new());
1935                 if on_retry {
1936                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1937                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1938                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1939                                 &&keys_manager, 0).unwrap();
1940                         outbound_payments.find_route_and_send_payment(
1941                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1942                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1943                                 &|_| Ok(()));
1944                         let events = pending_events.lock().unwrap();
1945                         assert_eq!(events.len(), 1);
1946                         if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1947                 } else {
1948                         let err = outbound_payments.send_payment(
1949                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1950                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1951                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1952                         if let RetryableSendFailure::RouteNotFound = err {
1953                         } else { panic!("Unexpected error"); }
1954                 }
1955         }
1956
1957         #[test]
1958         fn initial_send_payment_path_failed_evs() {
1959                 let outbound_payments = OutboundPayments::new();
1960                 let logger = test_utils::TestLogger::new();
1961                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1962                 let scorer = RwLock::new(test_utils::TestScorer::new());
1963                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1964                 let secp_ctx = Secp256k1::new();
1965                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1966
1967                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1968                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1969                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1970                 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1971                 let failed_scid = 42;
1972                 let route = Route {
1973                         paths: vec![Path { hops: vec![RouteHop {
1974                                 pubkey: receiver_pk,
1975                                 node_features: NodeFeatures::empty(),
1976                                 short_channel_id: failed_scid,
1977                                 channel_features: ChannelFeatures::empty(),
1978                                 fee_msat: 0,
1979                                 cltv_expiry_delta: 0,
1980                                 maybe_announced_channel: true,
1981                         }], blinded_tail: None }],
1982                         route_params: Some(route_params.clone()),
1983                 };
1984                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1985                 let mut route_params_w_failed_scid = route_params.clone();
1986                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1987                 let mut route_w_failed_scid = route.clone();
1988                 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
1989                 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
1990                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1991                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1992
1993                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1994                 // PaymentPathFailed event.
1995                 let pending_events = Mutex::new(VecDeque::new());
1996                 outbound_payments.send_payment(
1997                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1998                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1999                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2000                         |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2001                 let mut events = pending_events.lock().unwrap();
2002                 assert_eq!(events.len(), 2);
2003                 if let Event::PaymentPathFailed {
2004                         short_channel_id,
2005                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2006                 {
2007                         assert_eq!(short_channel_id, Some(failed_scid));
2008                 } else { panic!("Unexpected event"); }
2009                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2010                 events.clear();
2011                 core::mem::drop(events);
2012
2013                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2014                 outbound_payments.send_payment(
2015                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2016                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2017                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2018                         |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2019                 assert_eq!(pending_events.lock().unwrap().len(), 0);
2020
2021                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2022                 outbound_payments.send_payment(
2023                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2024                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2025                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2026                         |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2027                 let events = pending_events.lock().unwrap();
2028                 assert_eq!(events.len(), 2);
2029                 if let Event::PaymentPathFailed {
2030                         short_channel_id,
2031                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2032                 {
2033                         assert_eq!(short_channel_id, None);
2034                 } else { panic!("Unexpected event"); }
2035                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2036         }
2037
2038         #[test]
2039         fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2040                 let pending_events = Mutex::new(VecDeque::new());
2041                 let outbound_payments = OutboundPayments::new();
2042                 let payment_id = PaymentId([0; 32]);
2043                 let absolute_expiry = 100;
2044                 let tick_interval = 10;
2045                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2046
2047                 assert!(!outbound_payments.has_pending_payments());
2048                 assert!(
2049                         outbound_payments.add_new_awaiting_invoice(
2050                                 payment_id, expiration, Retry::Attempts(0), None
2051                         ).is_ok()
2052                 );
2053                 assert!(outbound_payments.has_pending_payments());
2054
2055                 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2056                         let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2057                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2058
2059                         assert!(outbound_payments.has_pending_payments());
2060                         assert!(pending_events.lock().unwrap().is_empty());
2061                 }
2062
2063                 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2064                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2065
2066                 assert!(!outbound_payments.has_pending_payments());
2067                 assert!(!pending_events.lock().unwrap().is_empty());
2068                 assert_eq!(
2069                         pending_events.lock().unwrap().pop_front(),
2070                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2071                 );
2072                 assert!(pending_events.lock().unwrap().is_empty());
2073
2074                 assert!(
2075                         outbound_payments.add_new_awaiting_invoice(
2076                                 payment_id, expiration, Retry::Attempts(0), None
2077                         ).is_ok()
2078                 );
2079                 assert!(outbound_payments.has_pending_payments());
2080
2081                 assert!(
2082                         outbound_payments.add_new_awaiting_invoice(
2083                                 payment_id, expiration, Retry::Attempts(0), None
2084                         ).is_err()
2085                 );
2086         }
2087
2088         #[test]
2089         fn removes_stale_awaiting_invoice_using_timer_ticks() {
2090                 let pending_events = Mutex::new(VecDeque::new());
2091                 let outbound_payments = OutboundPayments::new();
2092                 let payment_id = PaymentId([0; 32]);
2093                 let timer_ticks = 3;
2094                 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2095
2096                 assert!(!outbound_payments.has_pending_payments());
2097                 assert!(
2098                         outbound_payments.add_new_awaiting_invoice(
2099                                 payment_id, expiration, Retry::Attempts(0), None
2100                         ).is_ok()
2101                 );
2102                 assert!(outbound_payments.has_pending_payments());
2103
2104                 for i in 0..timer_ticks {
2105                         let duration_since_epoch = Duration::from_secs(i * 60);
2106                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2107
2108                         assert!(outbound_payments.has_pending_payments());
2109                         assert!(pending_events.lock().unwrap().is_empty());
2110                 }
2111
2112                 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2113                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2114
2115                 assert!(!outbound_payments.has_pending_payments());
2116                 assert!(!pending_events.lock().unwrap().is_empty());
2117                 assert_eq!(
2118                         pending_events.lock().unwrap().pop_front(),
2119                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2120                 );
2121                 assert!(pending_events.lock().unwrap().is_empty());
2122
2123                 assert!(
2124                         outbound_payments.add_new_awaiting_invoice(
2125                                 payment_id, expiration, Retry::Attempts(0), None
2126                         ).is_ok()
2127                 );
2128                 assert!(outbound_payments.has_pending_payments());
2129
2130                 assert!(
2131                         outbound_payments.add_new_awaiting_invoice(
2132                                 payment_id, expiration, Retry::Attempts(0), None
2133                         ).is_err()
2134                 );
2135         }
2136
2137         #[test]
2138         fn removes_abandoned_awaiting_invoice() {
2139                 let pending_events = Mutex::new(VecDeque::new());
2140                 let outbound_payments = OutboundPayments::new();
2141                 let payment_id = PaymentId([0; 32]);
2142                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2143
2144                 assert!(!outbound_payments.has_pending_payments());
2145                 assert!(
2146                         outbound_payments.add_new_awaiting_invoice(
2147                                 payment_id, expiration, Retry::Attempts(0), None
2148                         ).is_ok()
2149                 );
2150                 assert!(outbound_payments.has_pending_payments());
2151
2152                 outbound_payments.abandon_payment(
2153                         payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2154                 );
2155                 assert!(!outbound_payments.has_pending_payments());
2156                 assert!(!pending_events.lock().unwrap().is_empty());
2157                 assert_eq!(
2158                         pending_events.lock().unwrap().pop_front(),
2159                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2160                 );
2161                 assert!(pending_events.lock().unwrap().is_empty());
2162         }
2163
2164         #[cfg(feature = "std")]
2165         #[test]
2166         fn fails_sending_payment_for_expired_bolt12_invoice() {
2167                 let logger = test_utils::TestLogger::new();
2168                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2169                 let scorer = RwLock::new(test_utils::TestScorer::new());
2170                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2171                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2172
2173                 let pending_events = Mutex::new(VecDeque::new());
2174                 let outbound_payments = OutboundPayments::new();
2175                 let payment_id = PaymentId([0; 32]);
2176                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2177
2178                 assert!(
2179                         outbound_payments.add_new_awaiting_invoice(
2180                                 payment_id, expiration, Retry::Attempts(0), None
2181                         ).is_ok()
2182                 );
2183                 assert!(outbound_payments.has_pending_payments());
2184
2185                 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2186                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2187                         .amount_msats(1000)
2188                         .build().unwrap()
2189                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2190                         .build().unwrap()
2191                         .sign(payer_sign).unwrap()
2192                         .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2193                         .build().unwrap()
2194                         .sign(recipient_sign).unwrap();
2195
2196                 assert_eq!(
2197                         outbound_payments.send_payment_for_bolt12_invoice(
2198                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2199                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2200                         ),
2201                         Ok(()),
2202                 );
2203                 assert!(!outbound_payments.has_pending_payments());
2204
2205                 let payment_hash = invoice.payment_hash();
2206                 let reason = Some(PaymentFailureReason::PaymentExpired);
2207
2208                 assert!(!pending_events.lock().unwrap().is_empty());
2209                 assert_eq!(
2210                         pending_events.lock().unwrap().pop_front(),
2211                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2212                 );
2213                 assert!(pending_events.lock().unwrap().is_empty());
2214         }
2215
2216         #[test]
2217         fn fails_finding_route_for_bolt12_invoice() {
2218                 let logger = test_utils::TestLogger::new();
2219                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2220                 let scorer = RwLock::new(test_utils::TestScorer::new());
2221                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2222                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2223
2224                 let pending_events = Mutex::new(VecDeque::new());
2225                 let outbound_payments = OutboundPayments::new();
2226                 let payment_id = PaymentId([0; 32]);
2227                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2228
2229                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2230                         .amount_msats(1000)
2231                         .build().unwrap()
2232                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2233                         .build().unwrap()
2234                         .sign(payer_sign).unwrap()
2235                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2236                         .build().unwrap()
2237                         .sign(recipient_sign).unwrap();
2238
2239                 assert!(
2240                         outbound_payments.add_new_awaiting_invoice(
2241                                 payment_id, expiration, Retry::Attempts(0),
2242                                 Some(invoice.amount_msats() / 100 + 50_000)
2243                         ).is_ok()
2244                 );
2245                 assert!(outbound_payments.has_pending_payments());
2246
2247                 router.expect_find_route(
2248                         RouteParameters::from_payment_params_and_value(
2249                                 PaymentParameters::from_bolt12_invoice(&invoice),
2250                                 invoice.amount_msats(),
2251                         ),
2252                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2253                 );
2254
2255                 assert_eq!(
2256                         outbound_payments.send_payment_for_bolt12_invoice(
2257                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2258                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2259                         ),
2260                         Ok(()),
2261                 );
2262                 assert!(!outbound_payments.has_pending_payments());
2263
2264                 let payment_hash = invoice.payment_hash();
2265                 let reason = Some(PaymentFailureReason::RouteNotFound);
2266
2267                 assert!(!pending_events.lock().unwrap().is_empty());
2268                 assert_eq!(
2269                         pending_events.lock().unwrap().pop_front(),
2270                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2271                 );
2272                 assert!(pending_events.lock().unwrap().is_empty());
2273         }
2274
2275         #[test]
2276         fn fails_paying_for_bolt12_invoice() {
2277                 let logger = test_utils::TestLogger::new();
2278                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2279                 let scorer = RwLock::new(test_utils::TestScorer::new());
2280                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2281                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2282
2283                 let pending_events = Mutex::new(VecDeque::new());
2284                 let outbound_payments = OutboundPayments::new();
2285                 let payment_id = PaymentId([0; 32]);
2286                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2287
2288                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2289                         .amount_msats(1000)
2290                         .build().unwrap()
2291                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2292                         .build().unwrap()
2293                         .sign(payer_sign).unwrap()
2294                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2295                         .build().unwrap()
2296                         .sign(recipient_sign).unwrap();
2297
2298                 assert!(
2299                         outbound_payments.add_new_awaiting_invoice(
2300                                 payment_id, expiration, Retry::Attempts(0),
2301                                 Some(invoice.amount_msats() / 100 + 50_000)
2302                         ).is_ok()
2303                 );
2304                 assert!(outbound_payments.has_pending_payments());
2305
2306                 let route_params = RouteParameters::from_payment_params_and_value(
2307                         PaymentParameters::from_bolt12_invoice(&invoice),
2308                         invoice.amount_msats(),
2309                 );
2310                 router.expect_find_route(
2311                         route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2312                 );
2313
2314                 assert_eq!(
2315                         outbound_payments.send_payment_for_bolt12_invoice(
2316                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2317                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2318                         ),
2319                         Ok(()),
2320                 );
2321                 assert!(!outbound_payments.has_pending_payments());
2322
2323                 let payment_hash = invoice.payment_hash();
2324                 let reason = Some(PaymentFailureReason::UnexpectedError);
2325
2326                 assert!(!pending_events.lock().unwrap().is_empty());
2327                 assert_eq!(
2328                         pending_events.lock().unwrap().pop_front(),
2329                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2330                 );
2331                 assert!(pending_events.lock().unwrap().is_empty());
2332         }
2333
2334         #[test]
2335         fn sends_payment_for_bolt12_invoice() {
2336                 let logger = test_utils::TestLogger::new();
2337                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2338                 let scorer = RwLock::new(test_utils::TestScorer::new());
2339                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2340                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2341
2342                 let pending_events = Mutex::new(VecDeque::new());
2343                 let outbound_payments = OutboundPayments::new();
2344                 let payment_id = PaymentId([0; 32]);
2345                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2346
2347                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2348                         .amount_msats(1000)
2349                         .build().unwrap()
2350                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2351                         .build().unwrap()
2352                         .sign(payer_sign).unwrap()
2353                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2354                         .build().unwrap()
2355                         .sign(recipient_sign).unwrap();
2356
2357                 let route_params = RouteParameters {
2358                         payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2359                         final_value_msat: invoice.amount_msats(),
2360                         max_total_routing_fee_msat: Some(1234),
2361                 };
2362                 router.expect_find_route(
2363                         route_params.clone(),
2364                         Ok(Route {
2365                                 paths: vec![
2366                                         Path {
2367                                                 hops: vec![
2368                                                         RouteHop {
2369                                                                 pubkey: recipient_pubkey(),
2370                                                                 node_features: NodeFeatures::empty(),
2371                                                                 short_channel_id: 42,
2372                                                                 channel_features: ChannelFeatures::empty(),
2373                                                                 fee_msat: invoice.amount_msats(),
2374                                                                 cltv_expiry_delta: 0,
2375                                                                 maybe_announced_channel: true,
2376                                                         }
2377                                                 ],
2378                                                 blinded_tail: None,
2379                                         }
2380                                 ],
2381                                 route_params: Some(route_params),
2382                         })
2383                 );
2384
2385                 assert!(!outbound_payments.has_pending_payments());
2386                 assert_eq!(
2387                         outbound_payments.send_payment_for_bolt12_invoice(
2388                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2389                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2390                         ),
2391                         Err(Bolt12PaymentError::UnexpectedInvoice),
2392                 );
2393                 assert!(!outbound_payments.has_pending_payments());
2394                 assert!(pending_events.lock().unwrap().is_empty());
2395
2396                 assert!(
2397                         outbound_payments.add_new_awaiting_invoice(
2398                                 payment_id, expiration, Retry::Attempts(0), Some(1234)
2399                         ).is_ok()
2400                 );
2401                 assert!(outbound_payments.has_pending_payments());
2402
2403                 assert_eq!(
2404                         outbound_payments.send_payment_for_bolt12_invoice(
2405                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2406                                 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2407                         ),
2408                         Ok(()),
2409                 );
2410                 assert!(outbound_payments.has_pending_payments());
2411                 assert!(pending_events.lock().unwrap().is_empty());
2412
2413                 assert_eq!(
2414                         outbound_payments.send_payment_for_bolt12_invoice(
2415                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2416                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2417                         ),
2418                         Err(Bolt12PaymentError::DuplicateInvoice),
2419                 );
2420                 assert!(outbound_payments.has_pending_payments());
2421                 assert!(pending_events.lock().unwrap().is_empty());
2422         }
2423 }