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