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