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