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