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