7e58c8adf298c1e7ace9085de66ac04c5913139e
[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).into_inner());
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).into_inner());
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         #[allow(unused)]
766         pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
767                 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
768                 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
769                 best_block_height: u32, logger: &L,
770                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
771                 send_payment_along_path: SP,
772         ) -> Result<(), Bolt12PaymentError>
773         where
774                 R::Target: Router,
775                 ES::Target: EntropySource,
776                 NS::Target: NodeSigner,
777                 L::Target: Logger,
778                 IH: Fn() -> InFlightHtlcs,
779                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
780         {
781                 let payment_hash = invoice.payment_hash();
782                 let mut max_total_routing_fee_msat = None;
783                 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
784                         hash_map::Entry::Occupied(entry) => match entry.get() {
785                                 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
786                                         max_total_routing_fee_msat = *max_total_fee;
787                                         *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
788                                                 payment_hash,
789                                                 retry_strategy: *retry_strategy,
790                                                 max_total_routing_fee_msat,
791                                         };
792                                 },
793                                 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
794                         },
795                         hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
796                 };
797
798                 let route_params = RouteParameters {
799                         payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
800                         final_value_msat: invoice.amount_msats(),
801                         max_total_routing_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                         total_value += path.final_value_msat();
1341                         path_errs.push(Ok(()));
1342                 }
1343                 if path_errs.iter().any(|e| e.is_err()) {
1344                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1345                 }
1346                 if let Some(amt_msat) = recv_value_msat {
1347                         total_value = amt_msat;
1348                 }
1349
1350                 let cur_height = best_block_height + 1;
1351                 let mut results = Vec::new();
1352                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1353                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1354                         let mut path_res = send_payment_along_path(SendAlongPathArgs {
1355                                 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1356                                 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1357                         });
1358                         match path_res {
1359                                 Ok(_) => {},
1360                                 Err(APIError::MonitorUpdateInProgress) => {
1361                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
1362                                         // considered "in flight" and we shouldn't remove it from the
1363                                         // PendingOutboundPayment set.
1364                                 },
1365                                 Err(_) => {
1366                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1367                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1368                                                 let removed = payment.remove(&session_priv_bytes, Some(path));
1369                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1370                                         } else {
1371                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
1372                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1373                                         }
1374                                 }
1375                         }
1376                         results.push(path_res);
1377                 }
1378                 let mut has_ok = false;
1379                 let mut has_err = false;
1380                 let mut has_unsent = false;
1381                 let mut total_ok_fees_msat = 0;
1382                 let mut total_ok_amt_sent_msat = 0;
1383                 for (res, path) in results.iter().zip(route.paths.iter()) {
1384                         if res.is_ok() {
1385                                 has_ok = true;
1386                                 total_ok_fees_msat += path.fee_msat();
1387                                 total_ok_amt_sent_msat += path.final_value_msat();
1388                         }
1389                         if res.is_err() { has_err = true; }
1390                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1391                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1392                                 // PartialFailure.
1393                                 has_err = true;
1394                                 has_ok = true;
1395                                 total_ok_fees_msat += path.fee_msat();
1396                                 total_ok_amt_sent_msat += path.final_value_msat();
1397                         } else if res.is_err() {
1398                                 has_unsent = true;
1399                         }
1400                 }
1401                 if has_err && has_ok {
1402                         Err(PaymentSendFailure::PartialFailure {
1403                                 results,
1404                                 payment_id,
1405                                 failed_paths_retry: if has_unsent {
1406                                         if let Some(route_params) = &route.route_params {
1407                                                 let mut route_params = route_params.clone();
1408                                                 // We calculate the leftover fee budget we're allowed to spend by
1409                                                 // subtracting the used fee from the total fee budget.
1410                                                 route_params.max_total_routing_fee_msat = route_params
1411                                                         .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1412
1413                                                 // We calculate the remaining target amount by subtracting the succeded
1414                                                 // path values.
1415                                                 route_params.final_value_msat = route_params.final_value_msat
1416                                                         .saturating_sub(total_ok_amt_sent_msat);
1417                                                 Some(route_params)
1418                                         } else { None }
1419                                 } else { None },
1420                         })
1421                 } else if has_err {
1422                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1423                 } else {
1424                         Ok(())
1425                 }
1426         }
1427
1428         #[cfg(test)]
1429         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1430                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1431                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1432                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1433                 send_payment_along_path: F
1434         ) -> Result<(), PaymentSendFailure>
1435         where
1436                 NS::Target: NodeSigner,
1437                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1438         {
1439                 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1440                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1441                         &send_payment_along_path)
1442                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1443         }
1444
1445         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1446         // map as the payment is free to be resent.
1447         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1448                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1449                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1450                         debug_assert!(removed, "We should always have a pending payment to remove here");
1451                 }
1452         }
1453
1454         pub(super) fn claim_htlc<L: Deref>(
1455                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1456                 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1457                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1458                 logger: &L,
1459         ) where L::Target: Logger {
1460                 let mut session_priv_bytes = [0; 32];
1461                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1462                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1463                 let mut pending_events = pending_events.lock().unwrap();
1464                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1465                         if !payment.get().is_fulfilled() {
1466                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1467                                 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1468                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1469                                 pending_events.push_back((events::Event::PaymentSent {
1470                                         payment_id: Some(payment_id),
1471                                         payment_preimage,
1472                                         payment_hash,
1473                                         fee_paid_msat,
1474                                 }, Some(ev_completion_action.clone())));
1475                                 payment.get_mut().mark_fulfilled();
1476                         }
1477
1478                         if from_onchain {
1479                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1480                                 // This could potentially lead to removing a pending payment too early,
1481                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1482                                 // restart.
1483                                 // TODO: We should have a second monitor event that informs us of payments
1484                                 // irrevocably fulfilled.
1485                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1486                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1487                                         pending_events.push_back((events::Event::PaymentPathSuccessful {
1488                                                 payment_id,
1489                                                 payment_hash,
1490                                                 path,
1491                                         }, Some(ev_completion_action)));
1492                                 }
1493                         }
1494                 } else {
1495                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1496                 }
1497         }
1498
1499         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1500                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1501         {
1502                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1503                 let mut pending_events = pending_events.lock().unwrap();
1504                 for source in sources {
1505                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1506                                 let mut session_priv_bytes = [0; 32];
1507                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1508                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1509                                         assert!(payment.get().is_fulfilled());
1510                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1511                                                 let payment_hash = payment.get().payment_hash();
1512                                                 debug_assert!(payment_hash.is_some());
1513                                                 pending_events.push_back((events::Event::PaymentPathSuccessful {
1514                                                         payment_id,
1515                                                         payment_hash,
1516                                                         path,
1517                                                 }, None));
1518                                         }
1519                                 }
1520                         }
1521                 }
1522         }
1523
1524         pub(super) fn remove_stale_payments(
1525                 &self, duration_since_epoch: Duration,
1526                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1527         {
1528                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1529                 let mut pending_events = pending_events.lock().unwrap();
1530                 pending_outbound_payments.retain(|payment_id, payment| match payment {
1531                         // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1532                         // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1533                         // this could race the user making a duplicate send_payment call and our idempotency
1534                         // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1535                         // removal. This should be more than sufficient to ensure the idempotency of any
1536                         // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1537                         // processed.
1538                         PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1539                                 let mut no_remaining_entries = session_privs.is_empty();
1540                                 if no_remaining_entries {
1541                                         for (ev, _) in pending_events.iter() {
1542                                                 match ev {
1543                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1544                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1545                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1546                                                                         if payment_id == ev_payment_id {
1547                                                                                 no_remaining_entries = false;
1548                                                                                 break;
1549                                                                         }
1550                                                                 },
1551                                                         _ => {},
1552                                                 }
1553                                         }
1554                                 }
1555                                 if no_remaining_entries {
1556                                         *timer_ticks_without_htlcs += 1;
1557                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1558                                 } else {
1559                                         *timer_ticks_without_htlcs = 0;
1560                                         true
1561                                 }
1562                         },
1563                         PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1564                                 let is_stale = match expiration {
1565                                         StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1566                                                 *absolute_expiry <= duration_since_epoch
1567                                         },
1568                                         StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1569                                                 if *timer_ticks_remaining > 0 {
1570                                                         *timer_ticks_remaining -= 1;
1571                                                         false
1572                                                 } else {
1573                                                         true
1574                                                 }
1575                                         },
1576                                 };
1577                                 if is_stale {
1578                                         pending_events.push_back(
1579                                                 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1580                                         );
1581                                         false
1582                                 } else {
1583                                         true
1584                                 }
1585                         },
1586                         _ => true,
1587                 });
1588         }
1589
1590         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1591         pub(super) fn fail_htlc<L: Deref>(
1592                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1593                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1594                 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1595                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1596         ) -> bool where L::Target: Logger {
1597                 #[cfg(test)]
1598                 let DecodedOnionFailure {
1599                         network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1600                         onion_error_data
1601                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1602                 #[cfg(not(test))]
1603                 let DecodedOnionFailure { network_update, short_channel_id, payment_failed_permanently } =
1604                         onion_error.decode_onion_failure(secp_ctx, logger, &source);
1605
1606                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1607                 let mut session_priv_bytes = [0; 32];
1608                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1609                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1610
1611                 // If any payments already need retry, there's no need to generate a redundant
1612                 // `PendingHTLCsForwardable`.
1613                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1614                         let mut awaiting_retry = false;
1615                         if pmt.is_auto_retryable_now() {
1616                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1617                                         if pending_amt_msat < total_msat {
1618                                                 awaiting_retry = true;
1619                                         }
1620                                 }
1621                         }
1622                         awaiting_retry
1623                 });
1624
1625                 let mut full_failure_ev = None;
1626                 let mut pending_retry_ev = false;
1627                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1628                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1629                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1630                                 return false
1631                         }
1632                         if payment.get().is_fulfilled() {
1633                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1634                                 return false
1635                         }
1636                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1637                         if let Some(scid) = short_channel_id {
1638                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1639                                 // process_onion_failure we should close that channel as it implies our
1640                                 // next-hop is needlessly blaming us!
1641                                 payment.get_mut().insert_previously_failed_scid(scid);
1642                         }
1643
1644                         if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1645                                 let reason = if payment_failed_permanently {
1646                                         PaymentFailureReason::RecipientRejected
1647                                 } else {
1648                                         PaymentFailureReason::RetriesExhausted
1649                                 };
1650                                 payment.get_mut().mark_abandoned(reason);
1651                                 is_retryable_now = false;
1652                         }
1653                         if payment.get().remaining_parts() == 0 {
1654                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1655                                         if !payment_is_probe {
1656                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1657                                                         payment_id: *payment_id,
1658                                                         payment_hash: *payment_hash,
1659                                                         reason: *reason,
1660                                                 });
1661                                         }
1662                                         payment.remove();
1663                                 }
1664                         }
1665                         is_retryable_now
1666                 } else {
1667                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1668                         return false
1669                 };
1670                 core::mem::drop(outbounds);
1671                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1672
1673                 let path_failure = {
1674                         if payment_is_probe {
1675                                 if payment_failed_permanently {
1676                                         events::Event::ProbeSuccessful {
1677                                                 payment_id: *payment_id,
1678                                                 payment_hash: payment_hash.clone(),
1679                                                 path: path.clone(),
1680                                         }
1681                                 } else {
1682                                         events::Event::ProbeFailed {
1683                                                 payment_id: *payment_id,
1684                                                 payment_hash: payment_hash.clone(),
1685                                                 path: path.clone(),
1686                                                 short_channel_id,
1687                                         }
1688                                 }
1689                         } else {
1690                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1691                                 // payment will sit in our outbounds forever.
1692                                 if attempts_remaining && !already_awaiting_retry {
1693                                         debug_assert!(full_failure_ev.is_none());
1694                                         pending_retry_ev = true;
1695                                 }
1696                                 events::Event::PaymentPathFailed {
1697                                         payment_id: Some(*payment_id),
1698                                         payment_hash: payment_hash.clone(),
1699                                         payment_failed_permanently,
1700                                         failure: events::PathFailure::OnPath { network_update },
1701                                         path: path.clone(),
1702                                         short_channel_id,
1703                                         #[cfg(test)]
1704                                         error_code: onion_error_code,
1705                                         #[cfg(test)]
1706                                         error_data: onion_error_data
1707                                 }
1708                         }
1709                 };
1710                 let mut pending_events = pending_events.lock().unwrap();
1711                 pending_events.push_back((path_failure, None));
1712                 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1713                 pending_retry_ev
1714         }
1715
1716         pub(super) fn abandon_payment(
1717                 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1718                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1719         ) {
1720                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1721                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1722                         payment.get_mut().mark_abandoned(reason);
1723                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1724                                 if payment.get().remaining_parts() == 0 {
1725                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1726                                                 payment_id,
1727                                                 payment_hash: *payment_hash,
1728                                                 reason: *reason,
1729                                         }, None));
1730                                         payment.remove();
1731                                 }
1732                         } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1733                                 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1734                                         payment_id,
1735                                 }, None));
1736                                 payment.remove();
1737                         }
1738                 }
1739         }
1740
1741         #[cfg(test)]
1742         pub fn has_pending_payments(&self) -> bool {
1743                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1744         }
1745
1746         #[cfg(test)]
1747         pub fn clear_pending_payments(&self) {
1748                 self.pending_outbound_payments.lock().unwrap().clear()
1749         }
1750 }
1751
1752 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1753 /// payment probe.
1754 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1755         probing_cookie_secret: [u8; 32]) -> bool
1756 {
1757         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1758         target_payment_hash == *payment_hash
1759 }
1760
1761 /// Returns the 'probing cookie' for the given [`PaymentId`].
1762 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1763         let mut preimage = [0u8; 64];
1764         preimage[..32].copy_from_slice(&probing_cookie_secret);
1765         preimage[32..].copy_from_slice(&payment_id.0);
1766         PaymentHash(Sha256::hash(&preimage).into_inner())
1767 }
1768
1769 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1770         (0, Legacy) => {
1771                 (0, session_privs, required),
1772         },
1773         (1, Fulfilled) => {
1774                 (0, session_privs, required),
1775                 (1, payment_hash, option),
1776                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1777         },
1778         (2, Retryable) => {
1779                 (0, session_privs, required),
1780                 (1, pending_fee_msat, option),
1781                 (2, payment_hash, required),
1782                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1783                 // never see it - `payment_params` was added here after the field was added/required.
1784                 (3, payment_params, (option: ReadableArgs, 0)),
1785                 (4, payment_secret, option),
1786                 (5, keysend_preimage, option),
1787                 (6, total_msat, required),
1788                 (7, payment_metadata, option),
1789                 (8, pending_amt_msat, required),
1790                 (9, custom_tlvs, optional_vec),
1791                 (10, starting_block_height, required),
1792                 (11, remaining_max_total_routing_fee_msat, option),
1793                 (not_written, retry_strategy, (static_value, None)),
1794                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1795         },
1796         (3, Abandoned) => {
1797                 (0, session_privs, required),
1798                 (1, reason, option),
1799                 (2, payment_hash, required),
1800         },
1801         (5, AwaitingInvoice) => {
1802                 (0, expiration, required),
1803                 (2, retry_strategy, required),
1804                 (4, max_total_routing_fee_msat, option),
1805         },
1806         (7, InvoiceReceived) => {
1807                 (0, payment_hash, required),
1808                 (2, retry_strategy, required),
1809                 (4, max_total_routing_fee_msat, option),
1810         },
1811 );
1812
1813 #[cfg(test)]
1814 mod tests {
1815         use bitcoin::network::constants::Network;
1816         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1817
1818         use core::time::Duration;
1819
1820         use crate::events::{Event, PathFailure, PaymentFailureReason};
1821         use crate::ln::PaymentHash;
1822         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1823         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1824         use crate::ln::msgs::{ErrorAction, LightningError};
1825         use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1826         use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1827         use crate::offers::offer::OfferBuilder;
1828         use crate::offers::test_utils::*;
1829         use crate::routing::gossip::NetworkGraph;
1830         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1831         use crate::sync::{Arc, Mutex, RwLock};
1832         use crate::util::errors::APIError;
1833         use crate::util::test_utils;
1834
1835         use alloc::collections::VecDeque;
1836
1837         #[test]
1838         fn test_recipient_onion_fields_with_custom_tlvs() {
1839                 let onion_fields = RecipientOnionFields::spontaneous_empty();
1840
1841                 let bad_type_range_tlvs = vec![
1842                         (0, vec![42]),
1843                         (1, vec![42; 32]),
1844                 ];
1845                 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1846
1847                 let keysend_tlv = vec![
1848                         (5482373484, vec![42; 32]),
1849                 ];
1850                 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1851
1852                 let good_tlvs = vec![
1853                         ((1 << 16) + 1, vec![42]),
1854                         ((1 << 16) + 3, vec![42; 32]),
1855                 ];
1856                 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1857         }
1858
1859         #[test]
1860         #[cfg(feature = "std")]
1861         fn fails_paying_after_expiration() {
1862                 do_fails_paying_after_expiration(false);
1863                 do_fails_paying_after_expiration(true);
1864         }
1865         #[cfg(feature = "std")]
1866         fn do_fails_paying_after_expiration(on_retry: bool) {
1867                 let outbound_payments = OutboundPayments::new();
1868                 let logger = test_utils::TestLogger::new();
1869                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1870                 let scorer = RwLock::new(test_utils::TestScorer::new());
1871                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1872                 let secp_ctx = Secp256k1::new();
1873                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1874
1875                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1876                 let payment_params = PaymentParameters::from_node_id(
1877                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1878                                 0
1879                         ).with_expiry_time(past_expiry_time);
1880                 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1881                 let pending_events = Mutex::new(VecDeque::new());
1882                 if on_retry {
1883                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1884                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1885                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1886                                 &&keys_manager, 0).unwrap();
1887                         outbound_payments.find_route_and_send_payment(
1888                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1889                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1890                                 &|_| Ok(()));
1891                         let events = pending_events.lock().unwrap();
1892                         assert_eq!(events.len(), 1);
1893                         if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1894                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1895                         } else { panic!("Unexpected event"); }
1896                 } else {
1897                         let err = outbound_payments.send_payment(
1898                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1899                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1900                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1901                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1902                 }
1903         }
1904
1905         #[test]
1906         fn find_route_error() {
1907                 do_find_route_error(false);
1908                 do_find_route_error(true);
1909         }
1910         fn do_find_route_error(on_retry: bool) {
1911                 let outbound_payments = OutboundPayments::new();
1912                 let logger = test_utils::TestLogger::new();
1913                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1914                 let scorer = RwLock::new(test_utils::TestScorer::new());
1915                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1916                 let secp_ctx = Secp256k1::new();
1917                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1918
1919                 let payment_params = PaymentParameters::from_node_id(
1920                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1921                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1922                 router.expect_find_route(route_params.clone(),
1923                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1924
1925                 let pending_events = Mutex::new(VecDeque::new());
1926                 if on_retry {
1927                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1928                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1929                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1930                                 &&keys_manager, 0).unwrap();
1931                         outbound_payments.find_route_and_send_payment(
1932                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1933                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1934                                 &|_| Ok(()));
1935                         let events = pending_events.lock().unwrap();
1936                         assert_eq!(events.len(), 1);
1937                         if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1938                 } else {
1939                         let err = outbound_payments.send_payment(
1940                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1941                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1942                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1943                         if let RetryableSendFailure::RouteNotFound = err {
1944                         } else { panic!("Unexpected error"); }
1945                 }
1946         }
1947
1948         #[test]
1949         fn initial_send_payment_path_failed_evs() {
1950                 let outbound_payments = OutboundPayments::new();
1951                 let logger = test_utils::TestLogger::new();
1952                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1953                 let scorer = RwLock::new(test_utils::TestScorer::new());
1954                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1955                 let secp_ctx = Secp256k1::new();
1956                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1957
1958                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1959                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1960                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1961                 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1962                 let failed_scid = 42;
1963                 let route = Route {
1964                         paths: vec![Path { hops: vec![RouteHop {
1965                                 pubkey: receiver_pk,
1966                                 node_features: NodeFeatures::empty(),
1967                                 short_channel_id: failed_scid,
1968                                 channel_features: ChannelFeatures::empty(),
1969                                 fee_msat: 0,
1970                                 cltv_expiry_delta: 0,
1971                                 maybe_announced_channel: true,
1972                         }], blinded_tail: None }],
1973                         route_params: Some(route_params.clone()),
1974                 };
1975                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1976                 let mut route_params_w_failed_scid = route_params.clone();
1977                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1978                 let mut route_w_failed_scid = route.clone();
1979                 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
1980                 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
1981                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1982                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1983
1984                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1985                 // PaymentPathFailed event.
1986                 let pending_events = Mutex::new(VecDeque::new());
1987                 outbound_payments.send_payment(
1988                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1989                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1990                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1991                         |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1992                 let mut events = pending_events.lock().unwrap();
1993                 assert_eq!(events.len(), 2);
1994                 if let Event::PaymentPathFailed {
1995                         short_channel_id,
1996                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1997                 {
1998                         assert_eq!(short_channel_id, Some(failed_scid));
1999                 } else { panic!("Unexpected event"); }
2000                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2001                 events.clear();
2002                 core::mem::drop(events);
2003
2004                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2005                 outbound_payments.send_payment(
2006                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2007                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2008                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2009                         |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2010                 assert_eq!(pending_events.lock().unwrap().len(), 0);
2011
2012                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2013                 outbound_payments.send_payment(
2014                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2015                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2016                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2017                         |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2018                 let events = pending_events.lock().unwrap();
2019                 assert_eq!(events.len(), 2);
2020                 if let Event::PaymentPathFailed {
2021                         short_channel_id,
2022                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2023                 {
2024                         assert_eq!(short_channel_id, None);
2025                 } else { panic!("Unexpected event"); }
2026                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2027         }
2028
2029         #[test]
2030         fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2031                 let pending_events = Mutex::new(VecDeque::new());
2032                 let outbound_payments = OutboundPayments::new();
2033                 let payment_id = PaymentId([0; 32]);
2034                 let absolute_expiry = 100;
2035                 let tick_interval = 10;
2036                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2037
2038                 assert!(!outbound_payments.has_pending_payments());
2039                 assert!(
2040                         outbound_payments.add_new_awaiting_invoice(
2041                                 payment_id, expiration, Retry::Attempts(0), None
2042                         ).is_ok()
2043                 );
2044                 assert!(outbound_payments.has_pending_payments());
2045
2046                 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2047                         let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2048                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2049
2050                         assert!(outbound_payments.has_pending_payments());
2051                         assert!(pending_events.lock().unwrap().is_empty());
2052                 }
2053
2054                 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2055                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2056
2057                 assert!(!outbound_payments.has_pending_payments());
2058                 assert!(!pending_events.lock().unwrap().is_empty());
2059                 assert_eq!(
2060                         pending_events.lock().unwrap().pop_front(),
2061                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2062                 );
2063                 assert!(pending_events.lock().unwrap().is_empty());
2064
2065                 assert!(
2066                         outbound_payments.add_new_awaiting_invoice(
2067                                 payment_id, expiration, Retry::Attempts(0), None
2068                         ).is_ok()
2069                 );
2070                 assert!(outbound_payments.has_pending_payments());
2071
2072                 assert!(
2073                         outbound_payments.add_new_awaiting_invoice(
2074                                 payment_id, expiration, Retry::Attempts(0), None
2075                         ).is_err()
2076                 );
2077         }
2078
2079         #[test]
2080         fn removes_stale_awaiting_invoice_using_timer_ticks() {
2081                 let pending_events = Mutex::new(VecDeque::new());
2082                 let outbound_payments = OutboundPayments::new();
2083                 let payment_id = PaymentId([0; 32]);
2084                 let timer_ticks = 3;
2085                 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2086
2087                 assert!(!outbound_payments.has_pending_payments());
2088                 assert!(
2089                         outbound_payments.add_new_awaiting_invoice(
2090                                 payment_id, expiration, Retry::Attempts(0), None
2091                         ).is_ok()
2092                 );
2093                 assert!(outbound_payments.has_pending_payments());
2094
2095                 for i in 0..timer_ticks {
2096                         let duration_since_epoch = Duration::from_secs(i * 60);
2097                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2098
2099                         assert!(outbound_payments.has_pending_payments());
2100                         assert!(pending_events.lock().unwrap().is_empty());
2101                 }
2102
2103                 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2104                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2105
2106                 assert!(!outbound_payments.has_pending_payments());
2107                 assert!(!pending_events.lock().unwrap().is_empty());
2108                 assert_eq!(
2109                         pending_events.lock().unwrap().pop_front(),
2110                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2111                 );
2112                 assert!(pending_events.lock().unwrap().is_empty());
2113
2114                 assert!(
2115                         outbound_payments.add_new_awaiting_invoice(
2116                                 payment_id, expiration, Retry::Attempts(0), None
2117                         ).is_ok()
2118                 );
2119                 assert!(outbound_payments.has_pending_payments());
2120
2121                 assert!(
2122                         outbound_payments.add_new_awaiting_invoice(
2123                                 payment_id, expiration, Retry::Attempts(0), None
2124                         ).is_err()
2125                 );
2126         }
2127
2128         #[test]
2129         fn removes_abandoned_awaiting_invoice() {
2130                 let pending_events = Mutex::new(VecDeque::new());
2131                 let outbound_payments = OutboundPayments::new();
2132                 let payment_id = PaymentId([0; 32]);
2133                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2134
2135                 assert!(!outbound_payments.has_pending_payments());
2136                 assert!(
2137                         outbound_payments.add_new_awaiting_invoice(
2138                                 payment_id, expiration, Retry::Attempts(0), None
2139                         ).is_ok()
2140                 );
2141                 assert!(outbound_payments.has_pending_payments());
2142
2143                 outbound_payments.abandon_payment(
2144                         payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2145                 );
2146                 assert!(!outbound_payments.has_pending_payments());
2147                 assert!(!pending_events.lock().unwrap().is_empty());
2148                 assert_eq!(
2149                         pending_events.lock().unwrap().pop_front(),
2150                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2151                 );
2152                 assert!(pending_events.lock().unwrap().is_empty());
2153         }
2154
2155         #[cfg(feature = "std")]
2156         #[test]
2157         fn fails_sending_payment_for_expired_bolt12_invoice() {
2158                 let logger = test_utils::TestLogger::new();
2159                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2160                 let scorer = RwLock::new(test_utils::TestScorer::new());
2161                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2162                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2163
2164                 let pending_events = Mutex::new(VecDeque::new());
2165                 let outbound_payments = OutboundPayments::new();
2166                 let payment_id = PaymentId([0; 32]);
2167                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2168
2169                 assert!(
2170                         outbound_payments.add_new_awaiting_invoice(
2171                                 payment_id, expiration, Retry::Attempts(0), None
2172                         ).is_ok()
2173                 );
2174                 assert!(outbound_payments.has_pending_payments());
2175
2176                 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2177                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2178                         .amount_msats(1000)
2179                         .build().unwrap()
2180                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2181                         .build().unwrap()
2182                         .sign(payer_sign).unwrap()
2183                         .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2184                         .build().unwrap()
2185                         .sign(recipient_sign).unwrap();
2186
2187                 assert_eq!(
2188                         outbound_payments.send_payment_for_bolt12_invoice(
2189                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2190                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2191                         ),
2192                         Ok(()),
2193                 );
2194                 assert!(!outbound_payments.has_pending_payments());
2195
2196                 let payment_hash = invoice.payment_hash();
2197                 let reason = Some(PaymentFailureReason::PaymentExpired);
2198
2199                 assert!(!pending_events.lock().unwrap().is_empty());
2200                 assert_eq!(
2201                         pending_events.lock().unwrap().pop_front(),
2202                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2203                 );
2204                 assert!(pending_events.lock().unwrap().is_empty());
2205         }
2206
2207         #[test]
2208         fn fails_finding_route_for_bolt12_invoice() {
2209                 let logger = test_utils::TestLogger::new();
2210                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2211                 let scorer = RwLock::new(test_utils::TestScorer::new());
2212                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2213                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2214
2215                 let pending_events = Mutex::new(VecDeque::new());
2216                 let outbound_payments = OutboundPayments::new();
2217                 let payment_id = PaymentId([0; 32]);
2218                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2219
2220                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2221                         .amount_msats(1000)
2222                         .build().unwrap()
2223                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2224                         .build().unwrap()
2225                         .sign(payer_sign).unwrap()
2226                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2227                         .build().unwrap()
2228                         .sign(recipient_sign).unwrap();
2229
2230                 assert!(
2231                         outbound_payments.add_new_awaiting_invoice(
2232                                 payment_id, expiration, Retry::Attempts(0),
2233                                 Some(invoice.amount_msats() / 100 + 50_000)
2234                         ).is_ok()
2235                 );
2236                 assert!(outbound_payments.has_pending_payments());
2237
2238                 router.expect_find_route(
2239                         RouteParameters::from_payment_params_and_value(
2240                                 PaymentParameters::from_bolt12_invoice(&invoice),
2241                                 invoice.amount_msats(),
2242                         ),
2243                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2244                 );
2245
2246                 assert_eq!(
2247                         outbound_payments.send_payment_for_bolt12_invoice(
2248                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2249                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2250                         ),
2251                         Ok(()),
2252                 );
2253                 assert!(!outbound_payments.has_pending_payments());
2254
2255                 let payment_hash = invoice.payment_hash();
2256                 let reason = Some(PaymentFailureReason::RouteNotFound);
2257
2258                 assert!(!pending_events.lock().unwrap().is_empty());
2259                 assert_eq!(
2260                         pending_events.lock().unwrap().pop_front(),
2261                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2262                 );
2263                 assert!(pending_events.lock().unwrap().is_empty());
2264         }
2265
2266         #[test]
2267         fn fails_paying_for_bolt12_invoice() {
2268                 let logger = test_utils::TestLogger::new();
2269                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2270                 let scorer = RwLock::new(test_utils::TestScorer::new());
2271                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2272                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2273
2274                 let pending_events = Mutex::new(VecDeque::new());
2275                 let outbound_payments = OutboundPayments::new();
2276                 let payment_id = PaymentId([0; 32]);
2277                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2278
2279                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2280                         .amount_msats(1000)
2281                         .build().unwrap()
2282                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2283                         .build().unwrap()
2284                         .sign(payer_sign).unwrap()
2285                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2286                         .build().unwrap()
2287                         .sign(recipient_sign).unwrap();
2288
2289                 assert!(
2290                         outbound_payments.add_new_awaiting_invoice(
2291                                 payment_id, expiration, Retry::Attempts(0),
2292                                 Some(invoice.amount_msats() / 100 + 50_000)
2293                         ).is_ok()
2294                 );
2295                 assert!(outbound_payments.has_pending_payments());
2296
2297                 let route_params = RouteParameters::from_payment_params_and_value(
2298                         PaymentParameters::from_bolt12_invoice(&invoice),
2299                         invoice.amount_msats(),
2300                 );
2301                 router.expect_find_route(
2302                         route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2303                 );
2304
2305                 assert_eq!(
2306                         outbound_payments.send_payment_for_bolt12_invoice(
2307                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2308                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2309                         ),
2310                         Ok(()),
2311                 );
2312                 assert!(!outbound_payments.has_pending_payments());
2313
2314                 let payment_hash = invoice.payment_hash();
2315                 let reason = Some(PaymentFailureReason::UnexpectedError);
2316
2317                 assert!(!pending_events.lock().unwrap().is_empty());
2318                 assert_eq!(
2319                         pending_events.lock().unwrap().pop_front(),
2320                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2321                 );
2322                 assert!(pending_events.lock().unwrap().is_empty());
2323         }
2324
2325         #[test]
2326         fn sends_payment_for_bolt12_invoice() {
2327                 let logger = test_utils::TestLogger::new();
2328                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2329                 let scorer = RwLock::new(test_utils::TestScorer::new());
2330                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2331                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2332
2333                 let pending_events = Mutex::new(VecDeque::new());
2334                 let outbound_payments = OutboundPayments::new();
2335                 let payment_id = PaymentId([0; 32]);
2336                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2337
2338                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2339                         .amount_msats(1000)
2340                         .build().unwrap()
2341                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2342                         .build().unwrap()
2343                         .sign(payer_sign).unwrap()
2344                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2345                         .build().unwrap()
2346                         .sign(recipient_sign).unwrap();
2347
2348                 let route_params = RouteParameters {
2349                         payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2350                         final_value_msat: invoice.amount_msats(),
2351                         max_total_routing_fee_msat: Some(1234),
2352                 };
2353                 router.expect_find_route(
2354                         route_params.clone(),
2355                         Ok(Route {
2356                                 paths: vec![
2357                                         Path {
2358                                                 hops: vec![
2359                                                         RouteHop {
2360                                                                 pubkey: recipient_pubkey(),
2361                                                                 node_features: NodeFeatures::empty(),
2362                                                                 short_channel_id: 42,
2363                                                                 channel_features: ChannelFeatures::empty(),
2364                                                                 fee_msat: invoice.amount_msats(),
2365                                                                 cltv_expiry_delta: 0,
2366                                                                 maybe_announced_channel: true,
2367                                                         }
2368                                                 ],
2369                                                 blinded_tail: None,
2370                                         }
2371                                 ],
2372                                 route_params: Some(route_params),
2373                         })
2374                 );
2375
2376                 assert!(!outbound_payments.has_pending_payments());
2377                 assert_eq!(
2378                         outbound_payments.send_payment_for_bolt12_invoice(
2379                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2380                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2381                         ),
2382                         Err(Bolt12PaymentError::UnexpectedInvoice),
2383                 );
2384                 assert!(!outbound_payments.has_pending_payments());
2385                 assert!(pending_events.lock().unwrap().is_empty());
2386
2387                 assert!(
2388                         outbound_payments.add_new_awaiting_invoice(
2389                                 payment_id, expiration, Retry::Attempts(0), Some(1234)
2390                         ).is_ok()
2391                 );
2392                 assert!(outbound_payments.has_pending_payments());
2393
2394                 assert_eq!(
2395                         outbound_payments.send_payment_for_bolt12_invoice(
2396                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2397                                 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2398                         ),
2399                         Ok(()),
2400                 );
2401                 assert!(outbound_payments.has_pending_payments());
2402                 assert!(pending_events.lock().unwrap().is_empty());
2403
2404                 assert_eq!(
2405                         outbound_payments.send_payment_for_bolt12_invoice(
2406                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2407                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2408                         ),
2409                         Err(Bolt12PaymentError::DuplicateInvoice),
2410                 );
2411                 assert!(outbound_payments.has_pending_payments());
2412                 assert!(pending_events.lock().unwrap().is_empty());
2413         }
2414 }