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