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