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