Copy Retry from invoice module to outbound_payment module
[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::{HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, RoutePath};
22 use crate::util::errors::APIError;
23 use crate::util::events;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(not(feature = "no-std"), test))]
27 use crate::util::time::tests::SinceEpoch;
28
29 use core::cmp;
30 use core::fmt::{self, Display, Formatter};
31 use core::ops::Deref;
32
33 use crate::prelude::*;
34 use crate::sync::Mutex;
35
36 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
37 /// and later, also stores information for retrying the payment.
38 pub(crate) enum PendingOutboundPayment {
39         Legacy {
40                 session_privs: HashSet<[u8; 32]>,
41         },
42         Retryable {
43                 session_privs: HashSet<[u8; 32]>,
44                 payment_hash: PaymentHash,
45                 payment_secret: Option<PaymentSecret>,
46                 pending_amt_msat: u64,
47                 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
48                 pending_fee_msat: Option<u64>,
49                 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
50                 total_msat: u64,
51                 /// Our best known block height at the time this payment was initiated.
52                 starting_block_height: u32,
53         },
54         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
55         /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
56         /// and add a pending payment that was already fulfilled.
57         Fulfilled {
58                 session_privs: HashSet<[u8; 32]>,
59                 payment_hash: Option<PaymentHash>,
60                 timer_ticks_without_htlcs: u8,
61         },
62         /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
63         /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
64         /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
65         /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
66         /// downstream event handler as to when a payment has actually failed.
67         ///
68         /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
69         Abandoned {
70                 session_privs: HashSet<[u8; 32]>,
71                 payment_hash: PaymentHash,
72         },
73 }
74
75 impl PendingOutboundPayment {
76         pub(super) fn is_fulfilled(&self) -> bool {
77                 match self {
78                         PendingOutboundPayment::Fulfilled { .. } => true,
79                         _ => false,
80                 }
81         }
82         pub(super) fn abandoned(&self) -> bool {
83                 match self {
84                         PendingOutboundPayment::Abandoned { .. } => true,
85                         _ => false,
86                 }
87         }
88         fn get_pending_fee_msat(&self) -> Option<u64> {
89                 match self {
90                         PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
91                         _ => None,
92                 }
93         }
94
95         fn payment_hash(&self) -> Option<PaymentHash> {
96                 match self {
97                         PendingOutboundPayment::Legacy { .. } => None,
98                         PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
99                         PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
100                         PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
101                 }
102         }
103
104         fn mark_fulfilled(&mut self) {
105                 let mut session_privs = HashSet::new();
106                 core::mem::swap(&mut session_privs, match self {
107                         PendingOutboundPayment::Legacy { session_privs } |
108                                 PendingOutboundPayment::Retryable { session_privs, .. } |
109                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
110                                 PendingOutboundPayment::Abandoned { session_privs, .. }
111                         => session_privs,
112                 });
113                 let payment_hash = self.payment_hash();
114                 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
115         }
116
117         fn mark_abandoned(&mut self) -> Result<(), ()> {
118                 let mut session_privs = HashSet::new();
119                 let our_payment_hash;
120                 core::mem::swap(&mut session_privs, match self {
121                         PendingOutboundPayment::Legacy { .. } |
122                                 PendingOutboundPayment::Fulfilled { .. } =>
123                                 return Err(()),
124                                 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
125                                         PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
126                                                 our_payment_hash = *payment_hash;
127                                                 session_privs
128                                         },
129                 });
130                 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
131                 Ok(())
132         }
133
134         /// panics if path is None and !self.is_fulfilled
135         fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
136                 let remove_res = match self {
137                         PendingOutboundPayment::Legacy { session_privs } |
138                                 PendingOutboundPayment::Retryable { session_privs, .. } |
139                                 PendingOutboundPayment::Fulfilled { session_privs, .. } |
140                                 PendingOutboundPayment::Abandoned { session_privs, .. } => {
141                                         session_privs.remove(session_priv)
142                                 }
143                 };
144                 if remove_res {
145                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
146                                 let path = path.expect("Fulfilling a payment should always come with a path");
147                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
148                                 *pending_amt_msat -= path_last_hop.fee_msat;
149                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
150                                         *fee_msat -= path.get_path_fees();
151                                 }
152                         }
153                 }
154                 remove_res
155         }
156
157         pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
158                 let insert_res = match self {
159                         PendingOutboundPayment::Legacy { session_privs } |
160                                 PendingOutboundPayment::Retryable { session_privs, .. } => {
161                                         session_privs.insert(session_priv)
162                                 }
163                         PendingOutboundPayment::Fulfilled { .. } => false,
164                         PendingOutboundPayment::Abandoned { .. } => false,
165                 };
166                 if insert_res {
167                         if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
168                                 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
169                                 *pending_amt_msat += path_last_hop.fee_msat;
170                                 if let Some(fee_msat) = pending_fee_msat.as_mut() {
171                                         *fee_msat += path.get_path_fees();
172                                 }
173                         }
174                 }
175                 insert_res
176         }
177
178         pub(super) fn remaining_parts(&self) -> usize {
179                 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.len()
185                                 }
186                 }
187         }
188 }
189
190 /// Strategies available to retry payment path failures.
191 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
192 pub enum Retry {
193         /// Max number of attempts to retry payment.
194         ///
195         /// Note that this is the number of *path* failures, not full payment retries. For multi-path
196         /// payments, if this is less than the total number of paths, we will never even retry all of the
197         /// payment's paths.
198         Attempts(usize),
199         #[cfg(not(feature = "no-std"))]
200         /// Time elapsed before abandoning retries for a payment.
201         Timeout(core::time::Duration),
202 }
203
204 impl Retry {
205         pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
206                 match (self, attempts) {
207                         (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
208                                 max_retry_count > count
209                         },
210                         #[cfg(all(not(feature = "no-std"), not(test)))]
211                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
212                                 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
213                         #[cfg(all(not(feature = "no-std"), test))]
214                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
215                                 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
216                 }
217         }
218 }
219
220 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
221
222 /// Storing minimal payment attempts information required for determining if a outbound payment can
223 /// be retried.
224 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
225         /// This count will be incremented only after the result of the attempt is known. When it's 0,
226         /// it means the result of the first attempt is not known yet.
227         pub(crate) count: usize,
228         /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
229         first_attempted_at: T
230 }
231
232 #[cfg(not(any(feature = "no-std", test)))]
233 type ConfiguredTime = std::time::Instant;
234 #[cfg(feature = "no-std")]
235 type ConfiguredTime = crate::util::time::Eternity;
236 #[cfg(all(not(feature = "no-std"), test))]
237 type ConfiguredTime = SinceEpoch;
238
239 impl<T: Time> PaymentAttemptsUsingTime<T> {
240         pub(crate) fn new() -> Self {
241                 PaymentAttemptsUsingTime {
242                         count: 0,
243                         first_attempted_at: T::now()
244                 }
245         }
246 }
247
248 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
249         fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
250                 #[cfg(feature = "no-std")]
251                 return write!(f, "attempts: {}", self.count);
252                 #[cfg(not(feature = "no-std"))]
253                 return write!(
254                         f,
255                         "attempts: {}, duration: {}s",
256                         self.count,
257                         T::now().duration_since(self.first_attempted_at).as_secs()
258                 );
259         }
260 }
261
262 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
263 /// Err() type describing which state the payment is in, see the description of individual enum
264 /// states for more.
265 #[derive(Clone, Debug)]
266 pub enum PaymentSendFailure {
267         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
268         /// send the payment at all.
269         ///
270         /// You can freely resend the payment in full (with the parameter error fixed).
271         ///
272         /// Because the payment failed outright, no payment tracking is done, you do not need to call
273         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
274         /// for this payment.
275         ///
276         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
277         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
278         ParameterError(APIError),
279         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
280         /// from attempting to send the payment at all.
281         ///
282         /// You can freely resend the payment in full (with the parameter error fixed).
283         ///
284         /// The results here are ordered the same as the paths in the route object which was passed to
285         /// send_payment.
286         ///
287         /// Because the payment failed outright, no payment tracking is done, you do not need to call
288         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
289         /// for this payment.
290         ///
291         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
292         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
293         PathParameterError(Vec<Result<(), APIError>>),
294         /// All paths which were attempted failed to send, with no channel state change taking place.
295         /// You can freely resend the payment in full (though you probably want to do so over different
296         /// paths than the ones selected).
297         ///
298         /// Because the payment failed outright, no payment tracking is done, you do not need to call
299         /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
300         /// for this payment.
301         ///
302         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
303         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
304         AllFailedResendSafe(Vec<APIError>),
305         /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
306         /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
307         /// [`ChannelManager::abandon_payment`]).
308         ///
309         /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
310         /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
311         /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
312         DuplicatePayment,
313         /// Some paths which were attempted failed to send, though possibly not all. At least some
314         /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
315         /// in over-/re-payment.
316         ///
317         /// The results here are ordered the same as the paths in the route object which was passed to
318         /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
319         /// safely retried via [`ChannelManager::retry_payment`].
320         ///
321         /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
322         /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
323         /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
324         /// the next-hop channel with the latest update_id.
325         ///
326         /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
327         /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
328         PartialFailure {
329                 /// The errors themselves, in the same order as the route hops.
330                 results: Vec<Result<(), APIError>>,
331                 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
332                 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
333                 /// will pay all remaining unpaid balance.
334                 failed_paths_retry: Option<RouteParameters>,
335                 /// The payment id for the payment, which is now at least partially pending.
336                 payment_id: PaymentId,
337         },
338 }
339
340 pub(super) struct OutboundPayments {
341         pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
342 }
343
344 impl OutboundPayments {
345         pub(super) fn new() -> Self {
346                 Self {
347                         pending_outbound_payments: Mutex::new(HashMap::new())
348                 }
349         }
350
351         pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
352                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
353                 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
354                 send_payment_along_path: F
355         ) -> Result<(), PaymentSendFailure>
356         where
357                 ES::Target: EntropySource,
358                 NS::Target: NodeSigner,
359                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
360                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
361         {
362                 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, entropy_source, best_block_height)?;
363                 self.send_payment_internal(route, payment_hash, payment_secret, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path)
364         }
365
366         pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
367                 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
368                 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
369         ) -> Result<PaymentHash, PaymentSendFailure>
370         where
371                 ES::Target: EntropySource,
372                 NS::Target: NodeSigner,
373                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
374                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
375         {
376                 let preimage = match payment_preimage {
377                         Some(p) => p,
378                         None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
379                 };
380                 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
381                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, entropy_source, best_block_height)?;
382
383                 match self.send_payment_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path) {
384                         Ok(()) => Ok(payment_hash),
385                         Err(e) => Err(e)
386                 }
387         }
388
389         pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
390                 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
391                 send_payment_along_path: F
392         ) -> Result<(), PaymentSendFailure>
393         where
394                 ES::Target: EntropySource,
395                 NS::Target: NodeSigner,
396                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
397                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
398         {
399                 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
400                 for path in route.paths.iter() {
401                         if path.len() == 0 {
402                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
403                                         err: "length-0 path in route".to_string()
404                                 }))
405                         }
406                 }
407
408                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
409                 for _ in 0..route.paths.len() {
410                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
411                 }
412
413                 let (total_msat, payment_hash, payment_secret) = {
414                         let mut outbounds = self.pending_outbound_payments.lock().unwrap();
415                         match outbounds.get_mut(&payment_id) {
416                                 Some(payment) => {
417                                         let res = match payment {
418                                                 PendingOutboundPayment::Retryable {
419                                                         total_msat, payment_hash, payment_secret, pending_amt_msat, ..
420                                                 } => {
421                                                         let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
422                                                         if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
423                                                                 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
424                                                                         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()
425                                                                 }))
426                                                         }
427                                                         (*total_msat, *payment_hash, *payment_secret)
428                                                 },
429                                                 PendingOutboundPayment::Legacy { .. } => {
430                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
431                                                                 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
432                                                         }))
433                                                 },
434                                                 PendingOutboundPayment::Fulfilled { .. } => {
435                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
436                                                                 err: "Payment already completed".to_owned()
437                                                         }));
438                                                 },
439                                                 PendingOutboundPayment::Abandoned { .. } => {
440                                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
441                                                                 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
442                                                         }));
443                                                 },
444                                         };
445                                         for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
446                                                 assert!(payment.insert(*session_priv_bytes, path));
447                                         }
448                                         res
449                                 },
450                                 None =>
451                                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
452                                                 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
453                                         })),
454                         }
455                 };
456                 self.send_payment_internal(route, payment_hash, &payment_secret, None, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, send_payment_along_path)
457         }
458
459         pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
460                 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
461                 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
462         ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
463         where
464                 ES::Target: EntropySource,
465                 NS::Target: NodeSigner,
466                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
467                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
468         {
469                 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
470
471                 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
472
473                 if hops.len() < 2 {
474                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
475                                 err: "No need probing a path with less than two hops".to_string()
476                         }))
477                 }
478
479                 let route = Route { paths: vec![hops], payment_params: None };
480                 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, entropy_source, best_block_height)?;
481
482                 match self.send_payment_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path) {
483                         Ok(()) => Ok((payment_hash, payment_id)),
484                         Err(e) => Err(e)
485                 }
486         }
487
488         #[cfg(test)]
489         pub(super) fn test_add_new_pending_payment<ES: Deref>(
490                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
491                 route: &Route, entropy_source: &ES, best_block_height: u32
492         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
493                 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, entropy_source, best_block_height)
494         }
495
496         pub(super) fn add_new_pending_payment<ES: Deref>(
497                 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
498                 route: &Route, entropy_source: &ES, best_block_height: u32
499         ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
500                 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
501                 for _ in 0..route.paths.len() {
502                         onion_session_privs.push(entropy_source.get_secure_random_bytes());
503                 }
504
505                 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
506                 match pending_outbounds.entry(payment_id) {
507                         hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
508                         hash_map::Entry::Vacant(entry) => {
509                                 let payment = entry.insert(PendingOutboundPayment::Retryable {
510                                         session_privs: HashSet::new(),
511                                         pending_amt_msat: 0,
512                                         pending_fee_msat: Some(0),
513                                         payment_hash,
514                                         payment_secret,
515                                         starting_block_height: best_block_height,
516                                         total_msat: route.get_total_amount(),
517                                 });
518
519                                 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
520                                         assert!(payment.insert(*session_priv_bytes, path));
521                                 }
522
523                                 Ok(onion_session_privs)
524                         },
525                 }
526         }
527
528         fn send_payment_internal<NS: Deref, F>(
529                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
530                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
531                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
532                 send_payment_along_path: F
533         ) -> Result<(), PaymentSendFailure>
534         where
535                 NS::Target: NodeSigner,
536                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
537                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
538         {
539                 if route.paths.len() < 1 {
540                         return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
541                 }
542                 if payment_secret.is_none() && route.paths.len() > 1 {
543                         return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
544                 }
545                 let mut total_value = 0;
546                 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
547                 let mut path_errs = Vec::with_capacity(route.paths.len());
548                 'path_check: for path in route.paths.iter() {
549                         if path.len() < 1 || path.len() > 20 {
550                                 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
551                                 continue 'path_check;
552                         }
553                         for (idx, hop) in path.iter().enumerate() {
554                                 if idx != path.len() - 1 && hop.pubkey == our_node_id {
555                                         path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
556                                         continue 'path_check;
557                                 }
558                         }
559                         total_value += path.last().unwrap().fee_msat;
560                         path_errs.push(Ok(()));
561                 }
562                 if path_errs.iter().any(|e| e.is_err()) {
563                         return Err(PaymentSendFailure::PathParameterError(path_errs));
564                 }
565                 if let Some(amt_msat) = recv_value_msat {
566                         debug_assert!(amt_msat >= total_value);
567                         total_value = amt_msat;
568                 }
569
570                 let cur_height = best_block_height + 1;
571                 let mut results = Vec::new();
572                 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
573                 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
574                         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);
575                         match path_res {
576                                 Ok(_) => {},
577                                 Err(APIError::MonitorUpdateInProgress) => {
578                                         // While a MonitorUpdateInProgress is an Err(_), the payment is still
579                                         // considered "in flight" and we shouldn't remove it from the
580                                         // PendingOutboundPayment set.
581                                 },
582                                 Err(_) => {
583                                         let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
584                                         if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
585                                                 let removed = payment.remove(&session_priv, Some(path));
586                                                 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
587                                         } else {
588                                                 debug_assert!(false, "This can't happen as the payment was added by callers");
589                                                 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
590                                         }
591                                 }
592                         }
593                         results.push(path_res);
594                 }
595                 let mut has_ok = false;
596                 let mut has_err = false;
597                 let mut pending_amt_unsent = 0;
598                 let mut max_unsent_cltv_delta = 0;
599                 for (res, path) in results.iter().zip(route.paths.iter()) {
600                         if res.is_ok() { has_ok = true; }
601                         if res.is_err() { has_err = true; }
602                         if let &Err(APIError::MonitorUpdateInProgress) = res {
603                                 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
604                                 // PartialFailure.
605                                 has_err = true;
606                                 has_ok = true;
607                         } else if res.is_err() {
608                                 pending_amt_unsent += path.last().unwrap().fee_msat;
609                                 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
610                         }
611                 }
612                 if has_err && has_ok {
613                         Err(PaymentSendFailure::PartialFailure {
614                                 results,
615                                 payment_id,
616                                 failed_paths_retry: if pending_amt_unsent != 0 {
617                                         if let Some(payment_params) = &route.payment_params {
618                                                 Some(RouteParameters {
619                                                         payment_params: payment_params.clone(),
620                                                         final_value_msat: pending_amt_unsent,
621                                                         final_cltv_expiry_delta: max_unsent_cltv_delta,
622                                                 })
623                                         } else { None }
624                                 } else { None },
625                         })
626                 } else if has_err {
627                         // If we failed to send any paths, we should remove the new PaymentId from the
628                         // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
629                         let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
630                         debug_assert!(removed, "We should always have a pending payment to remove here");
631                         Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
632                 } else {
633                         Ok(())
634                 }
635         }
636
637         #[cfg(test)]
638         pub(super) fn test_send_payment_internal<NS: Deref, F>(
639                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
640                 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
641                 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
642                 send_payment_along_path: F
643         ) -> Result<(), PaymentSendFailure>
644         where
645                 NS::Target: NodeSigner,
646                 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
647                    u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
648         {
649                 self.send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
650                         recv_value_msat, onion_session_privs, node_signer, best_block_height,
651                         send_payment_along_path)
652         }
653
654         pub(super) fn claim_htlc<L: Deref>(
655                 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
656                 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
657         ) where L::Target: Logger {
658                 let mut session_priv_bytes = [0; 32];
659                 session_priv_bytes.copy_from_slice(&session_priv[..]);
660                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
661                 let mut pending_events = pending_events.lock().unwrap();
662                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
663                         if !payment.get().is_fulfilled() {
664                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
665                                 let fee_paid_msat = payment.get().get_pending_fee_msat();
666                                 pending_events.push(
667                                         events::Event::PaymentSent {
668                                                 payment_id: Some(payment_id),
669                                                 payment_preimage,
670                                                 payment_hash,
671                                                 fee_paid_msat,
672                                         }
673                                 );
674                                 payment.get_mut().mark_fulfilled();
675                         }
676
677                         if from_onchain {
678                                 // We currently immediately remove HTLCs which were fulfilled on-chain.
679                                 // This could potentially lead to removing a pending payment too early,
680                                 // with a reorg of one block causing us to re-add the fulfilled payment on
681                                 // restart.
682                                 // TODO: We should have a second monitor event that informs us of payments
683                                 // irrevocably fulfilled.
684                                 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
685                                         let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
686                                         pending_events.push(
687                                                 events::Event::PaymentPathSuccessful {
688                                                         payment_id,
689                                                         payment_hash,
690                                                         path,
691                                                 }
692                                         );
693                                 }
694                         }
695                 } else {
696                         log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
697                 }
698         }
699
700         pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
701                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
702                 let mut pending_events = pending_events.lock().unwrap();
703                 for source in sources {
704                         if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
705                                 let mut session_priv_bytes = [0; 32];
706                                 session_priv_bytes.copy_from_slice(&session_priv[..]);
707                                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
708                                         assert!(payment.get().is_fulfilled());
709                                         if payment.get_mut().remove(&session_priv_bytes, None) {
710                                                 pending_events.push(
711                                                         events::Event::PaymentPathSuccessful {
712                                                                 payment_id,
713                                                                 payment_hash: payment.get().payment_hash(),
714                                                                 path,
715                                                         }
716                                                 );
717                                         }
718                                 }
719                         }
720                 }
721         }
722
723         pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
724                 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
725                 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
726                 // this could race the user making a duplicate send_payment call and our idempotency
727                 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
728                 // removal. This should be more than sufficient to ensure the idempotency of any
729                 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
730                 // processed.
731                 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
732                 let pending_events = pending_events.lock().unwrap();
733                 pending_outbound_payments.retain(|payment_id, payment| {
734                         if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
735                                 let mut no_remaining_entries = session_privs.is_empty();
736                                 if no_remaining_entries {
737                                         for ev in pending_events.iter() {
738                                                 match ev {
739                                                         events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
740                                                                 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
741                                                                 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
742                                                                         if payment_id == ev_payment_id {
743                                                                                 no_remaining_entries = false;
744                                                                                 break;
745                                                                         }
746                                                                 },
747                                                         _ => {},
748                                                 }
749                                         }
750                                 }
751                                 if no_remaining_entries {
752                                         *timer_ticks_without_htlcs += 1;
753                                         *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
754                                 } else {
755                                         *timer_ticks_without_htlcs = 0;
756                                         true
757                                 }
758                         } else { true }
759                 });
760         }
761
762         pub(super) fn fail_htlc<L: Deref>(
763                 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
764                 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
765                 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
766                 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
767         ) where L::Target: Logger {
768                 let mut session_priv_bytes = [0; 32];
769                 session_priv_bytes.copy_from_slice(&session_priv[..]);
770                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
771                 let mut all_paths_failed = false;
772                 let mut full_failure_ev = None;
773                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
774                         if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
775                                 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
776                                 return
777                         }
778                         if payment.get().is_fulfilled() {
779                                 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
780                                 return
781                         }
782                         if payment.get().remaining_parts() == 0 {
783                                 all_paths_failed = true;
784                                 if payment.get().abandoned() {
785                                         full_failure_ev = Some(events::Event::PaymentFailed {
786                                                 payment_id: *payment_id,
787                                                 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
788                                         });
789                                         payment.remove();
790                                 }
791                         }
792                 } else {
793                         log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
794                         return
795                 }
796                 let mut retry = if let Some(payment_params_data) = payment_params {
797                         let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
798                         Some(RouteParameters {
799                                 payment_params: payment_params_data.clone(),
800                                 final_value_msat: path_last_hop.fee_msat,
801                                 final_cltv_expiry_delta: path_last_hop.cltv_expiry_delta,
802                         })
803                 } else { None };
804                 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
805
806                 let path_failure = {
807                         #[cfg(test)]
808                         let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
809                         #[cfg(not(test))]
810                         let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
811
812                         if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
813                                 if !payment_retryable {
814                                         events::Event::ProbeSuccessful {
815                                                 payment_id: *payment_id,
816                                                 payment_hash: payment_hash.clone(),
817                                                 path: path.clone(),
818                                         }
819                                 } else {
820                                         events::Event::ProbeFailed {
821                                                 payment_id: *payment_id,
822                                                 payment_hash: payment_hash.clone(),
823                                                 path: path.clone(),
824                                                 short_channel_id,
825                                         }
826                                 }
827                         } else {
828                                 // TODO: If we decided to blame ourselves (or one of our channels) in
829                                 // process_onion_failure we should close that channel as it implies our
830                                 // next-hop is needlessly blaming us!
831                                 if let Some(scid) = short_channel_id {
832                                         retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
833                                 }
834                                 events::Event::PaymentPathFailed {
835                                         payment_id: Some(*payment_id),
836                                         payment_hash: payment_hash.clone(),
837                                         payment_failed_permanently: !payment_retryable,
838                                         network_update,
839                                         all_paths_failed,
840                                         path: path.clone(),
841                                         short_channel_id,
842                                         retry,
843                                         #[cfg(test)]
844                                         error_code: onion_error_code,
845                                         #[cfg(test)]
846                                         error_data: onion_error_data
847                                 }
848                         }
849                 };
850                 let mut pending_events = pending_events.lock().unwrap();
851                 pending_events.push(path_failure);
852                 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
853         }
854
855         pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
856                 let mut failed_ev = None;
857                 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
858                 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
859                         if let Ok(()) = payment.get_mut().mark_abandoned() {
860                                 if payment.get().remaining_parts() == 0 {
861                                         failed_ev = Some(events::Event::PaymentFailed {
862                                                 payment_id,
863                                                 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
864                                         });
865                                         payment.remove();
866                                 }
867                         }
868                 }
869                 failed_ev
870         }
871
872         #[cfg(test)]
873         pub fn has_pending_payments(&self) -> bool {
874                 !self.pending_outbound_payments.lock().unwrap().is_empty()
875         }
876
877         #[cfg(test)]
878         pub fn clear_pending_payments(&self) {
879                 self.pending_outbound_payments.lock().unwrap().clear()
880         }
881 }
882
883 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
884 /// payment probe.
885 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
886         probing_cookie_secret: [u8; 32]) -> bool
887 {
888         let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
889         target_payment_hash == *payment_hash
890 }
891
892 /// Returns the 'probing cookie' for the given [`PaymentId`].
893 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
894         let mut preimage = [0u8; 64];
895         preimage[..32].copy_from_slice(&probing_cookie_secret);
896         preimage[32..].copy_from_slice(&payment_id.0);
897         PaymentHash(Sha256::hash(&preimage).into_inner())
898 }
899
900 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
901         (0, Legacy) => {
902                 (0, session_privs, required),
903         },
904         (1, Fulfilled) => {
905                 (0, session_privs, required),
906                 (1, payment_hash, option),
907                 (3, timer_ticks_without_htlcs, (default_value, 0)),
908         },
909         (2, Retryable) => {
910                 (0, session_privs, required),
911                 (1, pending_fee_msat, option),
912                 (2, payment_hash, required),
913                 (4, payment_secret, option),
914                 (6, total_msat, required),
915                 (8, pending_amt_msat, required),
916                 (10, starting_block_height, required),
917         },
918         (3, Abandoned) => {
919                 (0, session_privs, required),
920                 (2, payment_hash, required),
921         },
922 );