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