(Bindings Only) Concretize LockableScore as MultiThreadedLockableScore
[rust-lightning] / lightning-invoice / src / 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 //! A module for paying Lightning invoices and sending spontaneous payments.
11 //!
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
16 //! applicable.
17 //!
18 //! [`InvoicePayer`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
19 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
20 //! [`Event::PaymentPathSuccessful`] events, respectively.
21 //!
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
27 //!
28 //! # Example
29 //!
30 //! ```
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
34 //! #
35 //! # #[cfg(feature = "no-std")]
36 //! # extern crate core2;
37 //! #
38 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
39 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
40 //! # use lightning::ln::msgs::LightningError;
41 //! # use lightning::routing::scoring::Score;
42 //! # use lightning::routing::network_graph::NodeId;
43 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
44 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # use lightning::util::ser::{Writeable, Writer};
47 //! # use lightning_invoice::Invoice;
48 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
49 //! # use secp256k1::key::PublicKey;
50 //! # use std::cell::RefCell;
51 //! # use std::ops::Deref;
52 //! #
53 //! # #[cfg(not(feature = "std"))]
54 //! # use core2::io;
55 //! # #[cfg(feature = "std")]
56 //! # use std::io;
57 //! #
58 //! # struct FakeEventProvider {}
59 //! # impl EventsProvider for FakeEventProvider {
60 //! #     fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
61 //! # }
62 //! #
63 //! # struct FakePayer {}
64 //! # impl Payer for FakePayer {
65 //! #     fn node_id(&self) -> PublicKey { unimplemented!() }
66 //! #     fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
67 //! #     fn send_payment(
68 //! #         &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
69 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
70 //! #     fn send_spontaneous_payment(
71 //! #         &self, route: &Route, payment_preimage: PaymentPreimage
72 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
73 //! #     fn retry_payment(
74 //! #         &self, route: &Route, payment_id: PaymentId
75 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
76 //! #     fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
77 //! # }
78 //! #
79 //! # struct FakeRouter {}
80 //! # impl<S: Score> Router<S> for FakeRouter {
81 //! #     fn find_route(
82 //! #         &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
83 //! #         first_hops: Option<&[&ChannelDetails]>, scorer: &S
84 //! #     ) -> Result<Route, LightningError> { unimplemented!() }
85 //! # }
86 //! #
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! #     fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
90 //! # }
91 //! # impl Score for FakeScorer {
92 //! #     fn channel_penalty_msat(
93 //! #         &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
94 //! #     ) -> u64 { 0 }
95 //! #     fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! #     fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # }
98 //! #
99 //! # struct FakeLogger {}
100 //! # impl Logger for FakeLogger {
101 //! #     fn log(&self, record: &Record) { unimplemented!() }
102 //! # }
103 //! #
104 //! # fn main() {
105 //! let event_handler = |event: &Event| {
106 //!     match event {
107 //!         Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
108 //!         Event::PaymentSent { .. } => println!("payment successful"),
109 //!         _ => {},
110 //!     }
111 //! };
112 //! # let payer = FakePayer {};
113 //! # let router = FakeRouter {};
114 //! # let scorer = RefCell::new(FakeScorer {});
115 //! # let logger = FakeLogger {};
116 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
117 //!
118 //! let invoice = "...";
119 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
120 //!     invoice_payer.pay_invoice(&invoice).unwrap();
121 //!
122 //! # let event_provider = FakeEventProvider {};
123 //!     loop {
124 //!         event_provider.process_pending_events(&invoice_payer);
125 //!     }
126 //! }
127 //! # }
128 //! ```
129 //!
130 //! # Note
131 //!
132 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
133 //! as updates to the network graph or changes to channel scores should be applied prior to
134 //! retries, typically by way of composing [`EventHandler`]s accordingly.
135
136 use crate::Invoice;
137
138 use bitcoin_hashes::Hash;
139 use bitcoin_hashes::sha256::Hash as Sha256;
140
141 use crate::prelude::*;
142 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
143 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
144 use lightning::ln::msgs::LightningError;
145 use lightning::routing::scoring::{LockableScore, MultiThreadedLockableScore, Score};
146 use lightning::routing::router::{PaymentParameters, Route, RouteParameters};
147 use lightning::util::events::{Event, EventHandler};
148 use lightning::util::logger::Logger;
149 use crate::sync::Mutex;
150
151 use secp256k1::key::PublicKey;
152
153 use core::ops::Deref;
154 use core::time::Duration;
155 #[cfg(feature = "std")]
156 use std::time::SystemTime;
157
158 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
159 ///
160 /// See [module-level documentation] for details.
161 ///
162 /// [module-level documentation]: crate::payment
163 pub struct InvoicePayer<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler>
164 where
165         P::Target: Payer,
166         R::Target: Router<S>,
167         L::Target: Logger,
168 {
169         payer: P,
170         router: R,
171         scorer: SR,
172         logger: L,
173         event_handler: E,
174         /// Caches the overall attempts at making a payment, which is updated prior to retrying.
175         payment_cache: Mutex<HashMap<PaymentHash, usize>>,
176         retry_attempts: RetryAttempts,
177 }
178
179 /// A trait defining behavior of an [`Invoice`] payer.
180 pub trait Payer {
181         /// Returns the payer's node id.
182         fn node_id(&self) -> PublicKey;
183
184         /// Returns the payer's channels.
185         fn first_hops(&self) -> Vec<ChannelDetails>;
186
187         /// Sends a payment over the Lightning Network using the given [`Route`].
188         fn send_payment(
189                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
190         ) -> Result<PaymentId, PaymentSendFailure>;
191
192         /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
193         fn send_spontaneous_payment(
194                 &self, route: &Route, payment_preimage: PaymentPreimage
195         ) -> Result<PaymentId, PaymentSendFailure>;
196
197         /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
198         fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
199
200         /// Signals that no further retries for the given payment will occur.
201         fn abandon_payment(&self, payment_id: PaymentId);
202 }
203
204 /// A trait defining behavior for routing an [`Invoice`] payment.
205 pub trait Router<S: Score> {
206         /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
207         fn find_route(
208                 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
209                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
210         ) -> Result<Route, LightningError>;
211 }
212
213 /// Number of attempts to retry payment path failures for an [`Invoice`].
214 ///
215 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
216 /// payments, if this is less than the total number of paths, we will never even retry all of the
217 /// payment's paths.
218 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
219 pub struct RetryAttempts(pub usize);
220
221 /// An error that may occur when making a payment.
222 #[derive(Clone, Debug)]
223 pub enum PaymentError {
224         /// An error resulting from the provided [`Invoice`] or payment hash.
225         Invoice(&'static str),
226         /// An error occurring when finding a route.
227         Routing(LightningError),
228         /// An error occurring when sending a payment.
229         Sending(PaymentSendFailure),
230 }
231
232 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler> InvoicePayer<P, S, R, SR, L, E>
233 where
234         P::Target: Payer,
235         R::Target: Router<S>,
236         L::Target: Logger,
237 {
238         /// Creates an invoice payer that retries failed payment paths.
239         ///
240         /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
241         /// `retry_attempts` has been exceeded for a given [`Invoice`].
242         pub fn new(
243                 payer: P, router: R, scorer: SR, logger: L, event_handler: E, retry_attempts: RetryAttempts
244         ) -> Self {
245                 Self {
246                         payer,
247                         router,
248                         scorer,
249                         logger,
250                         event_handler,
251                         payment_cache: Mutex::new(HashMap::new()),
252                         retry_attempts,
253                 }
254         }
255
256         /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
257         ///
258         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
259         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
260         /// for you.
261         pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
262                 if invoice.amount_milli_satoshis().is_none() {
263                         Err(PaymentError::Invoice("amount missing"))
264                 } else {
265                         self.pay_invoice_using_amount(invoice, None)
266                 }
267         }
268
269         /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
270         /// case a retry is needed.
271         ///
272         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
273         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
274         /// for you.
275         pub fn pay_zero_value_invoice(
276                 &self, invoice: &Invoice, amount_msats: u64
277         ) -> Result<PaymentId, PaymentError> {
278                 if invoice.amount_milli_satoshis().is_some() {
279                         Err(PaymentError::Invoice("amount unexpected"))
280                 } else {
281                         self.pay_invoice_using_amount(invoice, Some(amount_msats))
282                 }
283         }
284
285         fn pay_invoice_using_amount(
286                 &self, invoice: &Invoice, amount_msats: Option<u64>
287         ) -> Result<PaymentId, PaymentError> {
288                 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
289
290                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
291                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
292                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
293                         hash_map::Entry::Vacant(entry) => entry.insert(0),
294                 };
295
296                 let payment_secret = Some(invoice.payment_secret().clone());
297                 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
298                         .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
299                         .with_route_hints(invoice.route_hints());
300                 if let Some(features) = invoice.features() {
301                         payment_params = payment_params.with_features(features.clone());
302                 }
303                 let route_params = RouteParameters {
304                         payment_params,
305                         final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
306                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
307                 };
308
309                 let send_payment = |route: &Route| {
310                         self.payer.send_payment(route, payment_hash, &payment_secret)
311                 };
312                 self.pay_internal(&route_params, payment_hash, send_payment)
313                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
314         }
315
316         /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
317         /// case a retry is needed.
318         ///
319         /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
320         /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
321         pub fn pay_pubkey(
322                 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
323                 final_cltv_expiry_delta: u32
324         ) -> Result<PaymentId, PaymentError> {
325                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
326                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
327                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
328                         hash_map::Entry::Vacant(entry) => entry.insert(0),
329                 };
330
331                 let route_params = RouteParameters {
332                         payment_params: PaymentParameters::for_keysend(pubkey),
333                         final_value_msat: amount_msats,
334                         final_cltv_expiry_delta,
335                 };
336
337                 let send_payment = |route: &Route| {
338                         self.payer.send_spontaneous_payment(route, payment_preimage)
339                 };
340                 self.pay_internal(&route_params, payment_hash, send_payment)
341                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
342         }
343
344         fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
345                 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
346         ) -> Result<PaymentId, PaymentError> {
347                 #[cfg(feature = "std")] {
348                         if has_expired(params) {
349                                 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
350                                 return Err(PaymentError::Invoice("Invoice expired prior to send"));
351                         }
352                 }
353
354                 let payer = self.payer.node_id();
355                 let first_hops = self.payer.first_hops();
356                 let route = self.router.find_route(
357                         &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
358                         &self.scorer.lock()
359                 ).map_err(|e| PaymentError::Routing(e))?;
360
361                 match send_payment(&route) {
362                         Ok(payment_id) => Ok(payment_id),
363                         Err(e) => match e {
364                                 PaymentSendFailure::ParameterError(_) => Err(e),
365                                 PaymentSendFailure::PathParameterError(_) => Err(e),
366                                 PaymentSendFailure::AllFailedRetrySafe(_) => {
367                                         let mut payment_cache = self.payment_cache.lock().unwrap();
368                                         let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
369                                         if *retry_count >= self.retry_attempts.0 {
370                                                 Err(e)
371                                         } else {
372                                                 *retry_count += 1;
373                                                 core::mem::drop(payment_cache);
374                                                 Ok(self.pay_internal(params, payment_hash, send_payment)?)
375                                         }
376                                 },
377                                 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
378                                         if let Some(retry_data) = failed_paths_retry {
379                                                 // Some paths were sent, even if we failed to send the full MPP value our
380                                                 // recipient may misbehave and claim the funds, at which point we have to
381                                                 // consider the payment sent, so return `Ok()` here, ignoring any retry
382                                                 // errors.
383                                                 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
384                                                 Ok(payment_id)
385                                         } else {
386                                                 // This may happen if we send a payment and some paths fail, but
387                                                 // only due to a temporary monitor failure or the like, implying
388                                                 // they're really in-flight, but we haven't sent the initial
389                                                 // HTLC-Add messages yet.
390                                                 Ok(payment_id)
391                                         }
392                                 },
393                         },
394                 }.map_err(|e| PaymentError::Sending(e))
395         }
396
397         fn retry_payment(
398                 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
399         ) -> Result<(), ()> {
400                 let max_payment_attempts = self.retry_attempts.0 + 1;
401                 let attempts = *self.payment_cache.lock().unwrap()
402                         .entry(payment_hash)
403                         .and_modify(|attempts| *attempts += 1)
404                         .or_insert(1);
405
406                 if attempts >= max_payment_attempts {
407                         log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
408                         return Err(());
409                 }
410
411                 #[cfg(feature = "std")] {
412                         if has_expired(params) {
413                                 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
414                                 return Err(());
415                         }
416                 }
417
418                 let payer = self.payer.node_id();
419                 let first_hops = self.payer.first_hops();
420                 let route = self.router.find_route(
421                         &payer, &params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
422                         &self.scorer.lock()
423                 );
424                 if route.is_err() {
425                         log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
426                         return Err(());
427                 }
428
429                 match self.payer.retry_payment(&route.unwrap(), payment_id) {
430                         Ok(()) => Ok(()),
431                         Err(PaymentSendFailure::ParameterError(_)) |
432                         Err(PaymentSendFailure::PathParameterError(_)) => {
433                                 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
434                                 Err(())
435                         },
436                         Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
437                                 self.retry_payment(payment_id, payment_hash, params)
438                         },
439                         Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
440                                 if let Some(retry) = failed_paths_retry {
441                                         // Always return Ok for the same reason as noted in pay_internal.
442                                         let _ = self.retry_payment(payment_id, payment_hash, &retry);
443                                 }
444                                 Ok(())
445                         },
446                 }
447         }
448
449         /// Removes the payment cached by the given payment hash.
450         ///
451         /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
452         /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
453         pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
454                 self.payment_cache.lock().unwrap().remove(payment_hash);
455         }
456 }
457
458 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
459         invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
460 }
461
462 #[cfg(feature = "std")]
463 fn has_expired(route_params: &RouteParameters) -> bool {
464         if let Some(expiry_time) = route_params.payment_params.expiry_time {
465                 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
466         } else { false }
467 }
468
469 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler> EventHandler for InvoicePayer<P, S, R, SR, L, E>
470 where
471         P::Target: Payer,
472         R::Target: Router<S>,
473         L::Target: Logger,
474 {
475         fn handle_event(&self, event: &Event) {
476                 match event {
477                         Event::PaymentPathFailed {
478                                 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
479                         } => {
480                                 if let Some(short_channel_id) = short_channel_id {
481                                         let path = path.iter().collect::<Vec<_>>();
482                                         self.scorer.lock().payment_path_failed(&path, *short_channel_id);
483                                 }
484
485                                 if payment_id.is_none() {
486                                         log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
487                                 } else if *rejected_by_dest {
488                                         log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
489                                         self.payer.abandon_payment(payment_id.unwrap());
490                                 } else if retry.is_none() {
491                                         log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
492                                         self.payer.abandon_payment(payment_id.unwrap());
493                                 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
494                                         // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
495                                         return;
496                                 } else {
497                                         self.payer.abandon_payment(payment_id.unwrap());
498                                 }
499                         },
500                         Event::PaymentFailed { payment_hash, .. } => {
501                                 self.remove_cached_payment(&payment_hash);
502                         },
503                         Event::PaymentPathSuccessful { path, .. } => {
504                                 let path = path.iter().collect::<Vec<_>>();
505                                 self.scorer.lock().payment_path_successful(&path);
506                         },
507                         Event::PaymentSent { payment_hash, .. } => {
508                                 let mut payment_cache = self.payment_cache.lock().unwrap();
509                                 let attempts = payment_cache
510                                         .remove(payment_hash)
511                                         .map_or(1, |attempts| attempts + 1);
512                                 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
513                         },
514                         _ => {},
515                 }
516
517                 // Delegate to the decorated event handler unless the payment is retried.
518                 self.event_handler.handle_event(event)
519         }
520 }
521
522 #[cfg(test)]
523 mod tests {
524         use super::*;
525         use crate::{InvoiceBuilder, Currency};
526         use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
527         use bitcoin_hashes::sha256::Hash as Sha256;
528         use lightning::ln::PaymentPreimage;
529         use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
530         use lightning::ln::functional_test_utils::*;
531         use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
532         use lightning::routing::network_graph::NodeId;
533         use lightning::routing::router::{PaymentParameters, Route, RouteHop};
534         use lightning::util::test_utils::TestLogger;
535         use lightning::util::errors::APIError;
536         use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
537         use secp256k1::{SecretKey, PublicKey, Secp256k1};
538         use std::cell::RefCell;
539         use std::collections::VecDeque;
540         use std::time::{SystemTime, Duration};
541         use DEFAULT_EXPIRY_TIME;
542
543         fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
544                 let payment_hash = Sha256::hash(&payment_preimage.0);
545                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
546
547                 InvoiceBuilder::new(Currency::Bitcoin)
548                         .description("test".into())
549                         .payment_hash(payment_hash)
550                         .payment_secret(PaymentSecret([0; 32]))
551                         .duration_since_epoch(duration_since_epoch())
552                         .min_final_cltv_expiry(144)
553                         .amount_milli_satoshis(128)
554                         .build_signed(|hash| {
555                                 Secp256k1::new().sign_recoverable(hash, &private_key)
556                         })
557                         .unwrap()
558         }
559
560         fn duration_since_epoch() -> Duration {
561                 #[cfg(feature = "std")]
562                         let duration_since_epoch =
563                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
564                 #[cfg(not(feature = "std"))]
565                         let duration_since_epoch = Duration::from_secs(1234567);
566                 duration_since_epoch
567         }
568
569         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
570                 let payment_hash = Sha256::hash(&payment_preimage.0);
571                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
572
573                 InvoiceBuilder::new(Currency::Bitcoin)
574                         .description("test".into())
575                         .payment_hash(payment_hash)
576                         .payment_secret(PaymentSecret([0; 32]))
577                         .duration_since_epoch(duration_since_epoch())
578                         .min_final_cltv_expiry(144)
579                         .build_signed(|hash| {
580                                 Secp256k1::new().sign_recoverable(hash, &private_key)
581                         })
582                         .unwrap()
583         }
584
585         #[cfg(feature = "std")]
586         fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
587                 let payment_hash = Sha256::hash(&payment_preimage.0);
588                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
589                 let duration = duration_since_epoch()
590                         .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
591                         .unwrap();
592                 InvoiceBuilder::new(Currency::Bitcoin)
593                         .description("test".into())
594                         .payment_hash(payment_hash)
595                         .payment_secret(PaymentSecret([0; 32]))
596                         .duration_since_epoch(duration)
597                         .min_final_cltv_expiry(144)
598                         .amount_milli_satoshis(128)
599                         .build_signed(|hash| {
600                                 Secp256k1::new().sign_recoverable(hash, &private_key)
601                         })
602                         .unwrap()
603         }
604
605         fn pubkey() -> PublicKey {
606                 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
607         }
608
609         #[test]
610         fn pays_invoice_on_first_attempt() {
611                 let event_handled = core::cell::RefCell::new(false);
612                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
613
614                 let payment_preimage = PaymentPreimage([1; 32]);
615                 let invoice = invoice(payment_preimage);
616                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
617                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
618
619                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
620                 let router = TestRouter {};
621                 let scorer = RefCell::new(TestScorer::new());
622                 let logger = TestLogger::new();
623                 let invoice_payer =
624                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
625
626                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
627                 assert_eq!(*payer.attempts.borrow(), 1);
628
629                 invoice_payer.handle_event(&Event::PaymentSent {
630                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
631                 });
632                 assert_eq!(*event_handled.borrow(), true);
633                 assert_eq!(*payer.attempts.borrow(), 1);
634         }
635
636         #[test]
637         fn pays_invoice_on_retry() {
638                 let event_handled = core::cell::RefCell::new(false);
639                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
640
641                 let payment_preimage = PaymentPreimage([1; 32]);
642                 let invoice = invoice(payment_preimage);
643                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
644                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
645
646                 let payer = TestPayer::new()
647                         .expect_send(Amount::ForInvoice(final_value_msat))
648                         .expect_send(Amount::OnRetry(final_value_msat / 2));
649                 let router = TestRouter {};
650                 let scorer = RefCell::new(TestScorer::new());
651                 let logger = TestLogger::new();
652                 let invoice_payer =
653                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
654
655                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
656                 assert_eq!(*payer.attempts.borrow(), 1);
657
658                 let event = Event::PaymentPathFailed {
659                         payment_id,
660                         payment_hash,
661                         network_update: None,
662                         rejected_by_dest: false,
663                         all_paths_failed: false,
664                         path: TestRouter::path_for_value(final_value_msat),
665                         short_channel_id: None,
666                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
667                 };
668                 invoice_payer.handle_event(&event);
669                 assert_eq!(*event_handled.borrow(), false);
670                 assert_eq!(*payer.attempts.borrow(), 2);
671
672                 invoice_payer.handle_event(&Event::PaymentSent {
673                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
674                 });
675                 assert_eq!(*event_handled.borrow(), true);
676                 assert_eq!(*payer.attempts.borrow(), 2);
677         }
678
679         #[test]
680         fn pays_invoice_on_partial_failure() {
681                 let event_handler = |_: &_| { panic!() };
682
683                 let payment_preimage = PaymentPreimage([1; 32]);
684                 let invoice = invoice(payment_preimage);
685                 let retry = TestRouter::retry_for_invoice(&invoice);
686                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
687
688                 let payer = TestPayer::new()
689                         .fails_with_partial_failure(retry.clone(), OnAttempt(1))
690                         .fails_with_partial_failure(retry, OnAttempt(2))
691                         .expect_send(Amount::ForInvoice(final_value_msat))
692                         .expect_send(Amount::OnRetry(final_value_msat / 2))
693                         .expect_send(Amount::OnRetry(final_value_msat / 2));
694                 let router = TestRouter {};
695                 let scorer = RefCell::new(TestScorer::new());
696                 let logger = TestLogger::new();
697                 let invoice_payer =
698                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
699
700                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
701         }
702
703         #[test]
704         fn retries_payment_path_for_unknown_payment() {
705                 let event_handled = core::cell::RefCell::new(false);
706                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
707
708                 let payment_preimage = PaymentPreimage([1; 32]);
709                 let invoice = invoice(payment_preimage);
710                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
711                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
712
713                 let payer = TestPayer::new()
714                         .expect_send(Amount::OnRetry(final_value_msat / 2))
715                         .expect_send(Amount::OnRetry(final_value_msat / 2));
716                 let router = TestRouter {};
717                 let scorer = RefCell::new(TestScorer::new());
718                 let logger = TestLogger::new();
719                 let invoice_payer =
720                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
721
722                 let payment_id = Some(PaymentId([1; 32]));
723                 let event = Event::PaymentPathFailed {
724                         payment_id,
725                         payment_hash,
726                         network_update: None,
727                         rejected_by_dest: false,
728                         all_paths_failed: false,
729                         path: TestRouter::path_for_value(final_value_msat),
730                         short_channel_id: None,
731                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
732                 };
733                 invoice_payer.handle_event(&event);
734                 assert_eq!(*event_handled.borrow(), false);
735                 assert_eq!(*payer.attempts.borrow(), 1);
736
737                 invoice_payer.handle_event(&event);
738                 assert_eq!(*event_handled.borrow(), false);
739                 assert_eq!(*payer.attempts.borrow(), 2);
740
741                 invoice_payer.handle_event(&Event::PaymentSent {
742                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
743                 });
744                 assert_eq!(*event_handled.borrow(), true);
745                 assert_eq!(*payer.attempts.borrow(), 2);
746         }
747
748         #[test]
749         fn fails_paying_invoice_after_max_retries() {
750                 let event_handled = core::cell::RefCell::new(false);
751                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
752
753                 let payment_preimage = PaymentPreimage([1; 32]);
754                 let invoice = invoice(payment_preimage);
755                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
756
757                 let payer = TestPayer::new()
758                         .expect_send(Amount::ForInvoice(final_value_msat))
759                         .expect_send(Amount::OnRetry(final_value_msat / 2))
760                         .expect_send(Amount::OnRetry(final_value_msat / 2));
761                 let router = TestRouter {};
762                 let scorer = RefCell::new(TestScorer::new());
763                 let logger = TestLogger::new();
764                 let invoice_payer =
765                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
766
767                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
768                 assert_eq!(*payer.attempts.borrow(), 1);
769
770                 let event = Event::PaymentPathFailed {
771                         payment_id,
772                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
773                         network_update: None,
774                         rejected_by_dest: false,
775                         all_paths_failed: true,
776                         path: TestRouter::path_for_value(final_value_msat),
777                         short_channel_id: None,
778                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
779                 };
780                 invoice_payer.handle_event(&event);
781                 assert_eq!(*event_handled.borrow(), false);
782                 assert_eq!(*payer.attempts.borrow(), 2);
783
784                 let event = Event::PaymentPathFailed {
785                         payment_id,
786                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
787                         network_update: None,
788                         rejected_by_dest: false,
789                         all_paths_failed: false,
790                         path: TestRouter::path_for_value(final_value_msat / 2),
791                         short_channel_id: None,
792                         retry: Some(RouteParameters {
793                                 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
794                         }),
795                 };
796                 invoice_payer.handle_event(&event);
797                 assert_eq!(*event_handled.borrow(), false);
798                 assert_eq!(*payer.attempts.borrow(), 3);
799
800                 invoice_payer.handle_event(&event);
801                 assert_eq!(*event_handled.borrow(), true);
802                 assert_eq!(*payer.attempts.borrow(), 3);
803         }
804
805         #[test]
806         fn fails_paying_invoice_with_missing_retry_params() {
807                 let event_handled = core::cell::RefCell::new(false);
808                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
809
810                 let payment_preimage = PaymentPreimage([1; 32]);
811                 let invoice = invoice(payment_preimage);
812                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
813
814                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
815                 let router = TestRouter {};
816                 let scorer = RefCell::new(TestScorer::new());
817                 let logger = TestLogger::new();
818                 let invoice_payer =
819                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
820
821                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
822                 assert_eq!(*payer.attempts.borrow(), 1);
823
824                 let event = Event::PaymentPathFailed {
825                         payment_id,
826                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
827                         network_update: None,
828                         rejected_by_dest: false,
829                         all_paths_failed: false,
830                         path: vec![],
831                         short_channel_id: None,
832                         retry: None,
833                 };
834                 invoice_payer.handle_event(&event);
835                 assert_eq!(*event_handled.borrow(), true);
836                 assert_eq!(*payer.attempts.borrow(), 1);
837         }
838
839         // Expiration is checked only in an std environment
840         #[cfg(feature = "std")]
841         #[test]
842         fn fails_paying_invoice_after_expiration() {
843                 let event_handled = core::cell::RefCell::new(false);
844                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
845
846                 let payer = TestPayer::new();
847                 let router = TestRouter {};
848                 let scorer = RefCell::new(TestScorer::new());
849                 let logger = TestLogger::new();
850                 let invoice_payer =
851                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
852
853                 let payment_preimage = PaymentPreimage([1; 32]);
854                 let invoice = expired_invoice(payment_preimage);
855                 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
856                         assert_eq!(msg, "Invoice expired prior to send");
857                 } else { panic!("Expected Invoice Error"); }
858         }
859
860         // Expiration is checked only in an std environment
861         #[cfg(feature = "std")]
862         #[test]
863         fn fails_retrying_invoice_after_expiration() {
864                 let event_handled = core::cell::RefCell::new(false);
865                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
866
867                 let payment_preimage = PaymentPreimage([1; 32]);
868                 let invoice = invoice(payment_preimage);
869                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
870
871                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
872                 let router = TestRouter {};
873                 let scorer = RefCell::new(TestScorer::new());
874                 let logger = TestLogger::new();
875                 let invoice_payer =
876                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
877
878                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
879                 assert_eq!(*payer.attempts.borrow(), 1);
880
881                 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
882                 retry_data.payment_params.expiry_time = Some(SystemTime::now()
883                         .checked_sub(Duration::from_secs(2)).unwrap()
884                         .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
885                 let event = Event::PaymentPathFailed {
886                         payment_id,
887                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
888                         network_update: None,
889                         rejected_by_dest: false,
890                         all_paths_failed: false,
891                         path: vec![],
892                         short_channel_id: None,
893                         retry: Some(retry_data),
894                 };
895                 invoice_payer.handle_event(&event);
896                 assert_eq!(*event_handled.borrow(), true);
897                 assert_eq!(*payer.attempts.borrow(), 1);
898         }
899
900         #[test]
901         fn fails_paying_invoice_after_retry_error() {
902                 let event_handled = core::cell::RefCell::new(false);
903                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
904
905                 let payment_preimage = PaymentPreimage([1; 32]);
906                 let invoice = invoice(payment_preimage);
907                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
908
909                 let payer = TestPayer::new()
910                         .fails_on_attempt(2)
911                         .expect_send(Amount::ForInvoice(final_value_msat))
912                         .expect_send(Amount::OnRetry(final_value_msat / 2));
913                 let router = TestRouter {};
914                 let scorer = RefCell::new(TestScorer::new());
915                 let logger = TestLogger::new();
916                 let invoice_payer =
917                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
918
919                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
920                 assert_eq!(*payer.attempts.borrow(), 1);
921
922                 let event = Event::PaymentPathFailed {
923                         payment_id,
924                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
925                         network_update: None,
926                         rejected_by_dest: false,
927                         all_paths_failed: false,
928                         path: TestRouter::path_for_value(final_value_msat / 2),
929                         short_channel_id: None,
930                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
931                 };
932                 invoice_payer.handle_event(&event);
933                 assert_eq!(*event_handled.borrow(), true);
934                 assert_eq!(*payer.attempts.borrow(), 2);
935         }
936
937         #[test]
938         fn fails_paying_invoice_after_rejected_by_payee() {
939                 let event_handled = core::cell::RefCell::new(false);
940                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
941
942                 let payment_preimage = PaymentPreimage([1; 32]);
943                 let invoice = invoice(payment_preimage);
944                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
945
946                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
947                 let router = TestRouter {};
948                 let scorer = RefCell::new(TestScorer::new());
949                 let logger = TestLogger::new();
950                 let invoice_payer =
951                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
952
953                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
954                 assert_eq!(*payer.attempts.borrow(), 1);
955
956                 let event = Event::PaymentPathFailed {
957                         payment_id,
958                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
959                         network_update: None,
960                         rejected_by_dest: true,
961                         all_paths_failed: false,
962                         path: vec![],
963                         short_channel_id: None,
964                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
965                 };
966                 invoice_payer.handle_event(&event);
967                 assert_eq!(*event_handled.borrow(), true);
968                 assert_eq!(*payer.attempts.borrow(), 1);
969         }
970
971         #[test]
972         fn fails_repaying_invoice_with_pending_payment() {
973                 let event_handled = core::cell::RefCell::new(false);
974                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
975
976                 let payment_preimage = PaymentPreimage([1; 32]);
977                 let invoice = invoice(payment_preimage);
978                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
979
980                 let payer = TestPayer::new()
981                         .expect_send(Amount::ForInvoice(final_value_msat))
982                         .expect_send(Amount::ForInvoice(final_value_msat));
983                 let router = TestRouter {};
984                 let scorer = RefCell::new(TestScorer::new());
985                 let logger = TestLogger::new();
986                 let invoice_payer =
987                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
988
989                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
990
991                 // Cannot repay an invoice pending payment.
992                 match invoice_payer.pay_invoice(&invoice) {
993                         Err(PaymentError::Invoice("payment pending")) => {},
994                         Err(_) => panic!("unexpected error"),
995                         Ok(_) => panic!("expected invoice error"),
996                 }
997
998                 // Can repay an invoice once cleared from cache.
999                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1000                 invoice_payer.remove_cached_payment(&payment_hash);
1001                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1002
1003                 // Cannot retry paying an invoice if cleared from cache.
1004                 invoice_payer.remove_cached_payment(&payment_hash);
1005                 let event = Event::PaymentPathFailed {
1006                         payment_id,
1007                         payment_hash,
1008                         network_update: None,
1009                         rejected_by_dest: false,
1010                         all_paths_failed: false,
1011                         path: vec![],
1012                         short_channel_id: None,
1013                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1014                 };
1015                 invoice_payer.handle_event(&event);
1016                 assert_eq!(*event_handled.borrow(), true);
1017         }
1018
1019         #[test]
1020         fn fails_paying_invoice_with_routing_errors() {
1021                 let payer = TestPayer::new();
1022                 let router = FailingRouter {};
1023                 let scorer = RefCell::new(TestScorer::new());
1024                 let logger = TestLogger::new();
1025                 let invoice_payer =
1026                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1027
1028                 let payment_preimage = PaymentPreimage([1; 32]);
1029                 let invoice = invoice(payment_preimage);
1030                 match invoice_payer.pay_invoice(&invoice) {
1031                         Err(PaymentError::Routing(_)) => {},
1032                         Err(_) => panic!("unexpected error"),
1033                         Ok(_) => panic!("expected routing error"),
1034                 }
1035         }
1036
1037         #[test]
1038         fn fails_paying_invoice_with_sending_errors() {
1039                 let payment_preimage = PaymentPreimage([1; 32]);
1040                 let invoice = invoice(payment_preimage);
1041                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1042
1043                 let payer = TestPayer::new()
1044                         .fails_on_attempt(1)
1045                         .expect_send(Amount::ForInvoice(final_value_msat));
1046                 let router = TestRouter {};
1047                 let scorer = RefCell::new(TestScorer::new());
1048                 let logger = TestLogger::new();
1049                 let invoice_payer =
1050                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1051
1052                 match invoice_payer.pay_invoice(&invoice) {
1053                         Err(PaymentError::Sending(_)) => {},
1054                         Err(_) => panic!("unexpected error"),
1055                         Ok(_) => panic!("expected sending error"),
1056                 }
1057         }
1058
1059         #[test]
1060         fn pays_zero_value_invoice_using_amount() {
1061                 let event_handled = core::cell::RefCell::new(false);
1062                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1063
1064                 let payment_preimage = PaymentPreimage([1; 32]);
1065                 let invoice = zero_value_invoice(payment_preimage);
1066                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1067                 let final_value_msat = 100;
1068
1069                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1070                 let router = TestRouter {};
1071                 let scorer = RefCell::new(TestScorer::new());
1072                 let logger = TestLogger::new();
1073                 let invoice_payer =
1074                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1075
1076                 let payment_id =
1077                         Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1078                 assert_eq!(*payer.attempts.borrow(), 1);
1079
1080                 invoice_payer.handle_event(&Event::PaymentSent {
1081                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1082                 });
1083                 assert_eq!(*event_handled.borrow(), true);
1084                 assert_eq!(*payer.attempts.borrow(), 1);
1085         }
1086
1087         #[test]
1088         fn fails_paying_zero_value_invoice_with_amount() {
1089                 let event_handled = core::cell::RefCell::new(false);
1090                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1091
1092                 let payer = TestPayer::new();
1093                 let router = TestRouter {};
1094                 let scorer = RefCell::new(TestScorer::new());
1095                 let logger = TestLogger::new();
1096                 let invoice_payer =
1097                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1098
1099                 let payment_preimage = PaymentPreimage([1; 32]);
1100                 let invoice = invoice(payment_preimage);
1101
1102                 // Cannot repay an invoice pending payment.
1103                 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1104                         Err(PaymentError::Invoice("amount unexpected")) => {},
1105                         Err(_) => panic!("unexpected error"),
1106                         Ok(_) => panic!("expected invoice error"),
1107                 }
1108         }
1109
1110         #[test]
1111         fn pays_pubkey_with_amount() {
1112                 let event_handled = core::cell::RefCell::new(false);
1113                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1114
1115                 let pubkey = pubkey();
1116                 let payment_preimage = PaymentPreimage([1; 32]);
1117                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1118                 let final_value_msat = 100;
1119                 let final_cltv_expiry_delta = 42;
1120
1121                 let payer = TestPayer::new()
1122                         .expect_send(Amount::Spontaneous(final_value_msat))
1123                         .expect_send(Amount::OnRetry(final_value_msat));
1124                 let router = TestRouter {};
1125                 let scorer = RefCell::new(TestScorer::new());
1126                 let logger = TestLogger::new();
1127                 let invoice_payer =
1128                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1129
1130                 let payment_id = Some(invoice_payer.pay_pubkey(
1131                                 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1132                         ).unwrap());
1133                 assert_eq!(*payer.attempts.borrow(), 1);
1134
1135                 let retry = RouteParameters {
1136                         payment_params: PaymentParameters::for_keysend(pubkey),
1137                         final_value_msat,
1138                         final_cltv_expiry_delta,
1139                 };
1140                 let event = Event::PaymentPathFailed {
1141                         payment_id,
1142                         payment_hash,
1143                         network_update: None,
1144                         rejected_by_dest: false,
1145                         all_paths_failed: false,
1146                         path: vec![],
1147                         short_channel_id: None,
1148                         retry: Some(retry),
1149                 };
1150                 invoice_payer.handle_event(&event);
1151                 assert_eq!(*event_handled.borrow(), false);
1152                 assert_eq!(*payer.attempts.borrow(), 2);
1153
1154                 invoice_payer.handle_event(&Event::PaymentSent {
1155                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1156                 });
1157                 assert_eq!(*event_handled.borrow(), true);
1158                 assert_eq!(*payer.attempts.borrow(), 2);
1159         }
1160
1161         #[test]
1162         fn scores_failed_channel() {
1163                 let event_handled = core::cell::RefCell::new(false);
1164                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1165
1166                 let payment_preimage = PaymentPreimage([1; 32]);
1167                 let invoice = invoice(payment_preimage);
1168                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1169                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1170                 let path = TestRouter::path_for_value(final_value_msat);
1171                 let short_channel_id = Some(path[0].short_channel_id);
1172
1173                 // Expect that scorer is given short_channel_id upon handling the event.
1174                 let payer = TestPayer::new()
1175                         .expect_send(Amount::ForInvoice(final_value_msat))
1176                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1177                 let router = TestRouter {};
1178                 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1179                         path: path.clone(), short_channel_id: path[0].short_channel_id,
1180                 }));
1181                 let logger = TestLogger::new();
1182                 let invoice_payer =
1183                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1184
1185                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1186                 let event = Event::PaymentPathFailed {
1187                         payment_id,
1188                         payment_hash,
1189                         network_update: None,
1190                         rejected_by_dest: false,
1191                         all_paths_failed: false,
1192                         path,
1193                         short_channel_id,
1194                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1195                 };
1196                 invoice_payer.handle_event(&event);
1197         }
1198
1199         #[test]
1200         fn scores_successful_channels() {
1201                 let event_handled = core::cell::RefCell::new(false);
1202                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1203
1204                 let payment_preimage = PaymentPreimage([1; 32]);
1205                 let invoice = invoice(payment_preimage);
1206                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1207                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1208                 let route = TestRouter::route_for_value(final_value_msat);
1209
1210                 // Expect that scorer is given short_channel_id upon handling the event.
1211                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1212                 let router = TestRouter {};
1213                 let scorer = RefCell::new(TestScorer::new()
1214                         .expect(PaymentPath::Success { path: route.paths[0].clone() })
1215                         .expect(PaymentPath::Success { path: route.paths[1].clone() })
1216                 );
1217                 let logger = TestLogger::new();
1218                 let invoice_payer =
1219                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1220
1221                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1222                 let event = Event::PaymentPathSuccessful {
1223                         payment_id, payment_hash, path: route.paths[0].clone()
1224                 };
1225                 invoice_payer.handle_event(&event);
1226                 let event = Event::PaymentPathSuccessful {
1227                         payment_id, payment_hash, path: route.paths[1].clone()
1228                 };
1229                 invoice_payer.handle_event(&event);
1230         }
1231
1232         struct TestRouter;
1233
1234         impl TestRouter {
1235                 fn route_for_value(final_value_msat: u64) -> Route {
1236                         Route {
1237                                 paths: vec![
1238                                         vec![RouteHop {
1239                                                 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1240                                                 channel_features: ChannelFeatures::empty(),
1241                                                 node_features: NodeFeatures::empty(),
1242                                                 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1243                                         }],
1244                                         vec![RouteHop {
1245                                                 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1246                                                 channel_features: ChannelFeatures::empty(),
1247                                                 node_features: NodeFeatures::empty(),
1248                                                 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1249                                         }],
1250                                 ],
1251                                 payment_params: None,
1252                         }
1253                 }
1254
1255                 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1256                         TestRouter::route_for_value(final_value_msat).paths[0].clone()
1257                 }
1258
1259                 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1260                         let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1261                                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1262                                 .with_route_hints(invoice.route_hints());
1263                         if let Some(features) = invoice.features() {
1264                                 payment_params = payment_params.with_features(features.clone());
1265                         }
1266                         let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1267                         RouteParameters {
1268                                 payment_params,
1269                                 final_value_msat,
1270                                 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1271                         }
1272                 }
1273         }
1274
1275         impl<S: Score> Router<S> for TestRouter {
1276                 fn find_route(
1277                         &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1278                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1279                 ) -> Result<Route, LightningError> {
1280                         Ok(Route {
1281                                 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1282                         })
1283                 }
1284         }
1285
1286         struct FailingRouter;
1287
1288         impl<S: Score> Router<S> for FailingRouter {
1289                 fn find_route(
1290                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1291                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1292                 ) -> Result<Route, LightningError> {
1293                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1294                 }
1295         }
1296
1297         struct TestScorer {
1298                 expectations: Option<VecDeque<PaymentPath>>,
1299         }
1300
1301         #[derive(Debug)]
1302         enum PaymentPath {
1303                 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1304                 Success { path: Vec<RouteHop> },
1305         }
1306
1307         impl TestScorer {
1308                 fn new() -> Self {
1309                         Self {
1310                                 expectations: None,
1311                         }
1312                 }
1313
1314                 fn expect(mut self, expectation: PaymentPath) -> Self {
1315                         self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1316                         self
1317                 }
1318         }
1319
1320         #[cfg(c_bindings)]
1321         impl lightning::util::ser::Writeable for TestScorer {
1322                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1323         }
1324
1325         impl Score for TestScorer {
1326                 fn channel_penalty_msat(
1327                         &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
1328                 ) -> u64 { 0 }
1329
1330                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1331                         if let Some(expectations) = &mut self.expectations {
1332                                 match expectations.pop_front() {
1333                                         Some(PaymentPath::Failure { path, short_channel_id }) => {
1334                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1335                                                 assert_eq!(actual_short_channel_id, short_channel_id);
1336                                         },
1337                                         Some(PaymentPath::Success { path }) => {
1338                                                 panic!("Unexpected successful payment path: {:?}", path)
1339                                         },
1340                                         None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1341                                 }
1342                         }
1343                 }
1344
1345                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1346                         if let Some(expectations) = &mut self.expectations {
1347                                 match expectations.pop_front() {
1348                                         Some(PaymentPath::Failure { path, .. }) => {
1349                                                 panic!("Unexpected payment path failure: {:?}", path)
1350                                         },
1351                                         Some(PaymentPath::Success { path }) => {
1352                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1353                                         },
1354                                         None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1355                                 }
1356                         }
1357                 }
1358         }
1359
1360         impl Drop for TestScorer {
1361                 fn drop(&mut self) {
1362                         if std::thread::panicking() {
1363                                 return;
1364                         }
1365
1366                         if let Some(expectations) = &self.expectations {
1367                                 if !expectations.is_empty() {
1368                                         panic!("Unsatisfied scorer expectations: {:?}", expectations);
1369                                 }
1370                         }
1371                 }
1372         }
1373
1374         struct TestPayer {
1375                 expectations: core::cell::RefCell<VecDeque<Amount>>,
1376                 attempts: core::cell::RefCell<usize>,
1377                 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1378         }
1379
1380         #[derive(Clone, Debug, PartialEq, Eq)]
1381         enum Amount {
1382                 ForInvoice(u64),
1383                 Spontaneous(u64),
1384                 OnRetry(u64),
1385         }
1386
1387         struct OnAttempt(usize);
1388
1389         impl TestPayer {
1390                 fn new() -> Self {
1391                         Self {
1392                                 expectations: core::cell::RefCell::new(VecDeque::new()),
1393                                 attempts: core::cell::RefCell::new(0),
1394                                 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1395                         }
1396                 }
1397
1398                 fn expect_send(self, value_msat: Amount) -> Self {
1399                         self.expectations.borrow_mut().push_back(value_msat);
1400                         self
1401                 }
1402
1403                 fn fails_on_attempt(self, attempt: usize) -> Self {
1404                         let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1405                         self.fails_with(failure, OnAttempt(attempt))
1406                 }
1407
1408                 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1409                         self.fails_with(PaymentSendFailure::PartialFailure {
1410                                 results: vec![],
1411                                 failed_paths_retry: Some(retry),
1412                                 payment_id: PaymentId([1; 32]),
1413                         }, attempt)
1414                 }
1415
1416                 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1417                         self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1418                         self
1419                 }
1420
1421                 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1422                         let mut attempts = self.attempts.borrow_mut();
1423                         *attempts += 1;
1424
1425                         match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1426                                 Some(failure) => Err(failure),
1427                                 None => Ok(PaymentId([1; 32])),
1428                         }
1429                 }
1430
1431                 fn check_value_msats(&self, actual_value_msats: Amount) {
1432                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
1433                         if let Some(expected_value_msats) = expected_value_msats {
1434                                 assert_eq!(actual_value_msats, expected_value_msats);
1435                         } else {
1436                                 panic!("Unexpected amount: {:?}", actual_value_msats);
1437                         }
1438                 }
1439         }
1440
1441         impl Drop for TestPayer {
1442                 fn drop(&mut self) {
1443                         if std::thread::panicking() {
1444                                 return;
1445                         }
1446
1447                         if !self.expectations.borrow().is_empty() {
1448                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1449                         }
1450                 }
1451         }
1452
1453         impl Payer for TestPayer {
1454                 fn node_id(&self) -> PublicKey {
1455                         let secp_ctx = Secp256k1::new();
1456                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1457                 }
1458
1459                 fn first_hops(&self) -> Vec<ChannelDetails> {
1460                         Vec::new()
1461                 }
1462
1463                 fn send_payment(
1464                         &self, route: &Route, _payment_hash: PaymentHash,
1465                         _payment_secret: &Option<PaymentSecret>
1466                 ) -> Result<PaymentId, PaymentSendFailure> {
1467                         self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1468                         self.check_attempts()
1469                 }
1470
1471                 fn send_spontaneous_payment(
1472                         &self, route: &Route, _payment_preimage: PaymentPreimage,
1473                 ) -> Result<PaymentId, PaymentSendFailure> {
1474                         self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1475                         self.check_attempts()
1476                 }
1477
1478                 fn retry_payment(
1479                         &self, route: &Route, _payment_id: PaymentId
1480                 ) -> Result<(), PaymentSendFailure> {
1481                         self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1482                         self.check_attempts().map(|_| ())
1483                 }
1484
1485                 fn abandon_payment(&self, _payment_id: PaymentId) { }
1486         }
1487
1488         // *** Full Featured Functional Tests with a Real ChannelManager ***
1489         struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1490
1491         impl<S: Score> Router<S> for ManualRouter {
1492                 fn find_route(
1493                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1494                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1495                 ) -> Result<Route, LightningError> {
1496                         self.0.borrow_mut().pop_front().unwrap()
1497                 }
1498         }
1499         impl ManualRouter {
1500                 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1501                         self.0.borrow_mut().push_back(result);
1502                 }
1503         }
1504         impl Drop for ManualRouter {
1505                 fn drop(&mut self) {
1506                         if std::thread::panicking() {
1507                                 return;
1508                         }
1509                         assert!(self.0.borrow_mut().is_empty());
1510                 }
1511         }
1512
1513         #[test]
1514         fn retry_multi_path_single_failed_payment() {
1515                 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1516                 let chanmon_cfgs = create_chanmon_cfgs(2);
1517                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1519                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1520
1521                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1522                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1523                 let chans = nodes[0].node.list_usable_channels();
1524                 let mut route = Route {
1525                         paths: vec![
1526                                 vec![RouteHop {
1527                                         pubkey: nodes[1].node.get_our_node_id(),
1528                                         node_features: NodeFeatures::known(),
1529                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1530                                         channel_features: ChannelFeatures::known(),
1531                                         fee_msat: 10_000,
1532                                         cltv_expiry_delta: 100,
1533                                 }],
1534                                 vec![RouteHop {
1535                                         pubkey: nodes[1].node.get_our_node_id(),
1536                                         node_features: NodeFeatures::known(),
1537                                         short_channel_id: chans[1].short_channel_id.unwrap(),
1538                                         channel_features: ChannelFeatures::known(),
1539                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1540                                         cltv_expiry_delta: 100,
1541                                 }],
1542                         ],
1543                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1544                 };
1545                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1546                 router.expect_find_route(Ok(route.clone()));
1547                 // On retry, split the payment across both channels.
1548                 route.paths[0][0].fee_msat = 50_000_001;
1549                 route.paths[1][0].fee_msat = 50_000_000;
1550                 router.expect_find_route(Ok(route.clone()));
1551
1552                 let event_handler = |_: &_| { panic!(); };
1553                 let scorer = RefCell::new(TestScorer::new());
1554                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1555
1556                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1557                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1558                         duration_since_epoch()).unwrap())
1559                         .is_ok());
1560                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1561                 assert_eq!(htlc_msgs.len(), 2);
1562                 check_added_monitors!(nodes[0], 2);
1563         }
1564
1565         #[test]
1566         fn immediate_retry_on_failure() {
1567                 // Tests that we can/will retry immediately after a failure
1568                 let chanmon_cfgs = create_chanmon_cfgs(2);
1569                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1571                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572
1573                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1574                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1575                 let chans = nodes[0].node.list_usable_channels();
1576                 let mut route = Route {
1577                         paths: vec![
1578                                 vec![RouteHop {
1579                                         pubkey: nodes[1].node.get_our_node_id(),
1580                                         node_features: NodeFeatures::known(),
1581                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1582                                         channel_features: ChannelFeatures::known(),
1583                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1584                                         cltv_expiry_delta: 100,
1585                                 }],
1586                         ],
1587                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1588                 };
1589                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1590                 router.expect_find_route(Ok(route.clone()));
1591                 // On retry, split the payment across both channels.
1592                 route.paths.push(route.paths[0].clone());
1593                 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1594                 route.paths[0][0].fee_msat = 50_000_000;
1595                 route.paths[1][0].fee_msat = 50_000_001;
1596                 router.expect_find_route(Ok(route.clone()));
1597
1598                 let event_handler = |_: &_| { panic!(); };
1599                 let scorer = RefCell::new(TestScorer::new());
1600                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1601
1602                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1603                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1604                         duration_since_epoch()).unwrap())
1605                         .is_ok());
1606                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1607                 assert_eq!(htlc_msgs.len(), 2);
1608                 check_added_monitors!(nodes[0], 2);
1609         }
1610
1611         #[test]
1612         fn no_extra_retries_on_back_to_back_fail() {
1613                 // In a previous release, we had a race where we may exceed the payment retry count if we
1614                 // get two failures in a row with the second having `all_paths_failed` set.
1615                 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1616                 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1617                 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1618                 // pending which we will see later. Thus, when we previously removed the retry tracking map
1619                 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1620                 // retry entry even though more events for the same payment were still pending. This led to
1621                 // us retrying a payment again even though we'd already given up on it.
1622                 //
1623                 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1624                 // is used to remove the payment retry counter entries instead. This tests for the specific
1625                 // excess-retry case while also testing `PaymentFailed` generation.
1626
1627                 let chanmon_cfgs = create_chanmon_cfgs(3);
1628                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1629                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1630                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1631
1632                 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1633                 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1634
1635                 let mut route = Route {
1636                         paths: vec![
1637                                 vec![RouteHop {
1638                                         pubkey: nodes[1].node.get_our_node_id(),
1639                                         node_features: NodeFeatures::known(),
1640                                         short_channel_id: chan_1_scid,
1641                                         channel_features: ChannelFeatures::known(),
1642                                         fee_msat: 0,
1643                                         cltv_expiry_delta: 100,
1644                                 }, RouteHop {
1645                                         pubkey: nodes[2].node.get_our_node_id(),
1646                                         node_features: NodeFeatures::known(),
1647                                         short_channel_id: chan_2_scid,
1648                                         channel_features: ChannelFeatures::known(),
1649                                         fee_msat: 100_000_000,
1650                                         cltv_expiry_delta: 100,
1651                                 }],
1652                                 vec![RouteHop {
1653                                         pubkey: nodes[1].node.get_our_node_id(),
1654                                         node_features: NodeFeatures::known(),
1655                                         short_channel_id: chan_1_scid,
1656                                         channel_features: ChannelFeatures::known(),
1657                                         fee_msat: 0,
1658                                         cltv_expiry_delta: 100,
1659                                 }, RouteHop {
1660                                         pubkey: nodes[2].node.get_our_node_id(),
1661                                         node_features: NodeFeatures::known(),
1662                                         short_channel_id: chan_2_scid,
1663                                         channel_features: ChannelFeatures::known(),
1664                                         fee_msat: 100_000_000,
1665                                         cltv_expiry_delta: 100,
1666                                 }]
1667                         ],
1668                         payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1669                 };
1670                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1671                 router.expect_find_route(Ok(route.clone()));
1672                 // On retry, we'll only be asked for one path
1673                 route.paths.remove(1);
1674                 router.expect_find_route(Ok(route.clone()));
1675
1676                 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1677                 let event_handler = |event: &Event| {
1678                         let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1679                         event_checker(event);
1680                 };
1681                 let scorer = RefCell::new(TestScorer::new());
1682                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1683
1684                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1685                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1686                         duration_since_epoch()).unwrap())
1687                         .is_ok());
1688                 let htlc_updates = SendEvent::from_node(&nodes[0]);
1689                 check_added_monitors!(nodes[0], 1);
1690                 assert_eq!(htlc_updates.msgs.len(), 1);
1691
1692                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1693                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1694                 check_added_monitors!(nodes[1], 1);
1695                 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1696
1697                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1698                 check_added_monitors!(nodes[0], 1);
1699                 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1700
1701                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1702                 check_added_monitors!(nodes[0], 1);
1703                 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1704
1705                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1706                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1707                 check_added_monitors!(nodes[1], 1);
1708                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1709
1710                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1711                 check_added_monitors!(nodes[1], 1);
1712                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1713
1714                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1715                 check_added_monitors!(nodes[0], 1);
1716
1717                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1718                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1719                 check_added_monitors!(nodes[0], 1);
1720                 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1721
1722                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1723                 check_added_monitors!(nodes[1], 1);
1724                 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1725
1726                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1727                 check_added_monitors!(nodes[1], 1);
1728                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1729
1730                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1731                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1732                 check_added_monitors!(nodes[0], 1);
1733
1734                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1735                 check_added_monitors!(nodes[0], 1);
1736                 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1737
1738                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1739                 check_added_monitors!(nodes[1], 1);
1740                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1741                 check_added_monitors!(nodes[1], 1);
1742                 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1743
1744                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1745                 check_added_monitors!(nodes[0], 1);
1746
1747                 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1748                 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1749                 // with it set. The first event will use up the only retry we are allowed, with the second
1750                 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1751                 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1752                 // if the final HTLC failed.
1753                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1754                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1755                                 assert!(!rejected_by_dest);
1756                                 assert!(all_paths_failed);
1757                         } else { panic!("Unexpected event"); }
1758                 });
1759                 nodes[0].node.process_pending_events(&invoice_payer);
1760                 assert!(expected_events.borrow().is_empty());
1761
1762                 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1763                 check_added_monitors!(nodes[0], 1);
1764
1765                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1766                 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1767                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1768                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1769                 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1770
1771                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1772                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1773                                 assert!(!rejected_by_dest);
1774                                 assert!(all_paths_failed);
1775                         } else { panic!("Unexpected event"); }
1776                 });
1777                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1778                         if let Event::PaymentFailed { .. } = ev {
1779                         } else { panic!("Unexpected event"); }
1780                 });
1781                 nodes[0].node.process_pending_events(&invoice_payer);
1782                 assert!(expected_events.borrow().is_empty());
1783         }
1784 }