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