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