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