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