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