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