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