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