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