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