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