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