cf60c2cf2fa8a0caad592065785187aba276b30d
[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.retry_payment_internal(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 retry_payment_internal<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                 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
843                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
844                 for _ in 0..route.paths.len() {
845                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
846                 }
847
848                 macro_rules! abandon_with_entry {
849                         ($payment: expr, $reason: expr) => {
850                                 $payment.get_mut().mark_abandoned($reason);
851                                 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
852                                         if $payment.get().remaining_parts() == 0 {
853                                                 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
854                                                         payment_id,
855                                                         payment_hash,
856                                                         reason: *reason,
857                                                 }, None));
858                                                 $payment.remove();
859                                         }
860                                 }
861                         }
862                 }
863                 let (total_msat, recipient_onion, keysend_preimage) = {
864                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
865                         match outbounds.entry(payment_id) {
866                                 hash_map::Entry::Occupied(mut payment) => {
867                                         let res = match payment.get() {
868                                                 PendingOutboundPayment::Retryable {
869                                                         total_msat, keysend_preimage, payment_secret, payment_metadata,
870                                                         custom_tlvs, pending_amt_msat, ..
871                                                 } => {
872                                                         let retry_amt_msat = route.get_total_amount();
873                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
874                                                                 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);
875                                                                 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
876                                                                 return
877                                                         }
878                                                         (*total_msat, RecipientOnionFields {
879                                                                         payment_secret: *payment_secret,
880                                                                         payment_metadata: payment_metadata.clone(),
881                                                                         custom_tlvs: custom_tlvs.clone(),
882                                                                 }, *keysend_preimage)
883                                                 },
884                                                 PendingOutboundPayment::Legacy { .. } => {
885                                                         log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
886                                                         return
887                                                 },
888                                                 PendingOutboundPayment::AwaitingInvoice { .. } |
889                                                         PendingOutboundPayment::InvoiceReceived { .. } =>
890                                                 {
891                                                         log_error!(logger, "Payment not yet sent");
892                                                         return
893                                                 },
894                                                 PendingOutboundPayment::Fulfilled { .. } => {
895                                                         log_error!(logger, "Payment already completed");
896                                                         return
897                                                 },
898                                                 PendingOutboundPayment::Abandoned { .. } => {
899                                                         log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
900                                                         return
901                                                 },
902                                         };
903                                         if !payment.get().is_retryable_now() {
904                                                 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
905                                                 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
906                                                 return
907                                         }
908                                         payment.get_mut().increment_attempts();
909                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
910                                                 assert!(payment.get_mut().insert(*session_priv_bytes, path));
911                                         }
912                                         res
913                                 },
914                                 hash_map::Entry::Vacant(_) => {
915                                         log_error!(logger, "Payment with ID {} not found", &payment_id);
916                                         return
917                                 }
918                         }
919                 };
920                 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
921                         payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
922                         &send_payment_along_path);
923                 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
924                 if let Err(e) = res {
925                         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);
926                 }
927         }
928
929         fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
930                 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
931                 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
932                 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
933                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
934         )
935         where
936                 R::Target: Router,
937                 ES::Target: EntropySource,
938                 NS::Target: NodeSigner,
939                 L::Target: Logger,
940                 IH: Fn() -> InFlightHtlcs,
941                 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
942         {
943                 match err {
944                         PaymentSendFailure::AllFailedResendSafe(errs) => {
945                                 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);
946                                 self.retry_payment_internal(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);
947                         },
948                         PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
949                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
950                                 // Some paths were sent, even if we failed to send the full MPP value our recipient may
951                                 // misbehave and claim the funds, at which point we have to consider the payment sent, so
952                                 // return `Ok()` here, ignoring any retry errors.
953                                 self.retry_payment_internal(payment_hash, payment_id, retry, 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: None, .. } => {
956                                 // This may happen if we send a payment and some paths fail, but only due to a temporary
957                                 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
958                                 // initial HTLC-Add messages yet.
959                         },
960                         PaymentSendFailure::PathParameterError(results) => {
961                                 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
962                                 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
963                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
964                         },
965                         PaymentSendFailure::ParameterError(e) => {
966                                 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
967                                 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
968                         },
969                         PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
970                 }
971         }
972
973         fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
974                 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
975                 paths: Vec<Path>, path_results: I, logger: &L,
976                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
977         ) where L::Target: Logger {
978                 let mut events = pending_events.lock().unwrap();
979                 debug_assert_eq!(paths.len(), path_results.len());
980                 for (path, path_res) in paths.into_iter().zip(path_results) {
981                         if let Err(e) = path_res {
982                                 if let APIError::MonitorUpdateInProgress = e { continue }
983                                 log_error!(logger, "Failed to send along path due to error: {:?}", e);
984                                 let mut failed_scid = None;
985                                 if let APIError::ChannelUnavailable { .. } = e {
986                                         let scid = path.hops[0].short_channel_id;
987                                         failed_scid = Some(scid);
988                                         route_params.payment_params.previously_failed_channels.push(scid);
989                                 }
990                                 events.push_back((events::Event::PaymentPathFailed {
991                                         payment_id: Some(payment_id),
992                                         payment_hash,
993                                         payment_failed_permanently: false,
994                                         failure: events::PathFailure::InitialSend { err: e },
995                                         path,
996                                         short_channel_id: failed_scid,
997                                         #[cfg(test)]
998                                         error_code: None,
999                                         #[cfg(test)]
1000                                         error_data: None,
1001                                 }, None));
1002                         }
1003                 }
1004         }
1005
1006         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1007                 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1008                 best_block_height: u32, send_payment_along_path: F
1009         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1010         where
1011                 ES::Target: EntropySource,
1012                 NS::Target: NodeSigner,
1013                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1014         {
1015                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1016
1017                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1018
1019                 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1020                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1021                                 err: "No need probing a path with less than two hops".to_string()
1022                         }))
1023                 }
1024
1025                 let route = Route { paths: vec![path], route_params: None };
1026                 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1027                         RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
1028                         entropy_source, best_block_height)?;
1029
1030                 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1031                         None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1032                 ) {
1033                         Ok(()) => Ok((payment_hash, payment_id)),
1034                         Err(e) => {
1035                                 self.remove_outbound_if_all_failed(payment_id, &e);
1036                                 Err(e)
1037                         }
1038                 }
1039         }
1040
1041         #[cfg(test)]
1042         pub(super) fn test_set_payment_metadata(
1043                 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1044         ) {
1045                 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1046                         PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1047                                 *payment_metadata = new_payment_metadata;
1048                         },
1049                         _ => panic!("Need a retryable payment to update metadata on"),
1050                 }
1051         }
1052
1053         #[cfg(test)]
1054         pub(super) fn test_add_new_pending_payment<ES: Deref>(
1055                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1056                 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1057         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1058                 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1059         }
1060
1061         pub(super) fn add_new_pending_payment<ES: Deref>(
1062                 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1063                 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1064                 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1065         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1066                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1067                 for _ in 0..route.paths.len() {
1068                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
1069                 }
1070
1071                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1072                 match pending_outbounds.entry(payment_id) {
1073                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1074                         hash_map::Entry::Vacant(entry) => {
1075                                 let payment = entry.insert(PendingOutboundPayment::Retryable {
1076                                         retry_strategy,
1077                                         attempts: PaymentAttempts::new(),
1078                                         payment_params,
1079                                         session_privs: HashSet::new(),
1080                                         pending_amt_msat: 0,
1081                                         pending_fee_msat: Some(0),
1082                                         payment_hash,
1083                                         payment_secret: recipient_onion.payment_secret,
1084                                         payment_metadata: recipient_onion.payment_metadata,
1085                                         keysend_preimage,
1086                                         custom_tlvs: recipient_onion.custom_tlvs,
1087                                         starting_block_height: best_block_height,
1088                                         total_msat: route.get_total_amount(),
1089                                 });
1090
1091                                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1092                                         assert!(payment.insert(*session_priv_bytes, path));
1093                                 }
1094
1095                                 Ok(onion_session_privs)
1096                         },
1097                 }
1098         }
1099
1100         #[allow(unused)]
1101         pub(super) fn add_new_awaiting_invoice(&self, payment_id: PaymentId) -> Result<(), ()> {
1102                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1103                 match pending_outbounds.entry(payment_id) {
1104                         hash_map::Entry::Occupied(_) => Err(()),
1105                         hash_map::Entry::Vacant(entry) => {
1106                                 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1107                                         timer_ticks_without_response: 0,
1108                                 });
1109
1110                                 Ok(())
1111                         },
1112                 }
1113         }
1114
1115         fn pay_route_internal<NS: Deref, F>(
1116                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1117                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1118                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1119                 send_payment_along_path: &F
1120         ) -> Result<(), PaymentSendFailure>
1121         where
1122                 NS::Target: NodeSigner,
1123                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1124         {
1125                 if route.paths.len() < 1 {
1126                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1127                 }
1128                 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
1129                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1130                 }
1131                 let mut total_value = 0;
1132                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1133                 let mut path_errs = Vec::with_capacity(route.paths.len());
1134                 'path_check: for path in route.paths.iter() {
1135                         if path.hops.len() < 1 || path.hops.len() > 20 {
1136                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1137                                 continue 'path_check;
1138                         }
1139                         if path.blinded_tail.is_some() {
1140                                 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1141                                 continue 'path_check;
1142                         }
1143                         let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1144                                 usize::max_value() } else { path.hops.len() - 1 };
1145                         for (idx, hop) in path.hops.iter().enumerate() {
1146                                 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1147                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1148                                         continue 'path_check;
1149                                 }
1150                         }
1151                         total_value += path.final_value_msat();
1152                         path_errs.push(Ok(()));
1153                 }
1154                 if path_errs.iter().any(|e| e.is_err()) {
1155                         return Err(PaymentSendFailure::PathParameterError(path_errs));
1156                 }
1157                 if let Some(amt_msat) = recv_value_msat {
1158                         total_value = amt_msat;
1159                 }
1160
1161                 let cur_height = best_block_height + 1;
1162                 let mut results = Vec::new();
1163                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1164                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1165                         let mut path_res = send_payment_along_path(SendAlongPathArgs {
1166                                 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1167                                 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1168                         });
1169                         match path_res {
1170                                 Ok(_) => {},
1171                                 Err(APIError::MonitorUpdateInProgress) => {
1172                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
1173                                         // considered "in flight" and we shouldn't remove it from the
1174                                         // PendingOutboundPayment set.
1175                                 },
1176                                 Err(_) => {
1177                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1178                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1179                                                 let removed = payment.remove(&session_priv_bytes, Some(path));
1180                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1181                                         } else {
1182                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
1183                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1184                                         }
1185                                 }
1186                         }
1187                         results.push(path_res);
1188                 }
1189                 let mut has_ok = false;
1190                 let mut has_err = false;
1191                 let mut pending_amt_unsent = 0;
1192                 for (res, path) in results.iter().zip(route.paths.iter()) {
1193                         if res.is_ok() { has_ok = true; }
1194                         if res.is_err() { has_err = true; }
1195                         if let &Err(APIError::MonitorUpdateInProgress) = res {
1196                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1197                                 // PartialFailure.
1198                                 has_err = true;
1199                                 has_ok = true;
1200                         } else if res.is_err() {
1201                                 pending_amt_unsent += path.final_value_msat();
1202                         }
1203                 }
1204                 if has_err && has_ok {
1205                         Err(PaymentSendFailure::PartialFailure {
1206                                 results,
1207                                 payment_id,
1208                                 failed_paths_retry: if pending_amt_unsent != 0 {
1209                                         if let Some(payment_params) = route.route_params.as_ref().map(|p| p.payment_params.clone()) {
1210                                                 Some(RouteParameters {
1211                                                         payment_params: payment_params,
1212                                                         final_value_msat: pending_amt_unsent,
1213                                                 })
1214                                         } else { None }
1215                                 } else { None },
1216                         })
1217                 } else if has_err {
1218                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1219                 } else {
1220                         Ok(())
1221                 }
1222         }
1223
1224         #[cfg(test)]
1225         pub(super) fn test_send_payment_internal<NS: Deref, F>(
1226                 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1227                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1228                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1229                 send_payment_along_path: F
1230         ) -> Result<(), PaymentSendFailure>
1231         where
1232                 NS::Target: NodeSigner,
1233                 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1234         {
1235                 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1236                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
1237                         &send_payment_along_path)
1238                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1239         }
1240
1241         // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1242         // map as the payment is free to be resent.
1243         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1244                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1245                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1246                         debug_assert!(removed, "We should always have a pending payment to remove here");
1247                 }
1248         }
1249
1250         pub(super) fn claim_htlc<L: Deref>(
1251                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1252                 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1253                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1254                 logger: &L,
1255         ) where L::Target: Logger {
1256                 let mut session_priv_bytes = [0; 32];
1257                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1258                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1259                 let mut pending_events = pending_events.lock().unwrap();
1260                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1261                         if !payment.get().is_fulfilled() {
1262                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1263                                 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1264                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
1265                                 pending_events.push_back((events::Event::PaymentSent {
1266                                         payment_id: Some(payment_id),
1267                                         payment_preimage,
1268                                         payment_hash,
1269                                         fee_paid_msat,
1270                                 }, Some(ev_completion_action.clone())));
1271                                 payment.get_mut().mark_fulfilled();
1272                         }
1273
1274                         if from_onchain {
1275                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
1276                                 // This could potentially lead to removing a pending payment too early,
1277                                 // with a reorg of one block causing us to re-add the fulfilled payment on
1278                                 // restart.
1279                                 // TODO: We should have a second monitor event that informs us of payments
1280                                 // irrevocably fulfilled.
1281                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1282                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1283                                         pending_events.push_back((events::Event::PaymentPathSuccessful {
1284                                                 payment_id,
1285                                                 payment_hash,
1286                                                 path,
1287                                         }, Some(ev_completion_action)));
1288                                 }
1289                         }
1290                 } else {
1291                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1292                 }
1293         }
1294
1295         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1296                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1297         {
1298                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1299                 let mut pending_events = pending_events.lock().unwrap();
1300                 for source in sources {
1301                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1302                                 let mut session_priv_bytes = [0; 32];
1303                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1304                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1305                                         assert!(payment.get().is_fulfilled());
1306                                         if payment.get_mut().remove(&session_priv_bytes, None) {
1307                                                 let payment_hash = payment.get().payment_hash();
1308                                                 debug_assert!(payment_hash.is_some());
1309                                                 pending_events.push_back((events::Event::PaymentPathSuccessful {
1310                                                         payment_id,
1311                                                         payment_hash,
1312                                                         path,
1313                                                 }, None));
1314                                         }
1315                                 }
1316                         }
1317                 }
1318         }
1319
1320         pub(super) fn remove_stale_payments(
1321                 &self, pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1322         {
1323                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1324                 let mut pending_events = pending_events.lock().unwrap();
1325                 pending_outbound_payments.retain(|payment_id, payment| {
1326                         // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1327                         // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1328                         // this could race the user making a duplicate send_payment call and our idempotency
1329                         // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1330                         // removal. This should be more than sufficient to ensure the idempotency of any
1331                         // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1332                         // processed.
1333                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1334                                 let mut no_remaining_entries = session_privs.is_empty();
1335                                 if no_remaining_entries {
1336                                         for (ev, _) in pending_events.iter() {
1337                                                 match ev {
1338                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1339                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1340                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1341                                                                         if payment_id == ev_payment_id {
1342                                                                                 no_remaining_entries = false;
1343                                                                                 break;
1344                                                                         }
1345                                                                 },
1346                                                         _ => {},
1347                                                 }
1348                                         }
1349                                 }
1350                                 if no_remaining_entries {
1351                                         *timer_ticks_without_htlcs += 1;
1352                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1353                                 } else {
1354                                         *timer_ticks_without_htlcs = 0;
1355                                         true
1356                                 }
1357                         } else if let PendingOutboundPayment::AwaitingInvoice { timer_ticks_without_response, .. } = payment {
1358                                 *timer_ticks_without_response += 1;
1359                                 if *timer_ticks_without_response <= INVOICE_REQUEST_TIMEOUT_TICKS {
1360                                         true
1361                                 } else {
1362                                         pending_events.push_back(
1363                                                 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1364                                         );
1365                                         false
1366                                 }
1367                         } else { true }
1368                 });
1369         }
1370
1371         // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1372         pub(super) fn fail_htlc<L: Deref>(
1373                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1374                 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1375                 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1376                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1377         ) -> bool where L::Target: Logger {
1378                 #[cfg(test)]
1379                 let DecodedOnionFailure {
1380                         network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data
1381                 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1382                 #[cfg(not(test))]
1383                 let DecodedOnionFailure { network_update, short_channel_id, payment_retryable } =
1384                         onion_error.decode_onion_failure(secp_ctx, logger, &source);
1385
1386                 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1387                 let mut session_priv_bytes = [0; 32];
1388                 session_priv_bytes.copy_from_slice(&session_priv[..]);
1389                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1390
1391                 // If any payments already need retry, there's no need to generate a redundant
1392                 // `PendingHTLCsForwardable`.
1393                 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1394                         let mut awaiting_retry = false;
1395                         if pmt.is_auto_retryable_now() {
1396                                 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1397                                         if pending_amt_msat < total_msat {
1398                                                 awaiting_retry = true;
1399                                         }
1400                                 }
1401                         }
1402                         awaiting_retry
1403                 });
1404
1405                 let mut full_failure_ev = None;
1406                 let mut pending_retry_ev = false;
1407                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1408                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1409                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1410                                 return false
1411                         }
1412                         if payment.get().is_fulfilled() {
1413                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1414                                 return false
1415                         }
1416                         let mut is_retryable_now = payment.get().is_auto_retryable_now();
1417                         if let Some(scid) = short_channel_id {
1418                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1419                                 // process_onion_failure we should close that channel as it implies our
1420                                 // next-hop is needlessly blaming us!
1421                                 payment.get_mut().insert_previously_failed_scid(scid);
1422                         }
1423
1424                         if payment_is_probe || !is_retryable_now || !payment_retryable {
1425                                 let reason = if !payment_retryable {
1426                                         PaymentFailureReason::RecipientRejected
1427                                 } else {
1428                                         PaymentFailureReason::RetriesExhausted
1429                                 };
1430                                 payment.get_mut().mark_abandoned(reason);
1431                                 is_retryable_now = false;
1432                         }
1433                         if payment.get().remaining_parts() == 0 {
1434                                 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1435                                         if !payment_is_probe {
1436                                                 full_failure_ev = Some(events::Event::PaymentFailed {
1437                                                         payment_id: *payment_id,
1438                                                         payment_hash: *payment_hash,
1439                                                         reason: *reason,
1440                                                 });
1441                                         }
1442                                         payment.remove();
1443                                 }
1444                         }
1445                         is_retryable_now
1446                 } else {
1447                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1448                         return false
1449                 };
1450                 core::mem::drop(outbounds);
1451                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1452
1453                 let path_failure = {
1454                         if payment_is_probe {
1455                                 if !payment_retryable {
1456                                         events::Event::ProbeSuccessful {
1457                                                 payment_id: *payment_id,
1458                                                 payment_hash: payment_hash.clone(),
1459                                                 path: path.clone(),
1460                                         }
1461                                 } else {
1462                                         events::Event::ProbeFailed {
1463                                                 payment_id: *payment_id,
1464                                                 payment_hash: payment_hash.clone(),
1465                                                 path: path.clone(),
1466                                                 short_channel_id,
1467                                         }
1468                                 }
1469                         } else {
1470                                 // If we miss abandoning the payment above, we *must* generate an event here or else the
1471                                 // payment will sit in our outbounds forever.
1472                                 if attempts_remaining && !already_awaiting_retry {
1473                                         debug_assert!(full_failure_ev.is_none());
1474                                         pending_retry_ev = true;
1475                                 }
1476                                 events::Event::PaymentPathFailed {
1477                                         payment_id: Some(*payment_id),
1478                                         payment_hash: payment_hash.clone(),
1479                                         payment_failed_permanently: !payment_retryable,
1480                                         failure: events::PathFailure::OnPath { network_update },
1481                                         path: path.clone(),
1482                                         short_channel_id,
1483                                         #[cfg(test)]
1484                                         error_code: onion_error_code,
1485                                         #[cfg(test)]
1486                                         error_data: onion_error_data
1487                                 }
1488                         }
1489                 };
1490                 let mut pending_events = pending_events.lock().unwrap();
1491                 pending_events.push_back((path_failure, None));
1492                 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1493                 pending_retry_ev
1494         }
1495
1496         pub(super) fn abandon_payment(
1497                 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1498                 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1499         ) {
1500                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1501                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1502                         payment.get_mut().mark_abandoned(reason);
1503                         if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1504                                 if payment.get().remaining_parts() == 0 {
1505                                         pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1506                                                 payment_id,
1507                                                 payment_hash: *payment_hash,
1508                                                 reason: *reason,
1509                                         }, None));
1510                                         payment.remove();
1511                                 }
1512                         } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1513                                 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1514                                         payment_id,
1515                                 }, None));
1516                                 payment.remove();
1517                         }
1518                 }
1519         }
1520
1521         #[cfg(test)]
1522         pub fn has_pending_payments(&self) -> bool {
1523                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1524         }
1525
1526         #[cfg(test)]
1527         pub fn clear_pending_payments(&self) {
1528                 self.pending_outbound_payments.lock().unwrap().clear()
1529         }
1530 }
1531
1532 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1533 /// payment probe.
1534 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1535         probing_cookie_secret: [u8; 32]) -> bool
1536 {
1537         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1538         target_payment_hash == *payment_hash
1539 }
1540
1541 /// Returns the 'probing cookie' for the given [`PaymentId`].
1542 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1543         let mut preimage = [0u8; 64];
1544         preimage[..32].copy_from_slice(&probing_cookie_secret);
1545         preimage[32..].copy_from_slice(&payment_id.0);
1546         PaymentHash(Sha256::hash(&preimage).into_inner())
1547 }
1548
1549 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1550         (0, Legacy) => {
1551                 (0, session_privs, required),
1552         },
1553         (1, Fulfilled) => {
1554                 (0, session_privs, required),
1555                 (1, payment_hash, option),
1556                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1557         },
1558         (2, Retryable) => {
1559                 (0, session_privs, required),
1560                 (1, pending_fee_msat, option),
1561                 (2, payment_hash, required),
1562                 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1563                 // never see it - `payment_params` was added here after the field was added/required.
1564                 (3, payment_params, (option: ReadableArgs, 0)),
1565                 (4, payment_secret, option),
1566                 (5, keysend_preimage, option),
1567                 (6, total_msat, required),
1568                 (7, payment_metadata, option),
1569                 (8, pending_amt_msat, required),
1570                 (9, custom_tlvs, optional_vec),
1571                 (10, starting_block_height, required),
1572                 (not_written, retry_strategy, (static_value, None)),
1573                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1574         },
1575         (3, Abandoned) => {
1576                 (0, session_privs, required),
1577                 (1, reason, option),
1578                 (2, payment_hash, required),
1579         },
1580         (5, AwaitingInvoice) => {
1581                 (0, timer_ticks_without_response, required),
1582         },
1583         (7, InvoiceReceived) => {
1584                 (0, payment_hash, required),
1585         },
1586 );
1587
1588 #[cfg(test)]
1589 mod tests {
1590         use bitcoin::network::constants::Network;
1591         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1592
1593         use crate::events::{Event, PathFailure, PaymentFailureReason};
1594         use crate::ln::PaymentHash;
1595         use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1596         use crate::ln::features::{ChannelFeatures, NodeFeatures};
1597         use crate::ln::msgs::{ErrorAction, LightningError};
1598         use crate::ln::outbound_payment::{INVOICE_REQUEST_TIMEOUT_TICKS, OutboundPayments, Retry, RetryableSendFailure};
1599         use crate::routing::gossip::NetworkGraph;
1600         use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1601         use crate::sync::{Arc, Mutex, RwLock};
1602         use crate::util::errors::APIError;
1603         use crate::util::test_utils;
1604
1605         use alloc::collections::VecDeque;
1606
1607         #[test]
1608         fn test_recipient_onion_fields_with_custom_tlvs() {
1609                 let onion_fields = RecipientOnionFields::spontaneous_empty();
1610
1611                 let bad_type_range_tlvs = vec![
1612                         (0, vec![42]),
1613                         (1, vec![42; 32]),
1614                 ];
1615                 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1616
1617                 let keysend_tlv = vec![
1618                         (5482373484, vec![42; 32]),
1619                 ];
1620                 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1621
1622                 let good_tlvs = vec![
1623                         ((1 << 16) + 1, vec![42]),
1624                         ((1 << 16) + 3, vec![42; 32]),
1625                 ];
1626                 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1627         }
1628
1629         #[test]
1630         #[cfg(feature = "std")]
1631         fn fails_paying_after_expiration() {
1632                 do_fails_paying_after_expiration(false);
1633                 do_fails_paying_after_expiration(true);
1634         }
1635         #[cfg(feature = "std")]
1636         fn do_fails_paying_after_expiration(on_retry: bool) {
1637                 let outbound_payments = OutboundPayments::new();
1638                 let logger = test_utils::TestLogger::new();
1639                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1640                 let scorer = RwLock::new(test_utils::TestScorer::new());
1641                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1642                 let secp_ctx = Secp256k1::new();
1643                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1644
1645                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1646                 let payment_params = PaymentParameters::from_node_id(
1647                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1648                                 0
1649                         ).with_expiry_time(past_expiry_time);
1650                 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1651                 let pending_events = Mutex::new(VecDeque::new());
1652                 if on_retry {
1653                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1654                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1655                                 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1656                                 &&keys_manager, 0).unwrap();
1657                         outbound_payments.retry_payment_internal(
1658                                 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1659                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1660                                 &|_| Ok(()));
1661                         let events = pending_events.lock().unwrap();
1662                         assert_eq!(events.len(), 1);
1663                         if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1664                                 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1665                         } else { panic!("Unexpected event"); }
1666                 } else {
1667                         let err = outbound_payments.send_payment(
1668                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1669                                 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1670                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1671                         if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1672                 }
1673         }
1674
1675         #[test]
1676         fn find_route_error() {
1677                 do_find_route_error(false);
1678                 do_find_route_error(true);
1679         }
1680         fn do_find_route_error(on_retry: bool) {
1681                 let outbound_payments = OutboundPayments::new();
1682                 let logger = test_utils::TestLogger::new();
1683                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1684                 let scorer = RwLock::new(test_utils::TestScorer::new());
1685                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1686                 let secp_ctx = Secp256k1::new();
1687                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1688
1689                 let payment_params = PaymentParameters::from_node_id(
1690                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1691                 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1692                 router.expect_find_route(route_params.clone(),
1693                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1694
1695                 let pending_events = Mutex::new(VecDeque::new());
1696                 if on_retry {
1697                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1698                                 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1699                                 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1700                                 &&keys_manager, 0).unwrap();
1701                         outbound_payments.retry_payment_internal(
1702                                 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1703                                 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1704                                 &|_| Ok(()));
1705                         let events = pending_events.lock().unwrap();
1706                         assert_eq!(events.len(), 1);
1707                         if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1708                 } else {
1709                         let err = outbound_payments.send_payment(
1710                                 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1711                                 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1712                                 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1713                         if let RetryableSendFailure::RouteNotFound = err {
1714                         } else { panic!("Unexpected error"); }
1715                 }
1716         }
1717
1718         #[test]
1719         fn initial_send_payment_path_failed_evs() {
1720                 let outbound_payments = OutboundPayments::new();
1721                 let logger = test_utils::TestLogger::new();
1722                 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1723                 let scorer = RwLock::new(test_utils::TestScorer::new());
1724                 let router = test_utils::TestRouter::new(network_graph, &scorer);
1725                 let secp_ctx = Secp256k1::new();
1726                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1727
1728                 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1729                 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1730                 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1731                 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1732                 let failed_scid = 42;
1733                 let route = Route {
1734                         paths: vec![Path { hops: vec![RouteHop {
1735                                 pubkey: receiver_pk,
1736                                 node_features: NodeFeatures::empty(),
1737                                 short_channel_id: failed_scid,
1738                                 channel_features: ChannelFeatures::empty(),
1739                                 fee_msat: 0,
1740                                 cltv_expiry_delta: 0,
1741                         }], blinded_tail: None }],
1742                         route_params: Some(route_params.clone()),
1743                 };
1744                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1745                 let mut route_params_w_failed_scid = route_params.clone();
1746                 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1747                 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1748                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1749                 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1750
1751                 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1752                 // PaymentPathFailed event.
1753                 let pending_events = Mutex::new(VecDeque::new());
1754                 outbound_payments.send_payment(
1755                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1756                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1757                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1758                         |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1759                 let mut events = pending_events.lock().unwrap();
1760                 assert_eq!(events.len(), 2);
1761                 if let Event::PaymentPathFailed {
1762                         short_channel_id,
1763                         failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1764                 {
1765                         assert_eq!(short_channel_id, Some(failed_scid));
1766                 } else { panic!("Unexpected event"); }
1767                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1768                 events.clear();
1769                 core::mem::drop(events);
1770
1771                 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1772                 outbound_payments.send_payment(
1773                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1774                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1775                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1776                         |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1777                 assert_eq!(pending_events.lock().unwrap().len(), 0);
1778
1779                 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1780                 outbound_payments.send_payment(
1781                         PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1782                         Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1783                         &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1784                         |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1785                 let events = pending_events.lock().unwrap();
1786                 assert_eq!(events.len(), 2);
1787                 if let Event::PaymentPathFailed {
1788                         short_channel_id,
1789                         failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1790                 {
1791                         assert_eq!(short_channel_id, None);
1792                 } else { panic!("Unexpected event"); }
1793                 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1794         }
1795
1796         #[test]
1797         fn removes_stale_awaiting_invoice() {
1798                 let pending_events = Mutex::new(VecDeque::new());
1799                 let outbound_payments = OutboundPayments::new();
1800                 let payment_id = PaymentId([0; 32]);
1801
1802                 assert!(!outbound_payments.has_pending_payments());
1803                 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1804                 assert!(outbound_payments.has_pending_payments());
1805
1806                 for _ in 0..INVOICE_REQUEST_TIMEOUT_TICKS {
1807                         outbound_payments.remove_stale_payments(&pending_events);
1808                         assert!(outbound_payments.has_pending_payments());
1809                         assert!(pending_events.lock().unwrap().is_empty());
1810                 }
1811
1812                 outbound_payments.remove_stale_payments(&pending_events);
1813                 assert!(!outbound_payments.has_pending_payments());
1814                 assert!(!pending_events.lock().unwrap().is_empty());
1815                 assert_eq!(
1816                         pending_events.lock().unwrap().pop_front(),
1817                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
1818                 );
1819                 assert!(pending_events.lock().unwrap().is_empty());
1820
1821                 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1822                 assert!(outbound_payments.has_pending_payments());
1823
1824                 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_err());
1825         }
1826
1827         #[test]
1828         fn removes_abandoned_awaiting_invoice() {
1829                 let pending_events = Mutex::new(VecDeque::new());
1830                 let outbound_payments = OutboundPayments::new();
1831                 let payment_id = PaymentId([0; 32]);
1832
1833                 assert!(!outbound_payments.has_pending_payments());
1834                 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1835                 assert!(outbound_payments.has_pending_payments());
1836
1837                 outbound_payments.abandon_payment(
1838                         payment_id, PaymentFailureReason::UserAbandoned, &pending_events
1839                 );
1840                 assert!(!outbound_payments.has_pending_payments());
1841                 assert!(!pending_events.lock().unwrap().is_empty());
1842                 assert_eq!(
1843                         pending_events.lock().unwrap().pop_front(),
1844                         Some((Event::InvoiceRequestFailed { payment_id }, None)),
1845                 );
1846                 assert!(pending_events.lock().unwrap().is_empty());
1847         }
1848 }