0b8819aa0c6dbd47e1b3e2f692079a19526a62da
[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 pay_params = PaymentParameters::from_bolt12_invoice(&invoice);
811                 let amount_msat = invoice.amount_msats();
812                 let mut route_params = RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
813                 if let Some(max_fee_msat) = max_total_routing_fee_msat {
814                         route_params.max_total_routing_fee_msat = Some(max_fee_msat);
815                 }
816
817                 self.find_route_and_send_payment(
818                         payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
819                         entropy_source, node_signer, best_block_height, logger, pending_events,
820                         &send_payment_along_path
821                 );
822
823                 Ok(())
824         }
825
826         pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
827                 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
828                 best_block_height: u32,
829                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
830                 send_payment_along_path: SP,
831         )
832         where
833                 R::Target: Router,
834                 ES::Target: EntropySource,
835                 NS::Target: NodeSigner,
836                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
837                 IH: Fn() -> InFlightHtlcs,
838                 FH: Fn() -> Vec<ChannelDetails>,
839                 L::Target: Logger,
840         {
841                 let _single_thread = self.retry_lock.lock().unwrap();
842                 loop {
843                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
844                         let mut retry_id_route_params = None;
845                         for (pmt_id, pmt) in outbounds.iter_mut() {
846                                 if pmt.is_auto_retryable_now() {
847                                         if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
848                                                 if pending_amt_msat < total_msat {
849                                                         retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
850                                                                 final_value_msat: *total_msat - *pending_amt_msat,
851                                                                 payment_params: params.clone(),
852                                                                 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
853                                                         }));
854                                                         break
855                                                 }
856                                         } else { debug_assert!(false); }
857                                 }
858                         }
859                         core::mem::drop(outbounds);
860                         if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
861                                 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)
862                         } else { break }
863                 }
864
865                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
866                 outbounds.retain(|pmt_id, pmt| {
867                         let mut retain = true;
868                         if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
869                                 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
870                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
871                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
872                                                 payment_id: *pmt_id,
873                                                 payment_hash: *payment_hash,
874                                                 reason: *reason,
875                                         }, None));
876                                         retain = false;
877                                 }
878                         }
879                         retain
880                 });
881         }
882
883         pub(super) fn needs_abandon(&self) -> bool {
884                 let outbounds = self.pending_outbound_payments.lock().unwrap();
885                 outbounds.iter().any(|(_, pmt)|
886                         !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
887                         !pmt.is_awaiting_invoice())
888         }
889
890         /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
891         /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
892         ///
893         /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
894         /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
895         fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
896                 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
897                 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, mut route_params: RouteParameters,
898                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
899                 node_signer: &NS, best_block_height: u32, logger: &L,
900                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
901         ) -> Result<(), RetryableSendFailure>
902         where
903                 R::Target: Router,
904                 ES::Target: EntropySource,
905                 NS::Target: NodeSigner,
906                 L::Target: Logger,
907                 IH: Fn() -> InFlightHtlcs,
908                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
909         {
910                 #[cfg(feature = "std")] {
911                         if has_expired(&route_params) {
912                                 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
913                                         payment_id, payment_hash);
914                                 return Err(RetryableSendFailure::PaymentExpired)
915                         }
916                 }
917
918                 onion_utils::set_max_path_length(
919                         &mut route_params, &recipient_onion, keysend_preimage, best_block_height
920                 )
921                         .map_err(|()| {
922                                 log_error!(logger, "Can't construct an onion packet without exceeding 1300-byte onion \
923                                         hop_data length for payment with id {} and hash {}", payment_id, payment_hash);
924                                 RetryableSendFailure::OnionPacketSizeExceeded
925                         })?;
926
927                 let mut route = router.find_route_with_id(
928                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
929                         Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
930                         payment_hash, payment_id,
931                 ).map_err(|_| {
932                         log_error!(logger, "Failed to find route for payment with id {} and hash {}",
933                                 payment_id, payment_hash);
934                         RetryableSendFailure::RouteNotFound
935                 })?;
936
937                 if route.route_params.as_ref() != Some(&route_params) {
938                         debug_assert!(false,
939                                 "Routers are expected to return a Route which includes the requested RouteParameters");
940                         route.route_params = Some(route_params.clone());
941                 }
942
943                 let onion_session_privs = self.add_new_pending_payment(payment_hash,
944                         recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
945                         Some(route_params.payment_params.clone()), entropy_source, best_block_height)
946                         .map_err(|_| {
947                                 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
948                                         payment_id, payment_hash);
949                                 RetryableSendFailure::DuplicatePayment
950                         })?;
951
952                 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion,
953                         keysend_preimage, payment_id, None, onion_session_privs, node_signer,
954                         best_block_height, &send_payment_along_path);
955                 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
956                         payment_id, payment_hash, res);
957                 if let Err(e) = res {
958                         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);
959                 }
960                 Ok(())
961         }
962
963         fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
964                 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
965                 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
966                 node_signer: &NS, best_block_height: u32, logger: &L,
967                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
968         )
969         where
970                 R::Target: Router,
971                 ES::Target: EntropySource,
972                 NS::Target: NodeSigner,
973                 L::Target: Logger,
974                 IH: Fn() -> InFlightHtlcs,
975                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
976         {
977                 #[cfg(feature = "std")] {
978                         if has_expired(&route_params) {
979                                 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
980                                 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
981                                 return
982                         }
983                 }
984
985                 let mut route = match router.find_route_with_id(
986                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
987                         Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
988                         payment_hash, payment_id,
989                 ) {
990                         Ok(route) => route,
991                         Err(e) => {
992                                 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
993                                 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
994                                 return
995                         }
996                 };
997
998                 if route.route_params.as_ref() != Some(&route_params) {
999                         debug_assert!(false,
1000                                 "Routers are expected to return a Route which includes the requested RouteParameters");
1001                         route.route_params = Some(route_params.clone());
1002                 }
1003
1004                 for path in route.paths.iter() {
1005                         if path.hops.len() == 0 {
1006                                 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
1007                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1008                                 return
1009                         }
1010                 }
1011
1012                 macro_rules! abandon_with_entry {
1013                         ($payment: expr, $reason: expr) => {
1014                                 $payment.get_mut().mark_abandoned($reason);
1015                                 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
1016                                         if $payment.get().remaining_parts() == 0 {
1017                                                 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1018                                                         payment_id,
1019                                                         payment_hash,
1020                                                         reason: *reason,
1021                                                 }, None));
1022                                                 $payment.remove();
1023                                         }
1024                                 }
1025                         }
1026                 }
1027                 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
1028                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1029                         match outbounds.entry(payment_id) {
1030                                 hash_map::Entry::Occupied(mut payment) => {
1031                                         match payment.get() {
1032                                                 PendingOutboundPayment::Retryable {
1033                                                         total_msat, keysend_preimage, payment_secret, payment_metadata,
1034                                                         custom_tlvs, pending_amt_msat, ..
1035                                                 } => {
1036                                                         const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1037                                                         let retry_amt_msat = route.get_total_amount();
1038                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1039                                                                 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);
1040                                                                 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1041                                                                 return
1042                                                         }
1043
1044                                                         if !payment.get().is_retryable_now() {
1045                                                                 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1046                                                                 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1047                                                                 return
1048                                                         }
1049
1050                                                         let total_msat = *total_msat;
1051                                                         let recipient_onion = RecipientOnionFields {
1052                                                                 payment_secret: *payment_secret,
1053                                                                 payment_metadata: payment_metadata.clone(),
1054                                                                 custom_tlvs: custom_tlvs.clone(),
1055                                                         };
1056                                                         let keysend_preimage = *keysend_preimage;
1057
1058                                                         let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1059                                                         for _ in 0..route.paths.len() {
1060                                                                 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1061                                                         }
1062
1063                                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1064                                                                 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1065                                                         }
1066
1067                                                         payment.get_mut().increment_attempts();
1068
1069                                                         (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1070                                                 },
1071                                                 PendingOutboundPayment::Legacy { .. } => {
1072                                                         log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1073                                                         return
1074                                                 },
1075                                                 PendingOutboundPayment::AwaitingInvoice { .. } => {
1076                                                         log_error!(logger, "Payment not yet sent");
1077                                                         return
1078                                                 },
1079                                                 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1080                                                         let total_amount = route_params.final_value_msat;
1081                                                         let recipient_onion = RecipientOnionFields {
1082                                                                 payment_secret: None,
1083                                                                 payment_metadata: None,
1084                                                                 custom_tlvs: vec![],
1085                                                         };
1086                                                         let retry_strategy = Some(*retry_strategy);
1087                                                         let payment_params = Some(route_params.payment_params.clone());
1088                                                         let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1089                                                                 *payment_hash, recipient_onion.clone(), None, &route,
1090                                                                 retry_strategy, payment_params, entropy_source, best_block_height
1091                                                         );
1092                                                         *payment.into_mut() = retryable_payment;
1093                                                         (total_amount, recipient_onion, None, onion_session_privs)
1094                                                 },
1095                                                 PendingOutboundPayment::Fulfilled { .. } => {
1096                                                         log_error!(logger, "Payment already completed");
1097                                                         return
1098                                                 },
1099                                                 PendingOutboundPayment::Abandoned { .. } => {
1100                                                         log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1101                                                         return
1102                                                 },
1103                                         }
1104                                 },
1105                                 hash_map::Entry::Vacant(_) => {
1106                                         log_error!(logger, "Payment with ID {} not found", &payment_id);
1107                                         return
1108                                 }
1109                         }
1110                 };
1111                 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion, keysend_preimage,
1112                         payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1113                         &send_payment_along_path);
1114                 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1115                 if let Err(e) = res {
1116                         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);
1117                 }
1118         }
1119
1120         fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1121                 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1122                 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1123                 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1124                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1125         )
1126         where
1127                 R::Target: Router,
1128                 ES::Target: EntropySource,
1129                 NS::Target: NodeSigner,
1130                 L::Target: Logger,
1131                 IH: Fn() -> InFlightHtlcs,
1132                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1133         {
1134                 match err {
1135                         PaymentSendFailure::AllFailedResendSafe(errs) => {
1136                                 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);
1137                                 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);
1138                         },
1139                         PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1140                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1141                                 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1142                                 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1143                                 // return `Ok()` here, ignoring any retry errors.
1144                                 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);
1145                         },
1146                         PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1147                                 // This may happen if we send a payment and some paths fail, but only due to a temporary
1148                                 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1149                                 // initial HTLC-Add messages yet.
1150                         },
1151                         PaymentSendFailure::PathParameterError(results) => {
1152                                 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1153                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1154                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1155                         },
1156                         PaymentSendFailure::ParameterError(e) => {
1157                                 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1158                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1159                         },
1160                         PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1161                 }
1162         }
1163
1164         fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1165                 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1166                 paths: Vec<Path>, path_results: I, logger: &L,
1167                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1168         ) where L::Target: Logger {
1169                 let mut events = pending_events.lock().unwrap();
1170                 debug_assert_eq!(paths.len(), path_results.len());
1171                 for (path, path_res) in paths.into_iter().zip(path_results) {
1172                         if let Err(e) = path_res {
1173                                 if let APIError::MonitorUpdateInProgress = e { continue }
1174                                 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1175                                 let mut failed_scid = None;
1176                                 if let APIError::ChannelUnavailable { .. } = e {
1177                                         let scid = path.hops[0].short_channel_id;
1178                                         failed_scid = Some(scid);
1179                                         route_params.payment_params.previously_failed_channels.push(scid);
1180                                 }
1181                                 events.push_back((events::Event::PaymentPathFailed {
1182                                         payment_id: Some(payment_id),
1183                                         payment_hash,
1184                                         payment_failed_permanently: false,
1185                                         failure: events::PathFailure::InitialSend { err: e },
1186                                         path,
1187                                         short_channel_id: failed_scid,
1188                                         #[cfg(test)]
1189                                         error_code: None,
1190                                         #[cfg(test)]
1191                                         error_data: None,
1192                                 }, None));
1193                         }
1194                 }
1195         }
1196
1197         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1198                 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1199                 best_block_height: u32, send_payment_along_path: F
1200         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1201         where
1202                 ES::Target: EntropySource,
1203                 NS::Target: NodeSigner,
1204                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1205         {
1206                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1207                 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1208
1209                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1210
1211                 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1212                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1213                                 err: "No need probing a path with less than two hops".to_string()
1214                         }))
1215                 }
1216
1217                 let route = Route { paths: vec![path], route_params: None };
1218                 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1219                         RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1220                         entropy_source, best_block_height)?;
1221
1222                 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1223                 match self.pay_route_internal(&route, payment_hash, &recipient_onion_fields,
1224                         None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1225                 ) {
1226                         Ok(()) => Ok((payment_hash, payment_id)),
1227                         Err(e) => {
1228                                 self.remove_outbound_if_all_failed(payment_id, &e);
1229                                 Err(e)
1230                         }
1231                 }
1232         }
1233
1234         #[cfg(test)]
1235         pub(super) fn test_set_payment_metadata(
1236                 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1237         ) {
1238                 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1239                         PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1240                                 *payment_metadata = new_payment_metadata;
1241                         },
1242                         _ => panic!("Need a retryable payment to update metadata on"),
1243                 }
1244         }
1245
1246         #[cfg(test)]
1247         pub(super) fn test_add_new_pending_payment<ES: Deref>(
1248                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1249                 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1250         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1251                 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1252         }
1253
1254         pub(super) fn add_new_pending_payment<ES: Deref>(
1255                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1256                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1257                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1258         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1259                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1260                 match pending_outbounds.entry(payment_id) {
1261                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1262                         hash_map::Entry::Vacant(entry) => {
1263                                 let (payment, onion_session_privs) = self.create_pending_payment(
1264                                         payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1265                                         payment_params, entropy_source, best_block_height
1266                                 );
1267                                 entry.insert(payment);
1268                                 Ok(onion_session_privs)
1269                         },
1270                 }
1271         }
1272
1273         fn create_pending_payment<ES: Deref>(
1274                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1275                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1276                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1277         ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1278         where
1279                 ES::Target: EntropySource,
1280         {
1281                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1282                 for _ in 0..route.paths.len() {
1283                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
1284                 }
1285
1286                 let mut payment = PendingOutboundPayment::Retryable {
1287                         retry_strategy,
1288                         attempts: PaymentAttempts::new(),
1289                         payment_params,
1290                         session_privs: new_hash_set(),
1291                         pending_amt_msat: 0,
1292                         pending_fee_msat: Some(0),
1293                         payment_hash,
1294                         payment_secret: recipient_onion.payment_secret,
1295                         payment_metadata: recipient_onion.payment_metadata,
1296                         keysend_preimage,
1297                         custom_tlvs: recipient_onion.custom_tlvs,
1298                         starting_block_height: best_block_height,
1299                         total_msat: route.get_total_amount(),
1300                         remaining_max_total_routing_fee_msat:
1301                                 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1302                 };
1303
1304                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1305                         assert!(payment.insert(*session_priv_bytes, path));
1306                 }
1307
1308                 (payment, onion_session_privs)
1309         }
1310
1311         pub(super) fn add_new_awaiting_invoice(
1312                 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1313                 max_total_routing_fee_msat: Option<u64>
1314         ) -> Result<(), ()> {
1315                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1316                 match pending_outbounds.entry(payment_id) {
1317                         hash_map::Entry::Occupied(_) => Err(()),
1318                         hash_map::Entry::Vacant(entry) => {
1319                                 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1320                                         expiration,
1321                                         retry_strategy,
1322                                         max_total_routing_fee_msat,
1323                                 });
1324
1325                                 Ok(())
1326                         },
1327                 }
1328         }
1329
1330         fn pay_route_internal<NS: Deref, F>(
1331                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
1332                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1333                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1334                 send_payment_along_path: &F
1335         ) -> Result<(), PaymentSendFailure>
1336         where
1337                 NS::Target: NodeSigner,
1338                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1339         {
1340                 if route.paths.len() < 1 {
1341                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1342                 }
1343                 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1344                         && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1345                 {
1346                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1347                 }
1348                 let mut total_value = 0;
1349                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1350                 let mut path_errs = Vec::with_capacity(route.paths.len());
1351                 'path_check: for path in route.paths.iter() {
1352                         if path.hops.len() < 1 || path.hops.len() > 20 {
1353                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1354                                 continue 'path_check;
1355                         }
1356                         let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1357                                 usize::max_value() } else { path.hops.len() - 1 };
1358                         for (idx, hop) in path.hops.iter().enumerate() {
1359                                 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1360                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1361                                         continue 'path_check;
1362                                 }
1363                         }
1364                         for (i, hop) in path.hops.iter().enumerate() {
1365                                 // Check for duplicate channel_id in the remaining hops of the path
1366                                 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1367                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1368                                         continue 'path_check;
1369                                 }
1370                         }
1371                         total_value += path.final_value_msat();
1372                         path_errs.push(Ok(()));
1373                 }
1374                 if path_errs.iter().any(|e| e.is_err()) {
1375                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1376                 }
1377                 if let Some(amt_msat) = recv_value_msat {
1378                         total_value = amt_msat;
1379                 }
1380
1381                 let cur_height = best_block_height + 1;
1382                 let mut results = Vec::new();
1383                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1384                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1385                         let mut path_res = send_payment_along_path(SendAlongPathArgs {
1386                                 path: &path, payment_hash: &payment_hash, recipient_onion, total_value,
1387                                 cur_height, payment_id, keysend_preimage: &keysend_preimage,
1388                                 session_priv_bytes
1389                         });
1390                         match path_res {
1391                                 Ok(_) => {},
1392                                 Err(APIError::MonitorUpdateInProgress) => {
1393                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
1394                                         // considered "in flight" and we shouldn't remove it from the
1395                                         // PendingOutboundPayment set.
1396                                 },
1397                                 Err(_) => {
1398                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1399                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1400                                                 let removed = payment.remove(&session_priv_bytes, Some(path));
1401                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1402                                         } else {
1403                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
1404                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1405                                         }
1406                                 }
1407                         }
1408                         results.push(path_res);
1409                 }
1410                 let mut has_ok = false;
1411                 let mut has_err = false;
1412                 let mut has_unsent = false;
1413                 let mut total_ok_fees_msat = 0;
1414                 let mut total_ok_amt_sent_msat = 0;
1415                 for (res, path) in results.iter().zip(route.paths.iter()) {
1416                         if res.is_ok() {
1417                                 has_ok = true;
1418                                 total_ok_fees_msat += path.fee_msat();
1419                                 total_ok_amt_sent_msat += path.final_value_msat();
1420                         }
1421                         if res.is_err() { has_err = true; }
1422                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1423                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1424                                 // PartialFailure.
1425                                 has_err = true;
1426                                 has_ok = true;
1427                                 total_ok_fees_msat += path.fee_msat();
1428                                 total_ok_amt_sent_msat += path.final_value_msat();
1429                         } else if res.is_err() {
1430                                 has_unsent = true;
1431                         }
1432                 }
1433                 if has_err && has_ok {
1434                         Err(PaymentSendFailure::PartialFailure {
1435                                 results,
1436                                 payment_id,
1437                                 failed_paths_retry: if has_unsent {
1438                                         if let Some(route_params) = &route.route_params {
1439                                                 let mut route_params = route_params.clone();
1440                                                 // We calculate the leftover fee budget we're allowed to spend by
1441                                                 // subtracting the used fee from the total fee budget.
1442                                                 route_params.max_total_routing_fee_msat = route_params
1443                                                         .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1444
1445                                                 // We calculate the remaining target amount by subtracting the succeded
1446                                                 // path values.
1447                                                 route_params.final_value_msat = route_params.final_value_msat
1448                                                         .saturating_sub(total_ok_amt_sent_msat);
1449                                                 Some(route_params)
1450                                         } else { None }
1451                                 } else { None },
1452                         })
1453                 } else if has_err {
1454                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1455                 } else {
1456                         Ok(())
1457                 }
1458         }
1459
1460         #[cfg(test)]
1461         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1462                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1463                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1464                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1465                 send_payment_along_path: F
1466         ) -> Result<(), PaymentSendFailure>
1467         where
1468                 NS::Target: NodeSigner,
1469                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1470         {
1471                 self.pay_route_internal(route, payment_hash, &recipient_onion,
1472                         keysend_preimage, payment_id, recv_value_msat, onion_session_privs,
1473                         node_signer, best_block_height, &send_payment_along_path)
1474                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1475         }
1476
1477         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1478         // map as the payment is free to be resent.
1479         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1480                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1481                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1482                         debug_assert!(removed, "We should always have a pending payment to remove here");
1483                 }
1484         }
1485
1486         pub(super) fn claim_htlc<L: Deref>(
1487                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1488                 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1489                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1490                 logger: &L,
1491         ) where L::Target: Logger {
1492                 let mut session_priv_bytes = [0; 32];
1493                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1494                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1495                 let mut pending_events = pending_events.lock().unwrap();
1496                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1497                         if !payment.get().is_fulfilled() {
1498                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1499                                 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1500                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1501                                 pending_events.push_back((events::Event::PaymentSent {
1502                                         payment_id: Some(payment_id),
1503                                         payment_preimage,
1504                                         payment_hash,
1505                                         fee_paid_msat,
1506                                 }, Some(ev_completion_action.clone())));
1507                                 payment.get_mut().mark_fulfilled();
1508                         }
1509
1510                         if from_onchain {
1511                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1512                                 // This could potentially lead to removing a pending payment too early,
1513                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1514                                 // restart.
1515                                 // TODO: We should have a second monitor event that informs us of payments
1516                                 // irrevocably fulfilled.
1517                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1518                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1519                                         pending_events.push_back((events::Event::PaymentPathSuccessful {
1520                                                 payment_id,
1521                                                 payment_hash,
1522                                                 path,
1523                                         }, Some(ev_completion_action)));
1524                                 }
1525                         }
1526                 } else {
1527                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1528                 }
1529         }
1530
1531         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1532                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1533         {
1534                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1535                 let mut pending_events = pending_events.lock().unwrap();
1536                 for source in sources {
1537                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1538                                 let mut session_priv_bytes = [0; 32];
1539                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1540                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1541                                         assert!(payment.get().is_fulfilled());
1542                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1543                                                 let payment_hash = payment.get().payment_hash();
1544                                                 debug_assert!(payment_hash.is_some());
1545                                                 pending_events.push_back((events::Event::PaymentPathSuccessful {
1546                                                         payment_id,
1547                                                         payment_hash,
1548                                                         path,
1549                                                 }, None));
1550                                         }
1551                                 }
1552                         }
1553                 }
1554         }
1555
1556         pub(super) fn remove_stale_payments(
1557                 &self, duration_since_epoch: Duration,
1558                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1559         {
1560                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1561                 let mut pending_events = pending_events.lock().unwrap();
1562                 pending_outbound_payments.retain(|payment_id, payment| match payment {
1563                         // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1564                         // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1565                         // this could race the user making a duplicate send_payment call and our idempotency
1566                         // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1567                         // removal. This should be more than sufficient to ensure the idempotency of any
1568                         // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1569                         // processed.
1570                         PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1571                                 let mut no_remaining_entries = session_privs.is_empty();
1572                                 if no_remaining_entries {
1573                                         for (ev, _) in pending_events.iter() {
1574                                                 match ev {
1575                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1576                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1577                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1578                                                                         if payment_id == ev_payment_id {
1579                                                                                 no_remaining_entries = false;
1580                                                                                 break;
1581                                                                         }
1582                                                                 },
1583                                                         _ => {},
1584                                                 }
1585                                         }
1586                                 }
1587                                 if no_remaining_entries {
1588                                         *timer_ticks_without_htlcs += 1;
1589                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1590                                 } else {
1591                                         *timer_ticks_without_htlcs = 0;
1592                                         true
1593                                 }
1594                         },
1595                         PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1596                                 let is_stale = match expiration {
1597                                         StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1598                                                 *absolute_expiry <= duration_since_epoch
1599                                         },
1600                                         StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1601                                                 if *timer_ticks_remaining > 0 {
1602                                                         *timer_ticks_remaining -= 1;
1603                                                         false
1604                                                 } else {
1605                                                         true
1606                                                 }
1607                                         },
1608                                 };
1609                                 if is_stale {
1610                                         pending_events.push_back(
1611                                                 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1612                                         );
1613                                         false
1614                                 } else {
1615                                         true
1616                                 }
1617                         },
1618                         _ => true,
1619                 });
1620         }
1621
1622         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1623         pub(super) fn fail_htlc<L: Deref>(
1624                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1625                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1626                 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1627                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1628         ) -> bool where L::Target: Logger {
1629                 #[cfg(test)]
1630                 let DecodedOnionFailure {
1631                         network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1632                         onion_error_data, failed_within_blinded_path
1633                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1634                 #[cfg(not(test))]
1635                 let DecodedOnionFailure {
1636                         network_update, short_channel_id, payment_failed_permanently, failed_within_blinded_path
1637                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1638
1639                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1640                 let mut session_priv_bytes = [0; 32];
1641                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1642                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1643
1644                 // If any payments already need retry, there's no need to generate a redundant
1645                 // `PendingHTLCsForwardable`.
1646                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1647                         let mut awaiting_retry = false;
1648                         if pmt.is_auto_retryable_now() {
1649                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1650                                         if pending_amt_msat < total_msat {
1651                                                 awaiting_retry = true;
1652                                         }
1653                                 }
1654                         }
1655                         awaiting_retry
1656                 });
1657
1658                 let mut full_failure_ev = None;
1659                 let mut pending_retry_ev = false;
1660                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1661                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1662                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1663                                 return false
1664                         }
1665                         if payment.get().is_fulfilled() {
1666                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1667                                 return false
1668                         }
1669                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1670                         if let Some(scid) = short_channel_id {
1671                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1672                                 // process_onion_failure we should close that channel as it implies our
1673                                 // next-hop is needlessly blaming us!
1674                                 payment.get_mut().insert_previously_failed_scid(scid);
1675                         }
1676                         if failed_within_blinded_path {
1677                                 debug_assert!(short_channel_id.is_none());
1678                                 if let Some(bt) = &path.blinded_tail {
1679                                         payment.get_mut().insert_previously_failed_blinded_path(&bt);
1680                                 } else { debug_assert!(false); }
1681                         }
1682
1683                         if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1684                                 let reason = if payment_failed_permanently {
1685                                         PaymentFailureReason::RecipientRejected
1686                                 } else {
1687                                         PaymentFailureReason::RetriesExhausted
1688                                 };
1689                                 payment.get_mut().mark_abandoned(reason);
1690                                 is_retryable_now = false;
1691                         }
1692                         if payment.get().remaining_parts() == 0 {
1693                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1694                                         if !payment_is_probe {
1695                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1696                                                         payment_id: *payment_id,
1697                                                         payment_hash: *payment_hash,
1698                                                         reason: *reason,
1699                                                 });
1700                                         }
1701                                         payment.remove();
1702                                 }
1703                         }
1704                         is_retryable_now
1705                 } else {
1706                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1707                         return false
1708                 };
1709                 core::mem::drop(outbounds);
1710                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1711
1712                 let path_failure = {
1713                         if payment_is_probe {
1714                                 if payment_failed_permanently {
1715                                         events::Event::ProbeSuccessful {
1716                                                 payment_id: *payment_id,
1717                                                 payment_hash: payment_hash.clone(),
1718                                                 path: path.clone(),
1719                                         }
1720                                 } else {
1721                                         events::Event::ProbeFailed {
1722                                                 payment_id: *payment_id,
1723                                                 payment_hash: payment_hash.clone(),
1724                                                 path: path.clone(),
1725                                                 short_channel_id,
1726                                         }
1727                                 }
1728                         } else {
1729                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1730                                 // payment will sit in our outbounds forever.
1731                                 if attempts_remaining && !already_awaiting_retry {
1732                                         debug_assert!(full_failure_ev.is_none());
1733                                         pending_retry_ev = true;
1734                                 }
1735                                 events::Event::PaymentPathFailed {
1736                                         payment_id: Some(*payment_id),
1737                                         payment_hash: payment_hash.clone(),
1738                                         payment_failed_permanently,
1739                                         failure: events::PathFailure::OnPath { network_update },
1740                                         path: path.clone(),
1741                                         short_channel_id,
1742                                         #[cfg(test)]
1743                                         error_code: onion_error_code,
1744                                         #[cfg(test)]
1745                                         error_data: onion_error_data
1746                                 }
1747                         }
1748                 };
1749                 let mut pending_events = pending_events.lock().unwrap();
1750                 pending_events.push_back((path_failure, None));
1751                 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1752                 pending_retry_ev
1753         }
1754
1755         pub(super) fn abandon_payment(
1756                 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1757                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1758         ) {
1759                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1760                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1761                         payment.get_mut().mark_abandoned(reason);
1762                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1763                                 if payment.get().remaining_parts() == 0 {
1764                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1765                                                 payment_id,
1766                                                 payment_hash: *payment_hash,
1767                                                 reason: *reason,
1768                                         }, None));
1769                                         payment.remove();
1770                                 }
1771                         } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1772                                 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1773                                         payment_id,
1774                                 }, None));
1775                                 payment.remove();
1776                         }
1777                 }
1778         }
1779
1780         #[cfg(test)]
1781         pub fn has_pending_payments(&self) -> bool {
1782                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1783         }
1784
1785         #[cfg(test)]
1786         pub fn clear_pending_payments(&self) {
1787                 self.pending_outbound_payments.lock().unwrap().clear()
1788         }
1789 }
1790
1791 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1792 /// payment probe.
1793 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1794         probing_cookie_secret: [u8; 32]) -> bool
1795 {
1796         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1797         target_payment_hash == *payment_hash
1798 }
1799
1800 /// Returns the 'probing cookie' for the given [`PaymentId`].
1801 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1802         let mut preimage = [0u8; 64];
1803         preimage[..32].copy_from_slice(&probing_cookie_secret);
1804         preimage[32..].copy_from_slice(&payment_id.0);
1805         PaymentHash(Sha256::hash(&preimage).to_byte_array())
1806 }
1807
1808 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1809         (0, Legacy) => {
1810                 (0, session_privs, required),
1811         },
1812         (1, Fulfilled) => {
1813                 (0, session_privs, required),
1814                 (1, payment_hash, option),
1815                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1816         },
1817         (2, Retryable) => {
1818                 (0, session_privs, required),
1819                 (1, pending_fee_msat, option),
1820                 (2, payment_hash, required),
1821                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1822                 // never see it - `payment_params` was added here after the field was added/required.
1823                 (3, payment_params, (option: ReadableArgs, 0)),
1824                 (4, payment_secret, option),
1825                 (5, keysend_preimage, option),
1826                 (6, total_msat, required),
1827                 (7, payment_metadata, option),
1828                 (8, pending_amt_msat, required),
1829                 (9, custom_tlvs, optional_vec),
1830                 (10, starting_block_height, required),
1831                 (11, remaining_max_total_routing_fee_msat, option),
1832                 (not_written, retry_strategy, (static_value, None)),
1833                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1834         },
1835         (3, Abandoned) => {
1836                 (0, session_privs, required),
1837                 (1, reason, option),
1838                 (2, payment_hash, required),
1839         },
1840         (5, AwaitingInvoice) => {
1841                 (0, expiration, required),
1842                 (2, retry_strategy, required),
1843                 (4, max_total_routing_fee_msat, option),
1844         },
1845         (7, InvoiceReceived) => {
1846                 (0, payment_hash, required),
1847                 (2, retry_strategy, required),
1848                 (4, max_total_routing_fee_msat, option),
1849         },
1850 );
1851
1852 #[cfg(test)]
1853 mod tests {
1854         use bitcoin::network::Network;
1855         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1856
1857         use core::time::Duration;
1858
1859         use crate::events::{Event, PathFailure, PaymentFailureReason};
1860         use crate::ln::types::PaymentHash;
1861         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1862         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1863         use crate::ln::msgs::{ErrorAction, LightningError};
1864         use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1865         #[cfg(feature = "std")]
1866         use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1867         use crate::offers::offer::OfferBuilder;
1868         use crate::offers::test_utils::*;
1869         use crate::routing::gossip::NetworkGraph;
1870         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1871         use crate::sync::{Arc, Mutex, RwLock};
1872         use crate::util::errors::APIError;
1873         use crate::util::test_utils;
1874
1875         use alloc::collections::VecDeque;
1876
1877         #[test]
1878         fn test_recipient_onion_fields_with_custom_tlvs() {
1879                 let onion_fields = RecipientOnionFields::spontaneous_empty();
1880
1881                 let bad_type_range_tlvs = vec![
1882                         (0, vec![42]),
1883                         (1, vec![42; 32]),
1884                 ];
1885                 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1886
1887                 let keysend_tlv = vec![
1888                         (5482373484, vec![42; 32]),
1889                 ];
1890                 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1891
1892                 let good_tlvs = vec![
1893                         ((1 << 16) + 1, vec![42]),
1894                         ((1 << 16) + 3, vec![42; 32]),
1895                 ];
1896                 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1897         }
1898
1899         #[test]
1900         #[cfg(feature = "std")]
1901         fn fails_paying_after_expiration() {
1902                 do_fails_paying_after_expiration(false);
1903                 do_fails_paying_after_expiration(true);
1904         }
1905         #[cfg(feature = "std")]
1906         fn do_fails_paying_after_expiration(on_retry: bool) {
1907                 let outbound_payments = OutboundPayments::new();
1908                 let logger = test_utils::TestLogger::new();
1909                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1910                 let scorer = RwLock::new(test_utils::TestScorer::new());
1911                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1912                 let secp_ctx = Secp256k1::new();
1913                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1914
1915                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1916                 let payment_params = PaymentParameters::from_node_id(
1917                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1918                                 0
1919                         ).with_expiry_time(past_expiry_time);
1920                 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1921                 let pending_events = Mutex::new(VecDeque::new());
1922                 if on_retry {
1923                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1924                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1925                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1926                                 &&keys_manager, 0).unwrap();
1927                         outbound_payments.find_route_and_send_payment(
1928                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1929                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1930                                 &|_| Ok(()));
1931                         let events = pending_events.lock().unwrap();
1932                         assert_eq!(events.len(), 1);
1933                         if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1934                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1935                         } else { panic!("Unexpected event"); }
1936                 } else {
1937                         let err = outbound_payments.send_payment(
1938                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1939                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1940                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1941                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1942                 }
1943         }
1944
1945         #[test]
1946         fn find_route_error() {
1947                 do_find_route_error(false);
1948                 do_find_route_error(true);
1949         }
1950         fn do_find_route_error(on_retry: bool) {
1951                 let outbound_payments = OutboundPayments::new();
1952                 let logger = test_utils::TestLogger::new();
1953                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1954                 let scorer = RwLock::new(test_utils::TestScorer::new());
1955                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1956                 let secp_ctx = Secp256k1::new();
1957                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1958
1959                 let payment_params = PaymentParameters::from_node_id(
1960                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1961                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1962                 router.expect_find_route(route_params.clone(),
1963                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1964
1965                 let pending_events = Mutex::new(VecDeque::new());
1966                 if on_retry {
1967                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1968                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1969                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1970                                 &&keys_manager, 0).unwrap();
1971                         outbound_payments.find_route_and_send_payment(
1972                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1973                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1974                                 &|_| Ok(()));
1975                         let events = pending_events.lock().unwrap();
1976                         assert_eq!(events.len(), 1);
1977                         if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1978                 } else {
1979                         let err = outbound_payments.send_payment(
1980                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1981                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1982                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1983                         if let RetryableSendFailure::RouteNotFound = err {
1984                         } else { panic!("Unexpected error"); }
1985                 }
1986         }
1987
1988         #[test]
1989         fn initial_send_payment_path_failed_evs() {
1990                 let outbound_payments = OutboundPayments::new();
1991                 let logger = test_utils::TestLogger::new();
1992                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1993                 let scorer = RwLock::new(test_utils::TestScorer::new());
1994                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1995                 let secp_ctx = Secp256k1::new();
1996                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1997
1998                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1999                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
2000                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
2001                 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
2002                 let failed_scid = 42;
2003                 let route = Route {
2004                         paths: vec![Path { hops: vec![RouteHop {
2005                                 pubkey: receiver_pk,
2006                                 node_features: NodeFeatures::empty(),
2007                                 short_channel_id: failed_scid,
2008                                 channel_features: ChannelFeatures::empty(),
2009                                 fee_msat: 0,
2010                                 cltv_expiry_delta: 0,
2011                                 maybe_announced_channel: true,
2012                         }], blinded_tail: None }],
2013                         route_params: Some(route_params.clone()),
2014                 };
2015                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2016                 let mut route_params_w_failed_scid = route_params.clone();
2017                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
2018                 let mut route_w_failed_scid = route.clone();
2019                 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
2020                 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
2021                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2022                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2023
2024                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
2025                 // PaymentPathFailed event.
2026                 let pending_events = Mutex::new(VecDeque::new());
2027                 outbound_payments.send_payment(
2028                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2029                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2030                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2031                         |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2032                 let mut events = pending_events.lock().unwrap();
2033                 assert_eq!(events.len(), 2);
2034                 if let Event::PaymentPathFailed {
2035                         short_channel_id,
2036                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2037                 {
2038                         assert_eq!(short_channel_id, Some(failed_scid));
2039                 } else { panic!("Unexpected event"); }
2040                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2041                 events.clear();
2042                 core::mem::drop(events);
2043
2044                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2045                 outbound_payments.send_payment(
2046                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2047                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2048                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2049                         |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2050                 assert_eq!(pending_events.lock().unwrap().len(), 0);
2051
2052                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2053                 outbound_payments.send_payment(
2054                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2055                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2056                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2057                         |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2058                 let events = pending_events.lock().unwrap();
2059                 assert_eq!(events.len(), 2);
2060                 if let Event::PaymentPathFailed {
2061                         short_channel_id,
2062                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2063                 {
2064                         assert_eq!(short_channel_id, None);
2065                 } else { panic!("Unexpected event"); }
2066                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2067         }
2068
2069         #[test]
2070         fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2071                 let pending_events = Mutex::new(VecDeque::new());
2072                 let outbound_payments = OutboundPayments::new();
2073                 let payment_id = PaymentId([0; 32]);
2074                 let absolute_expiry = 100;
2075                 let tick_interval = 10;
2076                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2077
2078                 assert!(!outbound_payments.has_pending_payments());
2079                 assert!(
2080                         outbound_payments.add_new_awaiting_invoice(
2081                                 payment_id, expiration, Retry::Attempts(0), None
2082                         ).is_ok()
2083                 );
2084                 assert!(outbound_payments.has_pending_payments());
2085
2086                 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2087                         let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2088                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2089
2090                         assert!(outbound_payments.has_pending_payments());
2091                         assert!(pending_events.lock().unwrap().is_empty());
2092                 }
2093
2094                 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2095                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2096
2097                 assert!(!outbound_payments.has_pending_payments());
2098                 assert!(!pending_events.lock().unwrap().is_empty());
2099                 assert_eq!(
2100                         pending_events.lock().unwrap().pop_front(),
2101                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2102                 );
2103                 assert!(pending_events.lock().unwrap().is_empty());
2104
2105                 assert!(
2106                         outbound_payments.add_new_awaiting_invoice(
2107                                 payment_id, expiration, Retry::Attempts(0), None
2108                         ).is_ok()
2109                 );
2110                 assert!(outbound_payments.has_pending_payments());
2111
2112                 assert!(
2113                         outbound_payments.add_new_awaiting_invoice(
2114                                 payment_id, expiration, Retry::Attempts(0), None
2115                         ).is_err()
2116                 );
2117         }
2118
2119         #[test]
2120         fn removes_stale_awaiting_invoice_using_timer_ticks() {
2121                 let pending_events = Mutex::new(VecDeque::new());
2122                 let outbound_payments = OutboundPayments::new();
2123                 let payment_id = PaymentId([0; 32]);
2124                 let timer_ticks = 3;
2125                 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2126
2127                 assert!(!outbound_payments.has_pending_payments());
2128                 assert!(
2129                         outbound_payments.add_new_awaiting_invoice(
2130                                 payment_id, expiration, Retry::Attempts(0), None
2131                         ).is_ok()
2132                 );
2133                 assert!(outbound_payments.has_pending_payments());
2134
2135                 for i in 0..timer_ticks {
2136                         let duration_since_epoch = Duration::from_secs(i * 60);
2137                         outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2138
2139                         assert!(outbound_payments.has_pending_payments());
2140                         assert!(pending_events.lock().unwrap().is_empty());
2141                 }
2142
2143                 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2144                 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2145
2146                 assert!(!outbound_payments.has_pending_payments());
2147                 assert!(!pending_events.lock().unwrap().is_empty());
2148                 assert_eq!(
2149                         pending_events.lock().unwrap().pop_front(),
2150                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2151                 );
2152                 assert!(pending_events.lock().unwrap().is_empty());
2153
2154                 assert!(
2155                         outbound_payments.add_new_awaiting_invoice(
2156                                 payment_id, expiration, Retry::Attempts(0), None
2157                         ).is_ok()
2158                 );
2159                 assert!(outbound_payments.has_pending_payments());
2160
2161                 assert!(
2162                         outbound_payments.add_new_awaiting_invoice(
2163                                 payment_id, expiration, Retry::Attempts(0), None
2164                         ).is_err()
2165                 );
2166         }
2167
2168         #[test]
2169         fn removes_abandoned_awaiting_invoice() {
2170                 let pending_events = Mutex::new(VecDeque::new());
2171                 let outbound_payments = OutboundPayments::new();
2172                 let payment_id = PaymentId([0; 32]);
2173                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2174
2175                 assert!(!outbound_payments.has_pending_payments());
2176                 assert!(
2177                         outbound_payments.add_new_awaiting_invoice(
2178                                 payment_id, expiration, Retry::Attempts(0), None
2179                         ).is_ok()
2180                 );
2181                 assert!(outbound_payments.has_pending_payments());
2182
2183                 outbound_payments.abandon_payment(
2184                         payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2185                 );
2186                 assert!(!outbound_payments.has_pending_payments());
2187                 assert!(!pending_events.lock().unwrap().is_empty());
2188                 assert_eq!(
2189                         pending_events.lock().unwrap().pop_front(),
2190                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
2191                 );
2192                 assert!(pending_events.lock().unwrap().is_empty());
2193         }
2194
2195         #[cfg(feature = "std")]
2196         #[test]
2197         fn fails_sending_payment_for_expired_bolt12_invoice() {
2198                 let logger = test_utils::TestLogger::new();
2199                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2200                 let scorer = RwLock::new(test_utils::TestScorer::new());
2201                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2202                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2203
2204                 let pending_events = Mutex::new(VecDeque::new());
2205                 let outbound_payments = OutboundPayments::new();
2206                 let payment_id = PaymentId([0; 32]);
2207                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2208
2209                 assert!(
2210                         outbound_payments.add_new_awaiting_invoice(
2211                                 payment_id, expiration, Retry::Attempts(0), None
2212                         ).is_ok()
2213                 );
2214                 assert!(outbound_payments.has_pending_payments());
2215
2216                 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2217                 let invoice = OfferBuilder::new(recipient_pubkey())
2218                         .amount_msats(1000)
2219                         .build().unwrap()
2220                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2221                         .build().unwrap()
2222                         .sign(payer_sign).unwrap()
2223                         .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2224                         .build().unwrap()
2225                         .sign(recipient_sign).unwrap();
2226
2227                 assert_eq!(
2228                         outbound_payments.send_payment_for_bolt12_invoice(
2229                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2230                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2231                         ),
2232                         Ok(()),
2233                 );
2234                 assert!(!outbound_payments.has_pending_payments());
2235
2236                 let payment_hash = invoice.payment_hash();
2237                 let reason = Some(PaymentFailureReason::PaymentExpired);
2238
2239                 assert!(!pending_events.lock().unwrap().is_empty());
2240                 assert_eq!(
2241                         pending_events.lock().unwrap().pop_front(),
2242                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2243                 );
2244                 assert!(pending_events.lock().unwrap().is_empty());
2245         }
2246
2247         #[test]
2248         fn fails_finding_route_for_bolt12_invoice() {
2249                 let logger = test_utils::TestLogger::new();
2250                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2251                 let scorer = RwLock::new(test_utils::TestScorer::new());
2252                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2253                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2254
2255                 let pending_events = Mutex::new(VecDeque::new());
2256                 let outbound_payments = OutboundPayments::new();
2257                 let payment_id = PaymentId([0; 32]);
2258                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2259
2260                 let invoice = OfferBuilder::new(recipient_pubkey())
2261                         .amount_msats(1000)
2262                         .build().unwrap()
2263                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2264                         .build().unwrap()
2265                         .sign(payer_sign).unwrap()
2266                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2267                         .build().unwrap()
2268                         .sign(recipient_sign).unwrap();
2269
2270                 assert!(
2271                         outbound_payments.add_new_awaiting_invoice(
2272                                 payment_id, expiration, Retry::Attempts(0),
2273                                 Some(invoice.amount_msats() / 100 + 50_000)
2274                         ).is_ok()
2275                 );
2276                 assert!(outbound_payments.has_pending_payments());
2277
2278                 router.expect_find_route(
2279                         RouteParameters::from_payment_params_and_value(
2280                                 PaymentParameters::from_bolt12_invoice(&invoice),
2281                                 invoice.amount_msats(),
2282                         ),
2283                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2284                 );
2285
2286                 assert_eq!(
2287                         outbound_payments.send_payment_for_bolt12_invoice(
2288                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2289                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2290                         ),
2291                         Ok(()),
2292                 );
2293                 assert!(!outbound_payments.has_pending_payments());
2294
2295                 let payment_hash = invoice.payment_hash();
2296                 let reason = Some(PaymentFailureReason::RouteNotFound);
2297
2298                 assert!(!pending_events.lock().unwrap().is_empty());
2299                 assert_eq!(
2300                         pending_events.lock().unwrap().pop_front(),
2301                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2302                 );
2303                 assert!(pending_events.lock().unwrap().is_empty());
2304         }
2305
2306         #[test]
2307         fn sends_payment_for_bolt12_invoice() {
2308                 let logger = test_utils::TestLogger::new();
2309                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2310                 let scorer = RwLock::new(test_utils::TestScorer::new());
2311                 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2312                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2313
2314                 let pending_events = Mutex::new(VecDeque::new());
2315                 let outbound_payments = OutboundPayments::new();
2316                 let payment_id = PaymentId([0; 32]);
2317                 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2318
2319                 let invoice = OfferBuilder::new(recipient_pubkey())
2320                         .amount_msats(1000)
2321                         .build().unwrap()
2322                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2323                         .build().unwrap()
2324                         .sign(payer_sign).unwrap()
2325                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2326                         .build().unwrap()
2327                         .sign(recipient_sign).unwrap();
2328
2329                 let route_params = RouteParameters {
2330                         payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2331                         final_value_msat: invoice.amount_msats(),
2332                         max_total_routing_fee_msat: Some(1234),
2333                 };
2334                 router.expect_find_route(
2335                         route_params.clone(),
2336                         Ok(Route {
2337                                 paths: vec![
2338                                         Path {
2339                                                 hops: vec![
2340                                                         RouteHop {
2341                                                                 pubkey: recipient_pubkey(),
2342                                                                 node_features: NodeFeatures::empty(),
2343                                                                 short_channel_id: 42,
2344                                                                 channel_features: ChannelFeatures::empty(),
2345                                                                 fee_msat: invoice.amount_msats(),
2346                                                                 cltv_expiry_delta: 0,
2347                                                                 maybe_announced_channel: true,
2348                                                         }
2349                                                 ],
2350                                                 blinded_tail: None,
2351                                         }
2352                                 ],
2353                                 route_params: Some(route_params),
2354                         })
2355                 );
2356
2357                 assert!(!outbound_payments.has_pending_payments());
2358                 assert_eq!(
2359                         outbound_payments.send_payment_for_bolt12_invoice(
2360                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2361                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2362                         ),
2363                         Err(Bolt12PaymentError::UnexpectedInvoice),
2364                 );
2365                 assert!(!outbound_payments.has_pending_payments());
2366                 assert!(pending_events.lock().unwrap().is_empty());
2367
2368                 assert!(
2369                         outbound_payments.add_new_awaiting_invoice(
2370                                 payment_id, expiration, Retry::Attempts(0), Some(1234)
2371                         ).is_ok()
2372                 );
2373                 assert!(outbound_payments.has_pending_payments());
2374
2375                 assert_eq!(
2376                         outbound_payments.send_payment_for_bolt12_invoice(
2377                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2378                                 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2379                         ),
2380                         Ok(()),
2381                 );
2382                 assert!(outbound_payments.has_pending_payments());
2383                 assert!(pending_events.lock().unwrap().is_empty());
2384
2385                 assert_eq!(
2386                         outbound_payments.send_payment_for_bolt12_invoice(
2387                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2388                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2389                         ),
2390                         Err(Bolt12PaymentError::DuplicateInvoice),
2391                 );
2392                 assert!(outbound_payments.has_pending_payments());
2393                 assert!(pending_events.lock().unwrap().is_empty());
2394         }
2395 }