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