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