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