2f1e3b0dd0e3d4358f7b43b5e01d1706f3ec005f
[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                 for (res, path) in results.iter().zip(route.paths.iter()) {
1326                         if res.is_ok() { has_ok = true; }
1327                         if res.is_err() { has_err = true; }
1328                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1329                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1330                                 // PartialFailure.
1331                                 has_err = true;
1332                                 has_ok = true;
1333                         } else if res.is_err() {
1334                                 pending_amt_unsent += path.final_value_msat();
1335                         }
1336                 }
1337                 if has_err && has_ok {
1338                         Err(PaymentSendFailure::PartialFailure {
1339                                 results,
1340                                 payment_id,
1341                                 failed_paths_retry: if pending_amt_unsent != 0 {
1342                                         if let Some(payment_params) = route.route_params.as_ref().map(|p| p.payment_params.clone()) {
1343                                                 Some(RouteParameters {
1344                                                         payment_params,
1345                                                         final_value_msat: pending_amt_unsent,
1346                                                         max_total_routing_fee_msat: None,
1347                                                 })
1348                                         } else { None }
1349                                 } else { None },
1350                         })
1351                 } else if has_err {
1352                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1353                 } else {
1354                         Ok(())
1355                 }
1356         }
1357
1358         #[cfg(test)]
1359         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1360                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1361                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1362                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1363                 send_payment_along_path: F
1364         ) -> Result<(), PaymentSendFailure>
1365         where
1366                 NS::Target: NodeSigner,
1367                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1368         {
1369                 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1370                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1371                         &send_payment_along_path)
1372                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1373         }
1374
1375         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1376         // map as the payment is free to be resent.
1377         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1378                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1379                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1380                         debug_assert!(removed, "We should always have a pending payment to remove here");
1381                 }
1382         }
1383
1384         pub(super) fn claim_htlc<L: Deref>(
1385                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1386                 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1387                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1388                 logger: &L,
1389         ) where L::Target: Logger {
1390                 let mut session_priv_bytes = [0; 32];
1391                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1392                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1393                 let mut pending_events = pending_events.lock().unwrap();
1394                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1395                         if !payment.get().is_fulfilled() {
1396                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1397                                 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1398                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1399                                 pending_events.push_back((events::Event::PaymentSent {
1400                                         payment_id: Some(payment_id),
1401                                         payment_preimage,
1402                                         payment_hash,
1403                                         fee_paid_msat,
1404                                 }, Some(ev_completion_action.clone())));
1405                                 payment.get_mut().mark_fulfilled();
1406                         }
1407
1408                         if from_onchain {
1409                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1410                                 // This could potentially lead to removing a pending payment too early,
1411                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1412                                 // restart.
1413                                 // TODO: We should have a second monitor event that informs us of payments
1414                                 // irrevocably fulfilled.
1415                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1416                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1417                                         pending_events.push_back((events::Event::PaymentPathSuccessful {
1418                                                 payment_id,
1419                                                 payment_hash,
1420                                                 path,
1421                                         }, Some(ev_completion_action)));
1422                                 }
1423                         }
1424                 } else {
1425                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1426                 }
1427         }
1428
1429         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1430                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1431         {
1432                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1433                 let mut pending_events = pending_events.lock().unwrap();
1434                 for source in sources {
1435                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1436                                 let mut session_priv_bytes = [0; 32];
1437                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1438                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1439                                         assert!(payment.get().is_fulfilled());
1440                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1441                                                 let payment_hash = payment.get().payment_hash();
1442                                                 debug_assert!(payment_hash.is_some());
1443                                                 pending_events.push_back((events::Event::PaymentPathSuccessful {
1444                                                         payment_id,
1445                                                         payment_hash,
1446                                                         path,
1447                                                 }, None));
1448                                         }
1449                                 }
1450                         }
1451                 }
1452         }
1453
1454         pub(super) fn remove_stale_payments(
1455                 &self, pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1456         {
1457                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1458                 let mut pending_events = pending_events.lock().unwrap();
1459                 pending_outbound_payments.retain(|payment_id, payment| {
1460                         // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1461                         // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1462                         // this could race the user making a duplicate send_payment call and our idempotency
1463                         // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1464                         // removal. This should be more than sufficient to ensure the idempotency of any
1465                         // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1466                         // processed.
1467                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1468                                 let mut no_remaining_entries = session_privs.is_empty();
1469                                 if no_remaining_entries {
1470                                         for (ev, _) in pending_events.iter() {
1471                                                 match ev {
1472                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1473                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1474                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1475                                                                         if payment_id == ev_payment_id {
1476                                                                                 no_remaining_entries = false;
1477                                                                                 break;
1478                                                                         }
1479                                                                 },
1480                                                         _ => {},
1481                                                 }
1482                                         }
1483                                 }
1484                                 if no_remaining_entries {
1485                                         *timer_ticks_without_htlcs += 1;
1486                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1487                                 } else {
1488                                         *timer_ticks_without_htlcs = 0;
1489                                         true
1490                                 }
1491                         } else if let PendingOutboundPayment::AwaitingInvoice { timer_ticks_without_response, .. } = payment {
1492                                 *timer_ticks_without_response += 1;
1493                                 if *timer_ticks_without_response <= INVOICE_REQUEST_TIMEOUT_TICKS {
1494                                         true
1495                                 } else {
1496                                         pending_events.push_back(
1497                                                 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1498                                         );
1499                                         false
1500                                 }
1501                         } else { true }
1502                 });
1503         }
1504
1505         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1506         pub(super) fn fail_htlc<L: Deref>(
1507                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1508                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1509                 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1510                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1511         ) -> bool where L::Target: Logger {
1512                 #[cfg(test)]
1513                 let DecodedOnionFailure {
1514                         network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data
1515                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1516                 #[cfg(not(test))]
1517                 let DecodedOnionFailure { network_update, short_channel_id, payment_retryable } =
1518                         onion_error.decode_onion_failure(secp_ctx, logger, &source);
1519
1520                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1521                 let mut session_priv_bytes = [0; 32];
1522                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1523                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1524
1525                 // If any payments already need retry, there's no need to generate a redundant
1526                 // `PendingHTLCsForwardable`.
1527                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1528                         let mut awaiting_retry = false;
1529                         if pmt.is_auto_retryable_now() {
1530                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1531                                         if pending_amt_msat < total_msat {
1532                                                 awaiting_retry = true;
1533                                         }
1534                                 }
1535                         }
1536                         awaiting_retry
1537                 });
1538
1539                 let mut full_failure_ev = None;
1540                 let mut pending_retry_ev = false;
1541                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1542                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1543                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1544                                 return false
1545                         }
1546                         if payment.get().is_fulfilled() {
1547                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1548                                 return false
1549                         }
1550                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1551                         if let Some(scid) = short_channel_id {
1552                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1553                                 // process_onion_failure we should close that channel as it implies our
1554                                 // next-hop is needlessly blaming us!
1555                                 payment.get_mut().insert_previously_failed_scid(scid);
1556                         }
1557
1558                         if payment_is_probe || !is_retryable_now || !payment_retryable {
1559                                 let reason = if !payment_retryable {
1560                                         PaymentFailureReason::RecipientRejected
1561                                 } else {
1562                                         PaymentFailureReason::RetriesExhausted
1563                                 };
1564                                 payment.get_mut().mark_abandoned(reason);
1565                                 is_retryable_now = false;
1566                         }
1567                         if payment.get().remaining_parts() == 0 {
1568                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1569                                         if !payment_is_probe {
1570                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1571                                                         payment_id: *payment_id,
1572                                                         payment_hash: *payment_hash,
1573                                                         reason: *reason,
1574                                                 });
1575                                         }
1576                                         payment.remove();
1577                                 }
1578                         }
1579                         is_retryable_now
1580                 } else {
1581                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1582                         return false
1583                 };
1584                 core::mem::drop(outbounds);
1585                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1586
1587                 let path_failure = {
1588                         if payment_is_probe {
1589                                 if !payment_retryable {
1590                                         events::Event::ProbeSuccessful {
1591                                                 payment_id: *payment_id,
1592                                                 payment_hash: payment_hash.clone(),
1593                                                 path: path.clone(),
1594                                         }
1595                                 } else {
1596                                         events::Event::ProbeFailed {
1597                                                 payment_id: *payment_id,
1598                                                 payment_hash: payment_hash.clone(),
1599                                                 path: path.clone(),
1600                                                 short_channel_id,
1601                                         }
1602                                 }
1603                         } else {
1604                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1605                                 // payment will sit in our outbounds forever.
1606                                 if attempts_remaining && !already_awaiting_retry {
1607                                         debug_assert!(full_failure_ev.is_none());
1608                                         pending_retry_ev = true;
1609                                 }
1610                                 events::Event::PaymentPathFailed {
1611                                         payment_id: Some(*payment_id),
1612                                         payment_hash: payment_hash.clone(),
1613                                         payment_failed_permanently: !payment_retryable,
1614                                         failure: events::PathFailure::OnPath { network_update },
1615                                         path: path.clone(),
1616                                         short_channel_id,
1617                                         #[cfg(test)]
1618                                         error_code: onion_error_code,
1619                                         #[cfg(test)]
1620                                         error_data: onion_error_data
1621                                 }
1622                         }
1623                 };
1624                 let mut pending_events = pending_events.lock().unwrap();
1625                 pending_events.push_back((path_failure, None));
1626                 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1627                 pending_retry_ev
1628         }
1629
1630         pub(super) fn abandon_payment(
1631                 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1632                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1633         ) {
1634                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1635                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1636                         payment.get_mut().mark_abandoned(reason);
1637                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1638                                 if payment.get().remaining_parts() == 0 {
1639                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1640                                                 payment_id,
1641                                                 payment_hash: *payment_hash,
1642                                                 reason: *reason,
1643                                         }, None));
1644                                         payment.remove();
1645                                 }
1646                         } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1647                                 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1648                                         payment_id,
1649                                 }, None));
1650                                 payment.remove();
1651                         }
1652                 }
1653         }
1654
1655         #[cfg(test)]
1656         pub fn has_pending_payments(&self) -> bool {
1657                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1658         }
1659
1660         #[cfg(test)]
1661         pub fn clear_pending_payments(&self) {
1662                 self.pending_outbound_payments.lock().unwrap().clear()
1663         }
1664 }
1665
1666 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1667 /// payment probe.
1668 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1669         probing_cookie_secret: [u8; 32]) -> bool
1670 {
1671         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1672         target_payment_hash == *payment_hash
1673 }
1674
1675 /// Returns the 'probing cookie' for the given [`PaymentId`].
1676 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1677         let mut preimage = [0u8; 64];
1678         preimage[..32].copy_from_slice(&probing_cookie_secret);
1679         preimage[32..].copy_from_slice(&payment_id.0);
1680         PaymentHash(Sha256::hash(&preimage).into_inner())
1681 }
1682
1683 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1684         (0, Legacy) => {
1685                 (0, session_privs, required),
1686         },
1687         (1, Fulfilled) => {
1688                 (0, session_privs, required),
1689                 (1, payment_hash, option),
1690                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1691         },
1692         (2, Retryable) => {
1693                 (0, session_privs, required),
1694                 (1, pending_fee_msat, option),
1695                 (2, payment_hash, required),
1696                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1697                 // never see it - `payment_params` was added here after the field was added/required.
1698                 (3, payment_params, (option: ReadableArgs, 0)),
1699                 (4, payment_secret, option),
1700                 (5, keysend_preimage, option),
1701                 (6, total_msat, required),
1702                 (7, payment_metadata, option),
1703                 (8, pending_amt_msat, required),
1704                 (9, custom_tlvs, optional_vec),
1705                 (10, starting_block_height, required),
1706                 (11, remaining_max_total_routing_fee_msat, option),
1707                 (not_written, retry_strategy, (static_value, None)),
1708                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1709         },
1710         (3, Abandoned) => {
1711                 (0, session_privs, required),
1712                 (1, reason, option),
1713                 (2, payment_hash, required),
1714         },
1715         (5, AwaitingInvoice) => {
1716                 (0, timer_ticks_without_response, required),
1717                 (2, retry_strategy, required),
1718                 (4, max_total_routing_fee_msat, option),
1719         },
1720         (7, InvoiceReceived) => {
1721                 (0, payment_hash, required),
1722                 (2, retry_strategy, required),
1723                 (4, max_total_routing_fee_msat, option),
1724         },
1725 );
1726
1727 #[cfg(test)]
1728 mod tests {
1729         use bitcoin::network::constants::Network;
1730         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1731
1732         use crate::events::{Event, PathFailure, PaymentFailureReason};
1733         use crate::ln::PaymentHash;
1734         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1735         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1736         use crate::ln::msgs::{ErrorAction, LightningError};
1737         use crate::ln::outbound_payment::{Bolt12PaymentError, INVOICE_REQUEST_TIMEOUT_TICKS, OutboundPayments, Retry, RetryableSendFailure};
1738         use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1739         use crate::offers::offer::OfferBuilder;
1740         use crate::offers::test_utils::*;
1741         use crate::routing::gossip::NetworkGraph;
1742         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1743         use crate::sync::{Arc, Mutex, RwLock};
1744         use crate::util::errors::APIError;
1745         use crate::util::test_utils;
1746
1747         use alloc::collections::VecDeque;
1748
1749         #[test]
1750         fn test_recipient_onion_fields_with_custom_tlvs() {
1751                 let onion_fields = RecipientOnionFields::spontaneous_empty();
1752
1753                 let bad_type_range_tlvs = vec![
1754                         (0, vec![42]),
1755                         (1, vec![42; 32]),
1756                 ];
1757                 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1758
1759                 let keysend_tlv = vec![
1760                         (5482373484, vec![42; 32]),
1761                 ];
1762                 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1763
1764                 let good_tlvs = vec![
1765                         ((1 << 16) + 1, vec![42]),
1766                         ((1 << 16) + 3, vec![42; 32]),
1767                 ];
1768                 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1769         }
1770
1771         #[test]
1772         #[cfg(feature = "std")]
1773         fn fails_paying_after_expiration() {
1774                 do_fails_paying_after_expiration(false);
1775                 do_fails_paying_after_expiration(true);
1776         }
1777         #[cfg(feature = "std")]
1778         fn do_fails_paying_after_expiration(on_retry: bool) {
1779                 let outbound_payments = OutboundPayments::new();
1780                 let logger = test_utils::TestLogger::new();
1781                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1782                 let scorer = RwLock::new(test_utils::TestScorer::new());
1783                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1784                 let secp_ctx = Secp256k1::new();
1785                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1786
1787                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1788                 let payment_params = PaymentParameters::from_node_id(
1789                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1790                                 0
1791                         ).with_expiry_time(past_expiry_time);
1792                 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1793                 let pending_events = Mutex::new(VecDeque::new());
1794                 if on_retry {
1795                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1796                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1797                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1798                                 &&keys_manager, 0).unwrap();
1799                         outbound_payments.find_route_and_send_payment(
1800                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1801                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1802                                 &|_| Ok(()));
1803                         let events = pending_events.lock().unwrap();
1804                         assert_eq!(events.len(), 1);
1805                         if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1806                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1807                         } else { panic!("Unexpected event"); }
1808                 } else {
1809                         let err = outbound_payments.send_payment(
1810                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1811                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1812                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1813                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1814                 }
1815         }
1816
1817         #[test]
1818         fn find_route_error() {
1819                 do_find_route_error(false);
1820                 do_find_route_error(true);
1821         }
1822         fn do_find_route_error(on_retry: bool) {
1823                 let outbound_payments = OutboundPayments::new();
1824                 let logger = test_utils::TestLogger::new();
1825                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1826                 let scorer = RwLock::new(test_utils::TestScorer::new());
1827                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1828                 let secp_ctx = Secp256k1::new();
1829                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1830
1831                 let payment_params = PaymentParameters::from_node_id(
1832                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1833                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1834                 router.expect_find_route(route_params.clone(),
1835                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1836
1837                 let pending_events = Mutex::new(VecDeque::new());
1838                 if on_retry {
1839                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1840                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1841                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1842                                 &&keys_manager, 0).unwrap();
1843                         outbound_payments.find_route_and_send_payment(
1844                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1845                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1846                                 &|_| Ok(()));
1847                         let events = pending_events.lock().unwrap();
1848                         assert_eq!(events.len(), 1);
1849                         if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1850                 } else {
1851                         let err = outbound_payments.send_payment(
1852                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1853                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1854                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1855                         if let RetryableSendFailure::RouteNotFound = err {
1856                         } else { panic!("Unexpected error"); }
1857                 }
1858         }
1859
1860         #[test]
1861         fn initial_send_payment_path_failed_evs() {
1862                 let outbound_payments = OutboundPayments::new();
1863                 let logger = test_utils::TestLogger::new();
1864                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1865                 let scorer = RwLock::new(test_utils::TestScorer::new());
1866                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1867                 let secp_ctx = Secp256k1::new();
1868                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1869
1870                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1871                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1872                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1873                 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1874                 let failed_scid = 42;
1875                 let route = Route {
1876                         paths: vec![Path { hops: vec![RouteHop {
1877                                 pubkey: receiver_pk,
1878                                 node_features: NodeFeatures::empty(),
1879                                 short_channel_id: failed_scid,
1880                                 channel_features: ChannelFeatures::empty(),
1881                                 fee_msat: 0,
1882                                 cltv_expiry_delta: 0,
1883                                 maybe_announced_channel: true,
1884                         }], blinded_tail: None }],
1885                         route_params: Some(route_params.clone()),
1886                 };
1887                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1888                 let mut route_params_w_failed_scid = route_params.clone();
1889                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1890                 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1891                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1892                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1893
1894                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1895                 // PaymentPathFailed event.
1896                 let pending_events = Mutex::new(VecDeque::new());
1897                 outbound_payments.send_payment(
1898                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1899                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1900                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1901                         |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1902                 let mut events = pending_events.lock().unwrap();
1903                 assert_eq!(events.len(), 2);
1904                 if let Event::PaymentPathFailed {
1905                         short_channel_id,
1906                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1907                 {
1908                         assert_eq!(short_channel_id, Some(failed_scid));
1909                 } else { panic!("Unexpected event"); }
1910                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1911                 events.clear();
1912                 core::mem::drop(events);
1913
1914                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1915                 outbound_payments.send_payment(
1916                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1917                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1918                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1919                         |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1920                 assert_eq!(pending_events.lock().unwrap().len(), 0);
1921
1922                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1923                 outbound_payments.send_payment(
1924                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1925                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1926                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1927                         |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1928                 let events = pending_events.lock().unwrap();
1929                 assert_eq!(events.len(), 2);
1930                 if let Event::PaymentPathFailed {
1931                         short_channel_id,
1932                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1933                 {
1934                         assert_eq!(short_channel_id, None);
1935                 } else { panic!("Unexpected event"); }
1936                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1937         }
1938
1939         #[test]
1940         fn removes_stale_awaiting_invoice() {
1941                 let pending_events = Mutex::new(VecDeque::new());
1942                 let outbound_payments = OutboundPayments::new();
1943                 let payment_id = PaymentId([0; 32]);
1944
1945                 assert!(!outbound_payments.has_pending_payments());
1946                 assert!(
1947                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
1948                 );
1949                 assert!(outbound_payments.has_pending_payments());
1950
1951                 for _ in 0..INVOICE_REQUEST_TIMEOUT_TICKS {
1952                         outbound_payments.remove_stale_payments(&pending_events);
1953                         assert!(outbound_payments.has_pending_payments());
1954                         assert!(pending_events.lock().unwrap().is_empty());
1955                 }
1956
1957                 outbound_payments.remove_stale_payments(&pending_events);
1958                 assert!(!outbound_payments.has_pending_payments());
1959                 assert!(!pending_events.lock().unwrap().is_empty());
1960                 assert_eq!(
1961                         pending_events.lock().unwrap().pop_front(),
1962                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
1963                 );
1964                 assert!(pending_events.lock().unwrap().is_empty());
1965
1966                 assert!(
1967                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
1968                 );
1969                 assert!(outbound_payments.has_pending_payments());
1970
1971                 assert!(
1972                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None)
1973                                 .is_err()
1974                 );
1975         }
1976
1977         #[test]
1978         fn removes_abandoned_awaiting_invoice() {
1979                 let pending_events = Mutex::new(VecDeque::new());
1980                 let outbound_payments = OutboundPayments::new();
1981                 let payment_id = PaymentId([0; 32]);
1982
1983                 assert!(!outbound_payments.has_pending_payments());
1984                 assert!(
1985                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
1986                 );
1987                 assert!(outbound_payments.has_pending_payments());
1988
1989                 outbound_payments.abandon_payment(
1990                         payment_id, PaymentFailureReason::UserAbandoned, &pending_events
1991                 );
1992                 assert!(!outbound_payments.has_pending_payments());
1993                 assert!(!pending_events.lock().unwrap().is_empty());
1994                 assert_eq!(
1995                         pending_events.lock().unwrap().pop_front(),
1996                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
1997                 );
1998                 assert!(pending_events.lock().unwrap().is_empty());
1999         }
2000
2001         #[cfg(feature = "std")]
2002         #[test]
2003         fn fails_sending_payment_for_expired_bolt12_invoice() {
2004                 let logger = test_utils::TestLogger::new();
2005                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2006                 let scorer = RwLock::new(test_utils::TestScorer::new());
2007                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2008                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2009
2010                 let pending_events = Mutex::new(VecDeque::new());
2011                 let outbound_payments = OutboundPayments::new();
2012                 let payment_id = PaymentId([0; 32]);
2013
2014                 assert!(
2015                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
2016                 );
2017                 assert!(outbound_payments.has_pending_payments());
2018
2019                 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2020                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2021                         .amount_msats(1000)
2022                         .build().unwrap()
2023                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2024                         .build().unwrap()
2025                         .sign(payer_sign).unwrap()
2026                         .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2027                         .build().unwrap()
2028                         .sign(recipient_sign).unwrap();
2029
2030                 assert_eq!(
2031                         outbound_payments.send_payment_for_bolt12_invoice(
2032                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2033                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2034                         ),
2035                         Ok(()),
2036                 );
2037                 assert!(!outbound_payments.has_pending_payments());
2038
2039                 let payment_hash = invoice.payment_hash();
2040                 let reason = Some(PaymentFailureReason::PaymentExpired);
2041
2042                 assert!(!pending_events.lock().unwrap().is_empty());
2043                 assert_eq!(
2044                         pending_events.lock().unwrap().pop_front(),
2045                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2046                 );
2047                 assert!(pending_events.lock().unwrap().is_empty());
2048         }
2049
2050         #[test]
2051         fn fails_finding_route_for_bolt12_invoice() {
2052                 let logger = test_utils::TestLogger::new();
2053                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2054                 let scorer = RwLock::new(test_utils::TestScorer::new());
2055                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2056                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2057
2058                 let pending_events = Mutex::new(VecDeque::new());
2059                 let outbound_payments = OutboundPayments::new();
2060                 let payment_id = PaymentId([0; 32]);
2061
2062                 assert!(
2063                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
2064                 );
2065                 assert!(outbound_payments.has_pending_payments());
2066
2067                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2068                         .amount_msats(1000)
2069                         .build().unwrap()
2070                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2071                         .build().unwrap()
2072                         .sign(payer_sign).unwrap()
2073                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2074                         .build().unwrap()
2075                         .sign(recipient_sign).unwrap();
2076
2077                 router.expect_find_route(
2078                         RouteParameters::from_payment_params_and_value(
2079                                 PaymentParameters::from_bolt12_invoice(&invoice),
2080                                 invoice.amount_msats(),
2081                         ),
2082                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2083                 );
2084
2085                 assert_eq!(
2086                         outbound_payments.send_payment_for_bolt12_invoice(
2087                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2088                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2089                         ),
2090                         Ok(()),
2091                 );
2092                 assert!(!outbound_payments.has_pending_payments());
2093
2094                 let payment_hash = invoice.payment_hash();
2095                 let reason = Some(PaymentFailureReason::RouteNotFound);
2096
2097                 assert!(!pending_events.lock().unwrap().is_empty());
2098                 assert_eq!(
2099                         pending_events.lock().unwrap().pop_front(),
2100                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2101                 );
2102                 assert!(pending_events.lock().unwrap().is_empty());
2103         }
2104
2105         #[test]
2106         fn fails_paying_for_bolt12_invoice() {
2107                 let logger = test_utils::TestLogger::new();
2108                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2109                 let scorer = RwLock::new(test_utils::TestScorer::new());
2110                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2111                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2112
2113                 let pending_events = Mutex::new(VecDeque::new());
2114                 let outbound_payments = OutboundPayments::new();
2115                 let payment_id = PaymentId([0; 32]);
2116
2117                 assert!(
2118                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), None).is_ok()
2119                 );
2120                 assert!(outbound_payments.has_pending_payments());
2121
2122                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2123                         .amount_msats(1000)
2124                         .build().unwrap()
2125                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2126                         .build().unwrap()
2127                         .sign(payer_sign).unwrap()
2128                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2129                         .build().unwrap()
2130                         .sign(recipient_sign).unwrap();
2131
2132                 let route_params = RouteParameters::from_payment_params_and_value(
2133                         PaymentParameters::from_bolt12_invoice(&invoice),
2134                         invoice.amount_msats(),
2135                 );
2136                 router.expect_find_route(
2137                         route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2138                 );
2139
2140                 assert_eq!(
2141                         outbound_payments.send_payment_for_bolt12_invoice(
2142                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2143                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2144                         ),
2145                         Ok(()),
2146                 );
2147                 assert!(!outbound_payments.has_pending_payments());
2148
2149                 let payment_hash = invoice.payment_hash();
2150                 let reason = Some(PaymentFailureReason::UnexpectedError);
2151
2152                 assert!(!pending_events.lock().unwrap().is_empty());
2153                 assert_eq!(
2154                         pending_events.lock().unwrap().pop_front(),
2155                         Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2156                 );
2157                 assert!(pending_events.lock().unwrap().is_empty());
2158         }
2159
2160         #[test]
2161         fn sends_payment_for_bolt12_invoice() {
2162                 let logger = test_utils::TestLogger::new();
2163                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2164                 let scorer = RwLock::new(test_utils::TestScorer::new());
2165                 let router = test_utils::TestRouter::new(network_graph, &scorer);
2166                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2167
2168                 let pending_events = Mutex::new(VecDeque::new());
2169                 let outbound_payments = OutboundPayments::new();
2170                 let payment_id = PaymentId([0; 32]);
2171
2172                 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2173                         .amount_msats(1000)
2174                         .build().unwrap()
2175                         .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2176                         .build().unwrap()
2177                         .sign(payer_sign).unwrap()
2178                         .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2179                         .build().unwrap()
2180                         .sign(recipient_sign).unwrap();
2181
2182                 let route_params = RouteParameters {
2183                         payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2184                         final_value_msat: invoice.amount_msats(),
2185                         max_total_routing_fee_msat: Some(1234),
2186                 };
2187                 router.expect_find_route(
2188                         route_params.clone(),
2189                         Ok(Route {
2190                                 paths: vec![
2191                                         Path {
2192                                                 hops: vec![
2193                                                         RouteHop {
2194                                                                 pubkey: recipient_pubkey(),
2195                                                                 node_features: NodeFeatures::empty(),
2196                                                                 short_channel_id: 42,
2197                                                                 channel_features: ChannelFeatures::empty(),
2198                                                                 fee_msat: invoice.amount_msats(),
2199                                                                 cltv_expiry_delta: 0,
2200                                                                 maybe_announced_channel: true,
2201                                                         }
2202                                                 ],
2203                                                 blinded_tail: None,
2204                                         }
2205                                 ],
2206                                 route_params: Some(route_params),
2207                         })
2208                 );
2209
2210                 assert!(!outbound_payments.has_pending_payments());
2211                 assert_eq!(
2212                         outbound_payments.send_payment_for_bolt12_invoice(
2213                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2214                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2215                         ),
2216                         Err(Bolt12PaymentError::UnexpectedInvoice),
2217                 );
2218                 assert!(!outbound_payments.has_pending_payments());
2219                 assert!(pending_events.lock().unwrap().is_empty());
2220
2221                 assert!(
2222                         outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0), Some(1234)).is_ok()
2223                 );
2224                 assert!(outbound_payments.has_pending_payments());
2225
2226                 assert_eq!(
2227                         outbound_payments.send_payment_for_bolt12_invoice(
2228                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2229                                 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2230                         ),
2231                         Ok(()),
2232                 );
2233                 assert!(outbound_payments.has_pending_payments());
2234                 assert!(pending_events.lock().unwrap().is_empty());
2235
2236                 assert_eq!(
2237                         outbound_payments.send_payment_for_bolt12_invoice(
2238                                 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2239                                 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2240                         ),
2241                         Err(Bolt12PaymentError::DuplicateInvoice),
2242                 );
2243                 assert!(outbound_payments.has_pending_payments());
2244                 assert!(pending_events.lock().unwrap().is_empty());
2245         }
2246 }