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