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