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