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