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