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