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