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