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