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