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