Move retry-limiting to `retry_payment_with_route`
[rust-lightning] / lightning / src / ln / outbound_payment.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Utilities to send payments and manage outbound payment information.
11
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
15
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
18 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, MIN_HTLC_RELAY_HOLDING_CELL_MILLIS, PaymentId};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
22 use crate::util::errors::APIError;
23 use crate::util::events;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(not(feature = "no-std"), test))]
27 use crate::util::time::tests::SinceEpoch;
28
29 use core::cmp;
30 use core::fmt::{self, Display, Formatter};
31 use core::ops::Deref;
32 use core::time::Duration;
33
34 use crate::prelude::*;
35 use crate::sync::Mutex;
36
37 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
38 /// and later, also stores information for retrying the payment.
39 pub(crate) enum PendingOutboundPayment {
40         Legacy {
41                 session_privs: HashSet<[u8; 32]>,
42         },
43         Retryable {
44                 retry_strategy: Option<Retry>,
45                 attempts: PaymentAttempts,
46                 route_params: Option<RouteParameters>,
47                 session_privs: HashSet<[u8; 32]>,
48                 payment_hash: PaymentHash,
49                 payment_secret: Option<PaymentSecret>,
50                 pending_amt_msat: u64,
51                 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
52                 pending_fee_msat: Option<u64>,
53                 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
54                 total_msat: u64,
55                 /// Our best known block height at the time this payment was initiated.
56                 starting_block_height: u32,
57         },
58         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
59         /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
60         /// and add a pending payment that was already fulfilled.
61         Fulfilled {
62                 session_privs: HashSet<[u8; 32]>,
63                 payment_hash: Option<PaymentHash>,
64                 timer_ticks_without_htlcs: u8,
65         },
66         /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
67         /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
68         /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
69         /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
70         /// downstream event handler as to when a payment has actually failed.
71         ///
72         /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
73         Abandoned {
74                 session_privs: HashSet<[u8; 32]>,
75                 payment_hash: PaymentHash,
76         },
77 }
78
79 impl PendingOutboundPayment {
80         fn increment_attempts(&mut self) {
81                 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
82                         attempts.count += 1;
83                 }
84         }
85         fn is_auto_retryable_now(&self) -> bool {
86                 match self {
87                         PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
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 { route_params: Some(params), .. } = self {
107                         params.payment_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) -> Result<(), ()> {
152                 let mut session_privs = HashSet::new();
153                 let our_payment_hash;
154                 core::mem::swap(&mut session_privs, match self {
155                         PendingOutboundPayment::Legacy { .. } |
156                                 PendingOutboundPayment::Fulfilled { .. } =>
157                                 return Err(()),
158                                 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
159                                         PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
160                                                 our_payment_hash = *payment_hash;
161                                                 session_privs
162                                         },
163                 });
164                 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
165                 Ok(())
166         }
167
168         /// panics if path is None and !self.is_fulfilled
169         fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
170                 let remove_res = match self {
171                         PendingOutboundPayment::Legacy { session_privs } |
172                                 PendingOutboundPayment::Retryable { session_privs, .. } |
173                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
174                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
175                                         session_privs.remove(session_priv)
176                                 }
177                 };
178                 if remove_res {
179                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
180                                 let path = path.expect("Fulfilling a payment should always come with a path");
181                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
182                                 *pending_amt_msat -= path_last_hop.fee_msat;
183                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
184                                         *fee_msat -= path.get_path_fees();
185                                 }
186                         }
187                 }
188                 remove_res
189         }
190
191         pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
192                 let insert_res = match self {
193                         PendingOutboundPayment::Legacy { session_privs } |
194                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
195                                         session_privs.insert(session_priv)
196                                 }
197                         PendingOutboundPayment::Fulfilled { .. } => false,
198                         PendingOutboundPayment::Abandoned { .. } => false,
199                 };
200                 if insert_res {
201                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
202                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
203                                 *pending_amt_msat += path_last_hop.fee_msat;
204                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
205                                         *fee_msat += path.get_path_fees();
206                                 }
207                         }
208                 }
209                 insert_res
210         }
211
212         pub(super) fn remaining_parts(&self) -> usize {
213                 match self {
214                         PendingOutboundPayment::Legacy { session_privs } |
215                                 PendingOutboundPayment::Retryable { session_privs, .. } |
216                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
217                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
218                                         session_privs.len()
219                                 }
220                 }
221         }
222 }
223
224 /// Strategies available to retry payment path failures.
225 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
226 pub enum Retry {
227         /// Max number of attempts to retry payment.
228         ///
229         /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
230         /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
231         /// were retried along a route from a single call to [`Router::find_route`].
232         Attempts(usize),
233         #[cfg(not(feature = "no-std"))]
234         /// Time elapsed before abandoning retries for a payment.
235         Timeout(core::time::Duration),
236 }
237
238 impl Retry {
239         pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
240                 match (self, attempts) {
241                         (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
242                                 max_retry_count > count
243                         },
244                         #[cfg(all(not(feature = "no-std"), not(test)))]
245                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
246                                 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
247                         #[cfg(all(not(feature = "no-std"), test))]
248                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
249                                 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
250                 }
251         }
252 }
253
254 #[cfg(feature = "std")]
255 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
256         if let Some(expiry_time) = route_params.payment_params.expiry_time {
257                 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
258                         return elapsed > core::time::Duration::from_secs(expiry_time)
259                 }
260         }
261         false
262 }
263
264 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
265
266 /// Storing minimal payment attempts information required for determining if a outbound payment can
267 /// be retried.
268 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
269         /// This count will be incremented only after the result of the attempt is known. When it's 0,
270         /// it means the result of the first attempt is not known yet.
271         pub(crate) count: usize,
272         /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
273         first_attempted_at: T
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                         first_attempted_at: T::now()
288                 }
289         }
290 }
291
292 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
293         fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
294                 #[cfg(feature = "no-std")]
295                 return write!(f, "attempts: {}", self.count);
296                 #[cfg(not(feature = "no-std"))]
297                 return write!(
298                         f,
299                         "attempts: {}, duration: {}s",
300                         self.count,
301                         T::now().duration_since(self.first_attempted_at).as_secs()
302                 );
303         }
304 }
305
306 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
307 /// Err() type describing which state the payment is in, see the description of individual enum
308 /// states for more.
309 #[derive(Clone, Debug)]
310 pub enum PaymentSendFailure {
311         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
312         /// send the payment at all.
313         ///
314         /// You can freely resend the payment in full (with the parameter error fixed).
315         ///
316         /// Because the payment failed outright, no payment tracking is done, you do not need to call
317         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
318         /// for this payment.
319         ///
320         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
321         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
322         ParameterError(APIError),
323         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
324         /// from attempting to send the payment at all.
325         ///
326         /// You can freely resend the payment in full (with the parameter error fixed).
327         ///
328         /// The results here are ordered the same as the paths in the route object which was passed to
329         /// send_payment.
330         ///
331         /// Because the payment failed outright, no payment tracking is done, you do not need to call
332         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
333         /// for this payment.
334         ///
335         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
336         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
337         PathParameterError(Vec<Result<(), APIError>>),
338         /// All paths which were attempted failed to send, with no channel state change taking place.
339         /// You can freely resend the payment in full (though you probably want to do so over different
340         /// paths than the ones selected).
341         ///
342         /// Because the payment failed outright, no payment tracking is done, you do not need to call
343         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
344         /// for this payment.
345         ///
346         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
347         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
348         AllFailedResendSafe(Vec<APIError>),
349         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
350         /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
351         /// [`ChannelManager::abandon_payment`]).
352         ///
353         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
354         /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
355         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
356         DuplicatePayment,
357         /// Some paths which were attempted failed to send, though possibly not all. At least some
358         /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
359         /// in over-/re-payment.
360         ///
361         /// The results here are ordered the same as the paths in the route object which was passed to
362         /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
363         /// safely retried via [`ChannelManager::retry_payment`].
364         ///
365         /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
366         /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
367         /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
368         /// the next-hop channel with the latest update_id.
369         ///
370         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
371         /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
372         PartialFailure {
373                 /// The errors themselves, in the same order as the route hops.
374                 results: Vec<Result<(), APIError>>,
375                 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
376                 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
377                 /// will pay all remaining unpaid balance.
378                 failed_paths_retry: Option<RouteParameters>,
379                 /// The payment id for the payment, which is now at least partially pending.
380                 payment_id: PaymentId,
381         },
382 }
383
384 pub(super) struct OutboundPayments {
385         pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
386 }
387
388 impl OutboundPayments {
389         pub(super) fn new() -> Self {
390                 Self {
391                         pending_outbound_payments: Mutex::new(HashMap::new())
392                 }
393         }
394
395         pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, F, L: Deref>(
396                 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
397                 retry_strategy: Retry, route_params: RouteParameters, router: &R,
398                 first_hops: Vec<ChannelDetails>, inflight_htlcs: InFlightHtlcs, entropy_source: &ES,
399                 node_signer: &NS, best_block_height: u32, logger: &L, send_payment_along_path: F,
400         ) -> Result<(), PaymentSendFailure>
401         where
402                 R::Target: Router,
403                 ES::Target: EntropySource,
404                 NS::Target: NodeSigner,
405                 L::Target: Logger,
406                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
407                          u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
408         {
409                 self.pay_internal(payment_id, Some((payment_hash, payment_secret, retry_strategy)),
410                         route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer,
411                         best_block_height, logger, &send_payment_along_path)
412                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
413         }
414
415         pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
416                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
417                 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
418                 send_payment_along_path: F
419         ) -> Result<(), PaymentSendFailure>
420         where
421                 ES::Target: EntropySource,
422                 NS::Target: NodeSigner,
423                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
424                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
425         {
426                 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, None, None, entropy_source, best_block_height)?;
427                 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
428                         onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
429                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
430         }
431
432         pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
433                 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
434                 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
435         ) -> Result<PaymentHash, PaymentSendFailure>
436         where
437                 ES::Target: EntropySource,
438                 NS::Target: NodeSigner,
439                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
440                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
441         {
442                 let preimage = match payment_preimage {
443                         Some(p) => p,
444                         None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
445                 };
446                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
447                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
448
449                 match self.pay_route_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
450                         Ok(()) => Ok(payment_hash),
451                         Err(e) => {
452                                 self.remove_outbound_if_all_failed(payment_id, &e);
453                                 Err(e)
454                         }
455                 }
456         }
457
458         pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
459                 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
460                 best_block_height: u32, logger: &L, send_payment_along_path: SP,
461         )
462         where
463                 R::Target: Router,
464                 ES::Target: EntropySource,
465                 NS::Target: NodeSigner,
466                 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
467                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
468                 IH: Fn() -> InFlightHtlcs,
469                 FH: Fn() -> Vec<ChannelDetails>,
470                 L::Target: Logger,
471         {
472                 loop {
473                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
474                         let mut retry_id_route_params = None;
475                         for (pmt_id, pmt) in outbounds.iter_mut() {
476                                 if pmt.is_auto_retryable_now() {
477                                         if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, route_params: Some(params), .. } = pmt {
478                                                 if pending_amt_msat < total_msat {
479                                                         retry_id_route_params = Some((*pmt_id, params.clone()));
480                                                         break
481                                                 }
482                                         }
483                                 }
484                         }
485                         if let Some((payment_id, route_params)) = retry_id_route_params {
486                                 core::mem::drop(outbounds);
487                                 if let Err(e) = self.pay_internal(payment_id, None, route_params, router, first_hops(), inflight_htlcs(), entropy_source, node_signer, best_block_height, logger, &send_payment_along_path) {
488                                         log_info!(logger, "Errored retrying payment: {:?}", e);
489                                 }
490                         } else { break }
491                 }
492         }
493
494         fn pay_internal<R: Deref, NS: Deref, ES: Deref, F, L: Deref>(
495                 &self, payment_id: PaymentId,
496                 initial_send_info: Option<(PaymentHash, &Option<PaymentSecret>, Retry)>,
497                 route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
498                 inflight_htlcs: InFlightHtlcs, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
499                 logger: &L, send_payment_along_path: &F,
500         ) -> Result<(), PaymentSendFailure>
501         where
502                 R::Target: Router,
503                 ES::Target: EntropySource,
504                 NS::Target: NodeSigner,
505                 L::Target: Logger,
506                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
507                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
508         {
509                 #[cfg(feature = "std")] {
510                         if has_expired(&route_params) {
511                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
512                                         err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
513                                 }))
514                         }
515                 }
516
517                 let route = router.find_route(
518                         &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
519                         Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
520                 ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
521                         err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
522                 }))?;
523
524                 let res = if let Some((payment_hash, payment_secret, retry_strategy)) = initial_send_info {
525                         let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, &route, Some(retry_strategy), Some(route_params.clone()), entropy_source, best_block_height)?;
526                         self.pay_route_internal(&route, payment_hash, payment_secret, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path)
527                 } else {
528                         self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path)
529                 };
530                 match res {
531                         Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
532                                 let retry_res = self.pay_internal(payment_id, None, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
533                                 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
534                                 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = &retry_res {
535                                         if err.starts_with("Retries exhausted ") { return res; }
536                                 }
537                                 retry_res
538                         },
539                         Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), .. }) => {
540                                 // Some paths were sent, even if we failed to send the full MPP value our recipient may
541                                 // misbehave and claim the funds, at which point we have to consider the payment sent, so
542                                 // return `Ok()` here, ignoring any retry errors.
543                                 let retry_res = self.pay_internal(payment_id, None, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
544                                 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
545                                 Ok(())
546                         },
547                         Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
548                                 // This may happen if we send a payment and some paths fail, but only due to a temporary
549                                 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
550                                 // initial HTLC-Add messages yet.
551                                 Ok(())
552                         },
553                         res => res,
554                 }
555         }
556
557         pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
558                 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
559                 send_payment_along_path: F
560         ) -> Result<(), PaymentSendFailure>
561         where
562                 ES::Target: EntropySource,
563                 NS::Target: NodeSigner,
564                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
565                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
566         {
567                 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
568                 for path in route.paths.iter() {
569                         if path.len() == 0 {
570                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
571                                         err: "length-0 path in route".to_string()
572                                 }))
573                         }
574                 }
575
576                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
577                 for _ in 0..route.paths.len() {
578                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
579                 }
580
581                 let (total_msat, payment_hash, payment_secret) = {
582                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
583                         match outbounds.get_mut(&payment_id) {
584                                 Some(payment) => {
585                                         let res = match payment {
586                                                 PendingOutboundPayment::Retryable {
587                                                         total_msat, payment_hash, payment_secret, pending_amt_msat, ..
588                                                 } => {
589                                                         let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
590                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
591                                                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
592                                                                         err: format!("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).to_string()
593                                                                 }))
594                                                         }
595                                                         (*total_msat, *payment_hash, *payment_secret)
596                                                 },
597                                                 PendingOutboundPayment::Legacy { .. } => {
598                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
599                                                                 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
600                                                         }))
601                                                 },
602                                                 PendingOutboundPayment::Fulfilled { .. } => {
603                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
604                                                                 err: "Payment already completed".to_owned()
605                                                         }));
606                                                 },
607                                                 PendingOutboundPayment::Abandoned { .. } => {
608                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
609                                                                 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
610                                                         }));
611                                                 },
612                                         };
613                                         if !payment.is_retryable_now() {
614                                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
615                                                         err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
616                                                 }))
617                                         }
618                                         payment.increment_attempts();
619                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
620                                                 assert!(payment.insert(*session_priv_bytes, path));
621                                         }
622                                         res
623                                 },
624                                 None =>
625                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
626                                                 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
627                                         })),
628                         }
629                 };
630                 self.pay_route_internal(route, payment_hash, &payment_secret, None, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
631         }
632
633         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
634                 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
635                 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
636         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
637         where
638                 ES::Target: EntropySource,
639                 NS::Target: NodeSigner,
640                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
641                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
642         {
643                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
644
645                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
646
647                 if hops.len() < 2 {
648                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
649                                 err: "No need probing a path with less than two hops".to_string()
650                         }))
651                 }
652
653                 let route = Route { paths: vec![hops], payment_params: None };
654                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
655
656                 match self.pay_route_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
657                         Ok(()) => Ok((payment_hash, payment_id)),
658                         Err(e) => {
659                                 self.remove_outbound_if_all_failed(payment_id, &e);
660                                 Err(e)
661                         }
662                 }
663         }
664
665         #[cfg(test)]
666         pub(super) fn test_add_new_pending_payment<ES: Deref>(
667                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
668                 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
669         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
670                 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, retry_strategy, None, entropy_source, best_block_height)
671         }
672
673         pub(super) fn add_new_pending_payment<ES: Deref>(
674                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
675                 route: &Route, retry_strategy: Option<Retry>, route_params: Option<RouteParameters>,
676                 entropy_source: &ES, best_block_height: u32
677         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
678                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
679                 for _ in 0..route.paths.len() {
680                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
681                 }
682
683                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
684                 match pending_outbounds.entry(payment_id) {
685                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
686                         hash_map::Entry::Vacant(entry) => {
687                                 let payment = entry.insert(PendingOutboundPayment::Retryable {
688                                         retry_strategy,
689                                         attempts: PaymentAttempts::new(),
690                                         route_params,
691                                         session_privs: HashSet::new(),
692                                         pending_amt_msat: 0,
693                                         pending_fee_msat: Some(0),
694                                         payment_hash,
695                                         payment_secret,
696                                         starting_block_height: best_block_height,
697                                         total_msat: route.get_total_amount(),
698                                 });
699
700                                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
701                                         assert!(payment.insert(*session_priv_bytes, path));
702                                 }
703
704                                 Ok(onion_session_privs)
705                         },
706                 }
707         }
708
709         fn pay_route_internal<NS: Deref, F>(
710                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
711                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
712                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
713                 send_payment_along_path: &F
714         ) -> Result<(), PaymentSendFailure>
715         where
716                 NS::Target: NodeSigner,
717                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
718                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
719         {
720                 if route.paths.len() < 1 {
721                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
722                 }
723                 if payment_secret.is_none() && route.paths.len() > 1 {
724                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
725                 }
726                 let mut total_value = 0;
727                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
728                 let mut path_errs = Vec::with_capacity(route.paths.len());
729                 'path_check: for path in route.paths.iter() {
730                         if path.len() < 1 || path.len() > 20 {
731                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
732                                 continue 'path_check;
733                         }
734                         for (idx, hop) in path.iter().enumerate() {
735                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
736                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
737                                         continue 'path_check;
738                                 }
739                         }
740                         total_value += path.last().unwrap().fee_msat;
741                         path_errs.push(Ok(()));
742                 }
743                 if path_errs.iter().any(|e| e.is_err()) {
744                         return Err(PaymentSendFailure::PathParameterError(path_errs));
745                 }
746                 if let Some(amt_msat) = recv_value_msat {
747                         debug_assert!(amt_msat >= total_value);
748                         total_value = amt_msat;
749                 }
750
751                 let cur_height = best_block_height + 1;
752                 let mut results = Vec::new();
753                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
754                 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
755                         let mut path_res = send_payment_along_path(&path, &route.payment_params, &payment_hash, payment_secret, total_value, cur_height, payment_id, &keysend_preimage, session_priv);
756                         match path_res {
757                                 Ok(_) => {},
758                                 Err(APIError::MonitorUpdateInProgress) => {
759                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
760                                         // considered "in flight" and we shouldn't remove it from the
761                                         // PendingOutboundPayment set.
762                                 },
763                                 Err(_) => {
764                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
765                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
766                                                 let removed = payment.remove(&session_priv, Some(path));
767                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
768                                         } else {
769                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
770                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
771                                         }
772                                 }
773                         }
774                         results.push(path_res);
775                 }
776                 let mut has_ok = false;
777                 let mut has_err = false;
778                 let mut pending_amt_unsent = 0;
779                 let mut max_unsent_cltv_delta = 0;
780                 for (res, path) in results.iter().zip(route.paths.iter()) {
781                         if res.is_ok() { has_ok = true; }
782                         if res.is_err() { has_err = true; }
783                         if let &Err(APIError::MonitorUpdateInProgress) = res {
784                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
785                                 // PartialFailure.
786                                 has_err = true;
787                                 has_ok = true;
788                         } else if res.is_err() {
789                                 pending_amt_unsent += path.last().unwrap().fee_msat;
790                                 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
791                         }
792                 }
793                 if has_err && has_ok {
794                         Err(PaymentSendFailure::PartialFailure {
795                                 results,
796                                 payment_id,
797                                 failed_paths_retry: if pending_amt_unsent != 0 {
798                                         if let Some(payment_params) = &route.payment_params {
799                                                 Some(RouteParameters {
800                                                         payment_params: payment_params.clone(),
801                                                         final_value_msat: pending_amt_unsent,
802                                                         final_cltv_expiry_delta:
803                                                                 if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
804                                                                 else { max_unsent_cltv_delta },
805                                                 })
806                                         } else { None }
807                                 } else { None },
808                         })
809                 } else if has_err {
810                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
811                 } else {
812                         Ok(())
813                 }
814         }
815
816         #[cfg(test)]
817         pub(super) fn test_send_payment_internal<NS: Deref, F>(
818                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
819                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
820                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
821                 send_payment_along_path: F
822         ) -> Result<(), PaymentSendFailure>
823         where
824                 NS::Target: NodeSigner,
825                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
826                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
827         {
828                 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
829                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
830                         &send_payment_along_path)
831                         .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
832         }
833
834         // If we failed to send any paths, we should remove the new PaymentId from the
835         // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
836         fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
837                 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
838                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
839                         debug_assert!(removed, "We should always have a pending payment to remove here");
840                 }
841         }
842
843         pub(super) fn claim_htlc<L: Deref>(
844                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
845                 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
846         ) where L::Target: Logger {
847                 let mut session_priv_bytes = [0; 32];
848                 session_priv_bytes.copy_from_slice(&session_priv[..]);
849                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
850                 let mut pending_events = pending_events.lock().unwrap();
851                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
852                         if !payment.get().is_fulfilled() {
853                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
854                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
855                                 pending_events.push(
856                                         events::Event::PaymentSent {
857                                                 payment_id: Some(payment_id),
858                                                 payment_preimage,
859                                                 payment_hash,
860                                                 fee_paid_msat,
861                                         }
862                                 );
863                                 payment.get_mut().mark_fulfilled();
864                         }
865
866                         if from_onchain {
867                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
868                                 // This could potentially lead to removing a pending payment too early,
869                                 // with a reorg of one block causing us to re-add the fulfilled payment on
870                                 // restart.
871                                 // TODO: We should have a second monitor event that informs us of payments
872                                 // irrevocably fulfilled.
873                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
874                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
875                                         pending_events.push(
876                                                 events::Event::PaymentPathSuccessful {
877                                                         payment_id,
878                                                         payment_hash,
879                                                         path,
880                                                 }
881                                         );
882                                 }
883                         }
884                 } else {
885                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
886                 }
887         }
888
889         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
890                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
891                 let mut pending_events = pending_events.lock().unwrap();
892                 for source in sources {
893                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
894                                 let mut session_priv_bytes = [0; 32];
895                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
896                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
897                                         assert!(payment.get().is_fulfilled());
898                                         if payment.get_mut().remove(&session_priv_bytes, None) {
899                                                 pending_events.push(
900                                                         events::Event::PaymentPathSuccessful {
901                                                                 payment_id,
902                                                                 payment_hash: payment.get().payment_hash(),
903                                                                 path,
904                                                         }
905                                                 );
906                                         }
907                                 }
908                         }
909                 }
910         }
911
912         pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
913                 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
914                 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
915                 // this could race the user making a duplicate send_payment call and our idempotency
916                 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
917                 // removal. This should be more than sufficient to ensure the idempotency of any
918                 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
919                 // processed.
920                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
921                 let pending_events = pending_events.lock().unwrap();
922                 pending_outbound_payments.retain(|payment_id, payment| {
923                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
924                                 let mut no_remaining_entries = session_privs.is_empty();
925                                 if no_remaining_entries {
926                                         for ev in pending_events.iter() {
927                                                 match ev {
928                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
929                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
930                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
931                                                                         if payment_id == ev_payment_id {
932                                                                                 no_remaining_entries = false;
933                                                                                 break;
934                                                                         }
935                                                                 },
936                                                         _ => {},
937                                                 }
938                                         }
939                                 }
940                                 if no_remaining_entries {
941                                         *timer_ticks_without_htlcs += 1;
942                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
943                                 } else {
944                                         *timer_ticks_without_htlcs = 0;
945                                         true
946                                 }
947                         } else { true }
948                 });
949         }
950
951         pub(super) fn fail_htlc<L: Deref>(
952                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
953                 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
954                 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
955                 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
956         ) where L::Target: Logger {
957                 #[cfg(test)]
958                 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
959                 #[cfg(not(test))]
960                 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
961
962                 let mut session_priv_bytes = [0; 32];
963                 session_priv_bytes.copy_from_slice(&session_priv[..]);
964                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
965                 let mut all_paths_failed = false;
966                 let mut full_failure_ev = None;
967                 let mut pending_retry_ev = None;
968                 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
969                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
970                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
971                                 return
972                         }
973                         if payment.get().is_fulfilled() {
974                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
975                                 return
976                         }
977                         let is_retryable_now = payment.get().is_auto_retryable_now();
978                         if let Some(scid) = short_channel_id {
979                                 payment.get_mut().insert_previously_failed_scid(scid);
980                         }
981                         if payment.get().remaining_parts() == 0 {
982                                 all_paths_failed = true;
983                                 if payment.get().abandoned() {
984                                         full_failure_ev = Some(events::Event::PaymentFailed {
985                                                 payment_id: *payment_id,
986                                                 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
987                                         });
988                                         payment.remove();
989                                 }
990                         }
991                         is_retryable_now
992                 } else {
993                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
994                         return
995                 };
996                 core::mem::drop(outbounds);
997                 let mut retry = if let Some(payment_params_data) = payment_params {
998                         let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
999                         Some(RouteParameters {
1000                                 payment_params: payment_params_data.clone(),
1001                                 final_value_msat: path_last_hop.fee_msat,
1002                                 final_cltv_expiry_delta:
1003                                         if let Some(delta) = payment_params_data.final_cltv_expiry_delta { delta }
1004                                         else { path_last_hop.cltv_expiry_delta },
1005                         })
1006                 } else { None };
1007                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1008
1009                 let path_failure = {
1010                         if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
1011                                 if !payment_retryable {
1012                                         events::Event::ProbeSuccessful {
1013                                                 payment_id: *payment_id,
1014                                                 payment_hash: payment_hash.clone(),
1015                                                 path: path.clone(),
1016                                         }
1017                                 } else {
1018                                         events::Event::ProbeFailed {
1019                                                 payment_id: *payment_id,
1020                                                 payment_hash: payment_hash.clone(),
1021                                                 path: path.clone(),
1022                                                 short_channel_id,
1023                                         }
1024                                 }
1025                         } else {
1026                                 // TODO: If we decided to blame ourselves (or one of our channels) in
1027                                 // process_onion_failure we should close that channel as it implies our
1028                                 // next-hop is needlessly blaming us!
1029                                 if let Some(scid) = short_channel_id {
1030                                         retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1031                                 }
1032                                 if payment_retryable && attempts_remaining && retry.is_some() {
1033                                         debug_assert!(full_failure_ev.is_none());
1034                                         pending_retry_ev = Some(events::Event::PendingHTLCsForwardable {
1035                                                 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
1036                                         });
1037                                 }
1038                                 events::Event::PaymentPathFailed {
1039                                         payment_id: Some(*payment_id),
1040                                         payment_hash: payment_hash.clone(),
1041                                         payment_failed_permanently: !payment_retryable,
1042                                         network_update,
1043                                         all_paths_failed,
1044                                         path: path.clone(),
1045                                         short_channel_id,
1046                                         retry,
1047                                         #[cfg(test)]
1048                                         error_code: onion_error_code,
1049                                         #[cfg(test)]
1050                                         error_data: onion_error_data
1051                                 }
1052                         }
1053                 };
1054                 let mut pending_events = pending_events.lock().unwrap();
1055                 pending_events.push(path_failure);
1056                 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1057                 if let Some(ev) = pending_retry_ev { pending_events.push(ev); }
1058         }
1059
1060         pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
1061                 let mut failed_ev = None;
1062                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1063                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1064                         if let Ok(()) = payment.get_mut().mark_abandoned() {
1065                                 if payment.get().remaining_parts() == 0 {
1066                                         failed_ev = Some(events::Event::PaymentFailed {
1067                                                 payment_id,
1068                                                 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1069                                         });
1070                                         payment.remove();
1071                                 }
1072                         }
1073                 }
1074                 failed_ev
1075         }
1076
1077         #[cfg(test)]
1078         pub fn has_pending_payments(&self) -> bool {
1079                 !self.pending_outbound_payments.lock().unwrap().is_empty()
1080         }
1081
1082         #[cfg(test)]
1083         pub fn clear_pending_payments(&self) {
1084                 self.pending_outbound_payments.lock().unwrap().clear()
1085         }
1086 }
1087
1088 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1089 /// payment probe.
1090 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1091         probing_cookie_secret: [u8; 32]) -> bool
1092 {
1093         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1094         target_payment_hash == *payment_hash
1095 }
1096
1097 /// Returns the 'probing cookie' for the given [`PaymentId`].
1098 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1099         let mut preimage = [0u8; 64];
1100         preimage[..32].copy_from_slice(&probing_cookie_secret);
1101         preimage[32..].copy_from_slice(&payment_id.0);
1102         PaymentHash(Sha256::hash(&preimage).into_inner())
1103 }
1104
1105 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1106         (0, Legacy) => {
1107                 (0, session_privs, required),
1108         },
1109         (1, Fulfilled) => {
1110                 (0, session_privs, required),
1111                 (1, payment_hash, option),
1112                 (3, timer_ticks_without_htlcs, (default_value, 0)),
1113         },
1114         (2, Retryable) => {
1115                 (0, session_privs, required),
1116                 (1, pending_fee_msat, option),
1117                 (2, payment_hash, required),
1118                 (not_written, retry_strategy, (static_value, None)),
1119                 (4, payment_secret, option),
1120                 (not_written, attempts, (static_value, PaymentAttempts::new())),
1121                 (6, total_msat, required),
1122                 (not_written, route_params, (static_value, None)),
1123                 (8, pending_amt_msat, required),
1124                 (10, starting_block_height, required),
1125         },
1126         (3, Abandoned) => {
1127                 (0, session_privs, required),
1128                 (2, payment_hash, required),
1129         },
1130 );
1131
1132 #[cfg(test)]
1133 mod tests {
1134         use bitcoin::blockdata::constants::genesis_block;
1135         use bitcoin::network::constants::Network;
1136         use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1137
1138         use crate::ln::PaymentHash;
1139         use crate::ln::channelmanager::{PaymentId, PaymentSendFailure};
1140         use crate::ln::msgs::{ErrorAction, LightningError};
1141         use crate::ln::outbound_payment::{OutboundPayments, Retry};
1142         use crate::routing::gossip::NetworkGraph;
1143         use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
1144         use crate::sync::Arc;
1145         use crate::util::errors::APIError;
1146         use crate::util::test_utils;
1147
1148         #[test]
1149         #[cfg(feature = "std")]
1150         fn fails_paying_after_expiration() {
1151                 do_fails_paying_after_expiration(false);
1152                 do_fails_paying_after_expiration(true);
1153         }
1154         #[cfg(feature = "std")]
1155         fn do_fails_paying_after_expiration(on_retry: bool) {
1156                 let outbound_payments = OutboundPayments::new();
1157                 let logger = test_utils::TestLogger::new();
1158                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1159                 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1160                 let router = test_utils::TestRouter::new(network_graph);
1161                 let secp_ctx = Secp256k1::new();
1162                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1163
1164                 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1165                 let payment_params = PaymentParameters::from_node_id(
1166                                 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1167                                 0
1168                         ).with_expiry_time(past_expiry_time);
1169                 let expired_route_params = RouteParameters {
1170                         payment_params,
1171                         final_value_msat: 0,
1172                         final_cltv_expiry_delta: 0,
1173                 };
1174                 let err = if on_retry {
1175                         outbound_payments.pay_internal(
1176                                 PaymentId([0; 32]), None, expired_route_params, &&router, vec![], InFlightHtlcs::new(),
1177                                 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1178                 } else {
1179                         outbound_payments.send_payment(
1180                                 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1181                                 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1182                                 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1183                 };
1184                 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1185                         assert!(err.contains("Invoice expired"));
1186                 } else { panic!("Unexpected error"); }
1187         }
1188
1189         #[test]
1190         fn find_route_error() {
1191                 do_find_route_error(false);
1192                 do_find_route_error(true);
1193         }
1194         fn do_find_route_error(on_retry: bool) {
1195                 let outbound_payments = OutboundPayments::new();
1196                 let logger = test_utils::TestLogger::new();
1197                 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1198                 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1199                 let router = test_utils::TestRouter::new(network_graph);
1200                 let secp_ctx = Secp256k1::new();
1201                 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1202
1203                 let payment_params = PaymentParameters::from_node_id(
1204                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1205                 let route_params = RouteParameters {
1206                         payment_params,
1207                         final_value_msat: 0,
1208                         final_cltv_expiry_delta: 0,
1209                 };
1210                 router.expect_find_route(route_params.clone(),
1211                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1212
1213                 let err = if on_retry {
1214                         outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]),
1215                         &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)), Some(route_params.clone()),
1216                         &&keys_manager, 0).unwrap();
1217                         outbound_payments.pay_internal(
1218                                 PaymentId([0; 32]), None, route_params, &&router, vec![], InFlightHtlcs::new(),
1219                                 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1220                 } else {
1221                         outbound_payments.send_payment(
1222                                 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1223                                 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1224                                 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1225                 };
1226                 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1227                         assert!(err.contains("Failed to find a route"));
1228                 } else { panic!("Unexpected error"); }
1229         }
1230 }