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