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