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