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