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