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