Pass effective capacity to scorer
[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::network_graph::NodeId;
42 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
43 //! # use lightning::routing::scoring::{ChannelUsage, Score};
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, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
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::routing::scoring::ChannelUsage;
608         use lightning::util::test_utils::TestLogger;
609         use lightning::util::errors::APIError;
610         use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
611         use secp256k1::{SecretKey, PublicKey, Secp256k1};
612         use std::cell::RefCell;
613         use std::collections::VecDeque;
614         use std::time::{SystemTime, Duration};
615         use time_utils::tests::SinceEpoch;
616         use DEFAULT_EXPIRY_TIME;
617
618         fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
619                 let payment_hash = Sha256::hash(&payment_preimage.0);
620                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
621
622                 InvoiceBuilder::new(Currency::Bitcoin)
623                         .description("test".into())
624                         .payment_hash(payment_hash)
625                         .payment_secret(PaymentSecret([0; 32]))
626                         .duration_since_epoch(duration_since_epoch())
627                         .min_final_cltv_expiry(144)
628                         .amount_milli_satoshis(128)
629                         .build_signed(|hash| {
630                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
631                         })
632                         .unwrap()
633         }
634
635         fn duration_since_epoch() -> Duration {
636                 #[cfg(feature = "std")]
637                         let duration_since_epoch =
638                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
639                 #[cfg(not(feature = "std"))]
640                         let duration_since_epoch = Duration::from_secs(1234567);
641                 duration_since_epoch
642         }
643
644         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
645                 let payment_hash = Sha256::hash(&payment_preimage.0);
646                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
647
648                 InvoiceBuilder::new(Currency::Bitcoin)
649                         .description("test".into())
650                         .payment_hash(payment_hash)
651                         .payment_secret(PaymentSecret([0; 32]))
652                         .duration_since_epoch(duration_since_epoch())
653                         .min_final_cltv_expiry(144)
654                         .build_signed(|hash| {
655                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
656                         })
657                         .unwrap()
658         }
659
660         #[cfg(feature = "std")]
661         fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
662                 let payment_hash = Sha256::hash(&payment_preimage.0);
663                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
664                 let duration = duration_since_epoch()
665                         .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
666                         .unwrap();
667                 InvoiceBuilder::new(Currency::Bitcoin)
668                         .description("test".into())
669                         .payment_hash(payment_hash)
670                         .payment_secret(PaymentSecret([0; 32]))
671                         .duration_since_epoch(duration)
672                         .min_final_cltv_expiry(144)
673                         .amount_milli_satoshis(128)
674                         .build_signed(|hash| {
675                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
676                         })
677                         .unwrap()
678         }
679
680         fn pubkey() -> PublicKey {
681                 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
682         }
683
684         #[test]
685         fn pays_invoice_on_first_attempt() {
686                 let event_handled = core::cell::RefCell::new(false);
687                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
688
689                 let payment_preimage = PaymentPreimage([1; 32]);
690                 let invoice = invoice(payment_preimage);
691                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
692                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
693
694                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
695                 let router = TestRouter {};
696                 let scorer = RefCell::new(TestScorer::new());
697                 let logger = TestLogger::new();
698                 let invoice_payer =
699                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
700
701                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
702                 assert_eq!(*payer.attempts.borrow(), 1);
703
704                 invoice_payer.handle_event(&Event::PaymentSent {
705                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
706                 });
707                 assert_eq!(*event_handled.borrow(), true);
708                 assert_eq!(*payer.attempts.borrow(), 1);
709         }
710
711         #[test]
712         fn pays_invoice_on_retry() {
713                 let event_handled = core::cell::RefCell::new(false);
714                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
715
716                 let payment_preimage = PaymentPreimage([1; 32]);
717                 let invoice = invoice(payment_preimage);
718                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
719                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
720
721                 let payer = TestPayer::new()
722                         .expect_send(Amount::ForInvoice(final_value_msat))
723                         .expect_send(Amount::OnRetry(final_value_msat / 2));
724                 let router = TestRouter {};
725                 let scorer = RefCell::new(TestScorer::new());
726                 let logger = TestLogger::new();
727                 let invoice_payer =
728                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
729
730                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
731                 assert_eq!(*payer.attempts.borrow(), 1);
732
733                 let event = Event::PaymentPathFailed {
734                         payment_id,
735                         payment_hash,
736                         network_update: None,
737                         rejected_by_dest: false,
738                         all_paths_failed: false,
739                         path: TestRouter::path_for_value(final_value_msat),
740                         short_channel_id: None,
741                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
742                 };
743                 invoice_payer.handle_event(&event);
744                 assert_eq!(*event_handled.borrow(), false);
745                 assert_eq!(*payer.attempts.borrow(), 2);
746
747                 invoice_payer.handle_event(&Event::PaymentSent {
748                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
749                 });
750                 assert_eq!(*event_handled.borrow(), true);
751                 assert_eq!(*payer.attempts.borrow(), 2);
752         }
753
754         #[test]
755         fn pays_invoice_on_partial_failure() {
756                 let event_handler = |_: &_| { panic!() };
757
758                 let payment_preimage = PaymentPreimage([1; 32]);
759                 let invoice = invoice(payment_preimage);
760                 let retry = TestRouter::retry_for_invoice(&invoice);
761                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
762
763                 let payer = TestPayer::new()
764                         .fails_with_partial_failure(retry.clone(), OnAttempt(1))
765                         .fails_with_partial_failure(retry, OnAttempt(2))
766                         .expect_send(Amount::ForInvoice(final_value_msat))
767                         .expect_send(Amount::OnRetry(final_value_msat / 2))
768                         .expect_send(Amount::OnRetry(final_value_msat / 2));
769                 let router = TestRouter {};
770                 let scorer = RefCell::new(TestScorer::new());
771                 let logger = TestLogger::new();
772                 let invoice_payer =
773                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
774
775                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
776         }
777
778         #[test]
779         fn retries_payment_path_for_unknown_payment() {
780                 let event_handled = core::cell::RefCell::new(false);
781                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
782
783                 let payment_preimage = PaymentPreimage([1; 32]);
784                 let invoice = invoice(payment_preimage);
785                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
786                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
787
788                 let payer = TestPayer::new()
789                         .expect_send(Amount::OnRetry(final_value_msat / 2))
790                         .expect_send(Amount::OnRetry(final_value_msat / 2));
791                 let router = TestRouter {};
792                 let scorer = RefCell::new(TestScorer::new());
793                 let logger = TestLogger::new();
794                 let invoice_payer =
795                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
796
797                 let payment_id = Some(PaymentId([1; 32]));
798                 let event = Event::PaymentPathFailed {
799                         payment_id,
800                         payment_hash,
801                         network_update: None,
802                         rejected_by_dest: false,
803                         all_paths_failed: false,
804                         path: TestRouter::path_for_value(final_value_msat),
805                         short_channel_id: None,
806                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
807                 };
808                 invoice_payer.handle_event(&event);
809                 assert_eq!(*event_handled.borrow(), false);
810                 assert_eq!(*payer.attempts.borrow(), 1);
811
812                 invoice_payer.handle_event(&event);
813                 assert_eq!(*event_handled.borrow(), false);
814                 assert_eq!(*payer.attempts.borrow(), 2);
815
816                 invoice_payer.handle_event(&Event::PaymentSent {
817                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
818                 });
819                 assert_eq!(*event_handled.borrow(), true);
820                 assert_eq!(*payer.attempts.borrow(), 2);
821         }
822
823         #[test]
824         fn fails_paying_invoice_after_max_retry_counts() {
825                 let event_handled = core::cell::RefCell::new(false);
826                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
827
828                 let payment_preimage = PaymentPreimage([1; 32]);
829                 let invoice = invoice(payment_preimage);
830                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
831
832                 let payer = TestPayer::new()
833                         .expect_send(Amount::ForInvoice(final_value_msat))
834                         .expect_send(Amount::OnRetry(final_value_msat / 2))
835                         .expect_send(Amount::OnRetry(final_value_msat / 2));
836                 let router = TestRouter {};
837                 let scorer = RefCell::new(TestScorer::new());
838                 let logger = TestLogger::new();
839                 let invoice_payer =
840                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
841
842                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
843                 assert_eq!(*payer.attempts.borrow(), 1);
844
845                 let event = Event::PaymentPathFailed {
846                         payment_id,
847                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
848                         network_update: None,
849                         rejected_by_dest: false,
850                         all_paths_failed: true,
851                         path: TestRouter::path_for_value(final_value_msat),
852                         short_channel_id: None,
853                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
854                 };
855                 invoice_payer.handle_event(&event);
856                 assert_eq!(*event_handled.borrow(), false);
857                 assert_eq!(*payer.attempts.borrow(), 2);
858
859                 let event = Event::PaymentPathFailed {
860                         payment_id,
861                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
862                         network_update: None,
863                         rejected_by_dest: false,
864                         all_paths_failed: false,
865                         path: TestRouter::path_for_value(final_value_msat / 2),
866                         short_channel_id: None,
867                         retry: Some(RouteParameters {
868                                 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
869                         }),
870                 };
871                 invoice_payer.handle_event(&event);
872                 assert_eq!(*event_handled.borrow(), false);
873                 assert_eq!(*payer.attempts.borrow(), 3);
874
875                 invoice_payer.handle_event(&event);
876                 assert_eq!(*event_handled.borrow(), true);
877                 assert_eq!(*payer.attempts.borrow(), 3);
878         }
879
880         #[cfg(feature = "std")]
881         #[test]
882         fn fails_paying_invoice_after_max_retry_timeout() {
883                 let event_handled = core::cell::RefCell::new(false);
884                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
885
886                 let payment_preimage = PaymentPreimage([1; 32]);
887                 let invoice = invoice(payment_preimage);
888                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
889
890                 let payer = TestPayer::new()
891                         .expect_send(Amount::ForInvoice(final_value_msat))
892                         .expect_send(Amount::OnRetry(final_value_msat / 2));
893
894                 let router = TestRouter {};
895                 let scorer = RefCell::new(TestScorer::new());
896                 let logger = TestLogger::new();
897                 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
898
899                 let invoice_payer =
900                         InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
901
902                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
903                 assert_eq!(*payer.attempts.borrow(), 1);
904
905                 let event = Event::PaymentPathFailed {
906                         payment_id,
907                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
908                         network_update: None,
909                         rejected_by_dest: false,
910                         all_paths_failed: true,
911                         path: TestRouter::path_for_value(final_value_msat),
912                         short_channel_id: None,
913                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
914                 };
915                 invoice_payer.handle_event(&event);
916                 assert_eq!(*event_handled.borrow(), false);
917                 assert_eq!(*payer.attempts.borrow(), 2);
918
919                 SinceEpoch::advance(Duration::from_secs(121));
920
921                 invoice_payer.handle_event(&event);
922                 assert_eq!(*event_handled.borrow(), true);
923                 assert_eq!(*payer.attempts.borrow(), 2);
924         }
925
926         #[test]
927         fn fails_paying_invoice_with_missing_retry_params() {
928                 let event_handled = core::cell::RefCell::new(false);
929                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
930
931                 let payment_preimage = PaymentPreimage([1; 32]);
932                 let invoice = invoice(payment_preimage);
933                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
934
935                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
936                 let router = TestRouter {};
937                 let scorer = RefCell::new(TestScorer::new());
938                 let logger = TestLogger::new();
939                 let invoice_payer =
940                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
941
942                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
943                 assert_eq!(*payer.attempts.borrow(), 1);
944
945                 let event = Event::PaymentPathFailed {
946                         payment_id,
947                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
948                         network_update: None,
949                         rejected_by_dest: false,
950                         all_paths_failed: false,
951                         path: vec![],
952                         short_channel_id: None,
953                         retry: None,
954                 };
955                 invoice_payer.handle_event(&event);
956                 assert_eq!(*event_handled.borrow(), true);
957                 assert_eq!(*payer.attempts.borrow(), 1);
958         }
959
960         // Expiration is checked only in an std environment
961         #[cfg(feature = "std")]
962         #[test]
963         fn fails_paying_invoice_after_expiration() {
964                 let event_handled = core::cell::RefCell::new(false);
965                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
966
967                 let payer = TestPayer::new();
968                 let router = TestRouter {};
969                 let scorer = RefCell::new(TestScorer::new());
970                 let logger = TestLogger::new();
971                 let invoice_payer =
972                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
973
974                 let payment_preimage = PaymentPreimage([1; 32]);
975                 let invoice = expired_invoice(payment_preimage);
976                 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
977                         assert_eq!(msg, "Invoice expired prior to send");
978                 } else { panic!("Expected Invoice Error"); }
979         }
980
981         // Expiration is checked only in an std environment
982         #[cfg(feature = "std")]
983         #[test]
984         fn fails_retrying_invoice_after_expiration() {
985                 let event_handled = core::cell::RefCell::new(false);
986                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
987
988                 let payment_preimage = PaymentPreimage([1; 32]);
989                 let invoice = invoice(payment_preimage);
990                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
991
992                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
993                 let router = TestRouter {};
994                 let scorer = RefCell::new(TestScorer::new());
995                 let logger = TestLogger::new();
996                 let invoice_payer =
997                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
998
999                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1000                 assert_eq!(*payer.attempts.borrow(), 1);
1001
1002                 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1003                 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1004                         .checked_sub(Duration::from_secs(2)).unwrap()
1005                         .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1006                 let event = Event::PaymentPathFailed {
1007                         payment_id,
1008                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1009                         network_update: None,
1010                         rejected_by_dest: false,
1011                         all_paths_failed: false,
1012                         path: vec![],
1013                         short_channel_id: None,
1014                         retry: Some(retry_data),
1015                 };
1016                 invoice_payer.handle_event(&event);
1017                 assert_eq!(*event_handled.borrow(), true);
1018                 assert_eq!(*payer.attempts.borrow(), 1);
1019         }
1020
1021         #[test]
1022         fn fails_paying_invoice_after_retry_error() {
1023                 let event_handled = core::cell::RefCell::new(false);
1024                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1025
1026                 let payment_preimage = PaymentPreimage([1; 32]);
1027                 let invoice = invoice(payment_preimage);
1028                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1029
1030                 let payer = TestPayer::new()
1031                         .fails_on_attempt(2)
1032                         .expect_send(Amount::ForInvoice(final_value_msat))
1033                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1034                 let router = TestRouter {};
1035                 let scorer = RefCell::new(TestScorer::new());
1036                 let logger = TestLogger::new();
1037                 let invoice_payer =
1038                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1039
1040                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1041                 assert_eq!(*payer.attempts.borrow(), 1);
1042
1043                 let event = Event::PaymentPathFailed {
1044                         payment_id,
1045                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1046                         network_update: None,
1047                         rejected_by_dest: false,
1048                         all_paths_failed: false,
1049                         path: TestRouter::path_for_value(final_value_msat / 2),
1050                         short_channel_id: None,
1051                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1052                 };
1053                 invoice_payer.handle_event(&event);
1054                 assert_eq!(*event_handled.borrow(), true);
1055                 assert_eq!(*payer.attempts.borrow(), 2);
1056         }
1057
1058         #[test]
1059         fn fails_paying_invoice_after_rejected_by_payee() {
1060                 let event_handled = core::cell::RefCell::new(false);
1061                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1062
1063                 let payment_preimage = PaymentPreimage([1; 32]);
1064                 let invoice = invoice(payment_preimage);
1065                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1066
1067                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1068                 let router = TestRouter {};
1069                 let scorer = RefCell::new(TestScorer::new());
1070                 let logger = TestLogger::new();
1071                 let invoice_payer =
1072                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1073
1074                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1075                 assert_eq!(*payer.attempts.borrow(), 1);
1076
1077                 let event = Event::PaymentPathFailed {
1078                         payment_id,
1079                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1080                         network_update: None,
1081                         rejected_by_dest: true,
1082                         all_paths_failed: false,
1083                         path: vec![],
1084                         short_channel_id: None,
1085                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1086                 };
1087                 invoice_payer.handle_event(&event);
1088                 assert_eq!(*event_handled.borrow(), true);
1089                 assert_eq!(*payer.attempts.borrow(), 1);
1090         }
1091
1092         #[test]
1093         fn fails_repaying_invoice_with_pending_payment() {
1094                 let event_handled = core::cell::RefCell::new(false);
1095                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1096
1097                 let payment_preimage = PaymentPreimage([1; 32]);
1098                 let invoice = invoice(payment_preimage);
1099                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1100
1101                 let payer = TestPayer::new()
1102                         .expect_send(Amount::ForInvoice(final_value_msat))
1103                         .expect_send(Amount::ForInvoice(final_value_msat));
1104                 let router = TestRouter {};
1105                 let scorer = RefCell::new(TestScorer::new());
1106                 let logger = TestLogger::new();
1107                 let invoice_payer =
1108                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1109
1110                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1111
1112                 // Cannot repay an invoice pending payment.
1113                 match invoice_payer.pay_invoice(&invoice) {
1114                         Err(PaymentError::Invoice("payment pending")) => {},
1115                         Err(_) => panic!("unexpected error"),
1116                         Ok(_) => panic!("expected invoice error"),
1117                 }
1118
1119                 // Can repay an invoice once cleared from cache.
1120                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1121                 invoice_payer.remove_cached_payment(&payment_hash);
1122                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1123
1124                 // Cannot retry paying an invoice if cleared from cache.
1125                 invoice_payer.remove_cached_payment(&payment_hash);
1126                 let event = Event::PaymentPathFailed {
1127                         payment_id,
1128                         payment_hash,
1129                         network_update: None,
1130                         rejected_by_dest: false,
1131                         all_paths_failed: false,
1132                         path: vec![],
1133                         short_channel_id: None,
1134                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1135                 };
1136                 invoice_payer.handle_event(&event);
1137                 assert_eq!(*event_handled.borrow(), true);
1138         }
1139
1140         #[test]
1141         fn fails_paying_invoice_with_routing_errors() {
1142                 let payer = TestPayer::new();
1143                 let router = FailingRouter {};
1144                 let scorer = RefCell::new(TestScorer::new());
1145                 let logger = TestLogger::new();
1146                 let invoice_payer =
1147                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1148
1149                 let payment_preimage = PaymentPreimage([1; 32]);
1150                 let invoice = invoice(payment_preimage);
1151                 match invoice_payer.pay_invoice(&invoice) {
1152                         Err(PaymentError::Routing(_)) => {},
1153                         Err(_) => panic!("unexpected error"),
1154                         Ok(_) => panic!("expected routing error"),
1155                 }
1156         }
1157
1158         #[test]
1159         fn fails_paying_invoice_with_sending_errors() {
1160                 let payment_preimage = PaymentPreimage([1; 32]);
1161                 let invoice = invoice(payment_preimage);
1162                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1163
1164                 let payer = TestPayer::new()
1165                         .fails_on_attempt(1)
1166                         .expect_send(Amount::ForInvoice(final_value_msat));
1167                 let router = TestRouter {};
1168                 let scorer = RefCell::new(TestScorer::new());
1169                 let logger = TestLogger::new();
1170                 let invoice_payer =
1171                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1172
1173                 match invoice_payer.pay_invoice(&invoice) {
1174                         Err(PaymentError::Sending(_)) => {},
1175                         Err(_) => panic!("unexpected error"),
1176                         Ok(_) => panic!("expected sending error"),
1177                 }
1178         }
1179
1180         #[test]
1181         fn pays_zero_value_invoice_using_amount() {
1182                 let event_handled = core::cell::RefCell::new(false);
1183                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1184
1185                 let payment_preimage = PaymentPreimage([1; 32]);
1186                 let invoice = zero_value_invoice(payment_preimage);
1187                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1188                 let final_value_msat = 100;
1189
1190                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1191                 let router = TestRouter {};
1192                 let scorer = RefCell::new(TestScorer::new());
1193                 let logger = TestLogger::new();
1194                 let invoice_payer =
1195                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1196
1197                 let payment_id =
1198                         Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1199                 assert_eq!(*payer.attempts.borrow(), 1);
1200
1201                 invoice_payer.handle_event(&Event::PaymentSent {
1202                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1203                 });
1204                 assert_eq!(*event_handled.borrow(), true);
1205                 assert_eq!(*payer.attempts.borrow(), 1);
1206         }
1207
1208         #[test]
1209         fn fails_paying_zero_value_invoice_with_amount() {
1210                 let event_handled = core::cell::RefCell::new(false);
1211                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1212
1213                 let payer = TestPayer::new();
1214                 let router = TestRouter {};
1215                 let scorer = RefCell::new(TestScorer::new());
1216                 let logger = TestLogger::new();
1217                 let invoice_payer =
1218                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1219
1220                 let payment_preimage = PaymentPreimage([1; 32]);
1221                 let invoice = invoice(payment_preimage);
1222
1223                 // Cannot repay an invoice pending payment.
1224                 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1225                         Err(PaymentError::Invoice("amount unexpected")) => {},
1226                         Err(_) => panic!("unexpected error"),
1227                         Ok(_) => panic!("expected invoice error"),
1228                 }
1229         }
1230
1231         #[test]
1232         fn pays_pubkey_with_amount() {
1233                 let event_handled = core::cell::RefCell::new(false);
1234                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1235
1236                 let pubkey = pubkey();
1237                 let payment_preimage = PaymentPreimage([1; 32]);
1238                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1239                 let final_value_msat = 100;
1240                 let final_cltv_expiry_delta = 42;
1241
1242                 let payer = TestPayer::new()
1243                         .expect_send(Amount::Spontaneous(final_value_msat))
1244                         .expect_send(Amount::OnRetry(final_value_msat));
1245                 let router = TestRouter {};
1246                 let scorer = RefCell::new(TestScorer::new());
1247                 let logger = TestLogger::new();
1248                 let invoice_payer =
1249                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1250
1251                 let payment_id = Some(invoice_payer.pay_pubkey(
1252                                 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1253                         ).unwrap());
1254                 assert_eq!(*payer.attempts.borrow(), 1);
1255
1256                 let retry = RouteParameters {
1257                         payment_params: PaymentParameters::for_keysend(pubkey),
1258                         final_value_msat,
1259                         final_cltv_expiry_delta,
1260                 };
1261                 let event = Event::PaymentPathFailed {
1262                         payment_id,
1263                         payment_hash,
1264                         network_update: None,
1265                         rejected_by_dest: false,
1266                         all_paths_failed: false,
1267                         path: vec![],
1268                         short_channel_id: None,
1269                         retry: Some(retry),
1270                 };
1271                 invoice_payer.handle_event(&event);
1272                 assert_eq!(*event_handled.borrow(), false);
1273                 assert_eq!(*payer.attempts.borrow(), 2);
1274
1275                 invoice_payer.handle_event(&Event::PaymentSent {
1276                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1277                 });
1278                 assert_eq!(*event_handled.borrow(), true);
1279                 assert_eq!(*payer.attempts.borrow(), 2);
1280         }
1281
1282         #[test]
1283         fn scores_failed_channel() {
1284                 let event_handled = core::cell::RefCell::new(false);
1285                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1286
1287                 let payment_preimage = PaymentPreimage([1; 32]);
1288                 let invoice = invoice(payment_preimage);
1289                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1290                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1291                 let path = TestRouter::path_for_value(final_value_msat);
1292                 let short_channel_id = Some(path[0].short_channel_id);
1293
1294                 // Expect that scorer is given short_channel_id upon handling the event.
1295                 let payer = TestPayer::new()
1296                         .expect_send(Amount::ForInvoice(final_value_msat))
1297                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1298                 let router = TestRouter {};
1299                 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1300                         path: path.clone(), short_channel_id: path[0].short_channel_id,
1301                 }));
1302                 let logger = TestLogger::new();
1303                 let invoice_payer =
1304                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1305
1306                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1307                 let event = Event::PaymentPathFailed {
1308                         payment_id,
1309                         payment_hash,
1310                         network_update: None,
1311                         rejected_by_dest: false,
1312                         all_paths_failed: false,
1313                         path,
1314                         short_channel_id,
1315                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1316                 };
1317                 invoice_payer.handle_event(&event);
1318         }
1319
1320         #[test]
1321         fn scores_successful_channels() {
1322                 let event_handled = core::cell::RefCell::new(false);
1323                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1324
1325                 let payment_preimage = PaymentPreimage([1; 32]);
1326                 let invoice = invoice(payment_preimage);
1327                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1328                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1329                 let route = TestRouter::route_for_value(final_value_msat);
1330
1331                 // Expect that scorer is given short_channel_id upon handling the event.
1332                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1333                 let router = TestRouter {};
1334                 let scorer = RefCell::new(TestScorer::new()
1335                         .expect(PaymentPath::Success { path: route.paths[0].clone() })
1336                         .expect(PaymentPath::Success { path: route.paths[1].clone() })
1337                 );
1338                 let logger = TestLogger::new();
1339                 let invoice_payer =
1340                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1341
1342                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1343                 let event = Event::PaymentPathSuccessful {
1344                         payment_id, payment_hash, path: route.paths[0].clone()
1345                 };
1346                 invoice_payer.handle_event(&event);
1347                 let event = Event::PaymentPathSuccessful {
1348                         payment_id, payment_hash, path: route.paths[1].clone()
1349                 };
1350                 invoice_payer.handle_event(&event);
1351         }
1352
1353         struct TestRouter;
1354
1355         impl TestRouter {
1356                 fn route_for_value(final_value_msat: u64) -> Route {
1357                         Route {
1358                                 paths: vec![
1359                                         vec![RouteHop {
1360                                                 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1361                                                 channel_features: ChannelFeatures::empty(),
1362                                                 node_features: NodeFeatures::empty(),
1363                                                 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1364                                         }],
1365                                         vec![RouteHop {
1366                                                 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1367                                                 channel_features: ChannelFeatures::empty(),
1368                                                 node_features: NodeFeatures::empty(),
1369                                                 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1370                                         }],
1371                                 ],
1372                                 payment_params: None,
1373                         }
1374                 }
1375
1376                 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1377                         TestRouter::route_for_value(final_value_msat).paths[0].clone()
1378                 }
1379
1380                 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1381                         let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1382                                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1383                                 .with_route_hints(invoice.route_hints());
1384                         if let Some(features) = invoice.features() {
1385                                 payment_params = payment_params.with_features(features.clone());
1386                         }
1387                         let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1388                         RouteParameters {
1389                                 payment_params,
1390                                 final_value_msat,
1391                                 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1392                         }
1393                 }
1394         }
1395
1396         impl<S: Score> Router<S> for TestRouter {
1397                 fn find_route(
1398                         &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1399                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1400                 ) -> Result<Route, LightningError> {
1401                         Ok(Route {
1402                                 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1403                         })
1404                 }
1405         }
1406
1407         struct FailingRouter;
1408
1409         impl<S: Score> Router<S> for FailingRouter {
1410                 fn find_route(
1411                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1412                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1413                 ) -> Result<Route, LightningError> {
1414                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1415                 }
1416         }
1417
1418         struct TestScorer {
1419                 expectations: Option<VecDeque<PaymentPath>>,
1420         }
1421
1422         #[derive(Debug)]
1423         enum PaymentPath {
1424                 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1425                 Success { path: Vec<RouteHop> },
1426         }
1427
1428         impl TestScorer {
1429                 fn new() -> Self {
1430                         Self {
1431                                 expectations: None,
1432                         }
1433                 }
1434
1435                 fn expect(mut self, expectation: PaymentPath) -> Self {
1436                         self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1437                         self
1438                 }
1439         }
1440
1441         #[cfg(c_bindings)]
1442         impl lightning::util::ser::Writeable for TestScorer {
1443                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1444         }
1445
1446         impl Score for TestScorer {
1447                 fn channel_penalty_msat(
1448                         &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
1449                 ) -> u64 { 0 }
1450
1451                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1452                         if let Some(expectations) = &mut self.expectations {
1453                                 match expectations.pop_front() {
1454                                         Some(PaymentPath::Failure { path, short_channel_id }) => {
1455                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1456                                                 assert_eq!(actual_short_channel_id, short_channel_id);
1457                                         },
1458                                         Some(PaymentPath::Success { path }) => {
1459                                                 panic!("Unexpected successful payment path: {:?}", path)
1460                                         },
1461                                         None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1462                                 }
1463                         }
1464                 }
1465
1466                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1467                         if let Some(expectations) = &mut self.expectations {
1468                                 match expectations.pop_front() {
1469                                         Some(PaymentPath::Failure { path, .. }) => {
1470                                                 panic!("Unexpected payment path failure: {:?}", path)
1471                                         },
1472                                         Some(PaymentPath::Success { path }) => {
1473                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1474                                         },
1475                                         None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1476                                 }
1477                         }
1478                 }
1479         }
1480
1481         impl Drop for TestScorer {
1482                 fn drop(&mut self) {
1483                         if std::thread::panicking() {
1484                                 return;
1485                         }
1486
1487                         if let Some(expectations) = &self.expectations {
1488                                 if !expectations.is_empty() {
1489                                         panic!("Unsatisfied scorer expectations: {:?}", expectations);
1490                                 }
1491                         }
1492                 }
1493         }
1494
1495         struct TestPayer {
1496                 expectations: core::cell::RefCell<VecDeque<Amount>>,
1497                 attempts: core::cell::RefCell<usize>,
1498                 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1499         }
1500
1501         #[derive(Clone, Debug, PartialEq, Eq)]
1502         enum Amount {
1503                 ForInvoice(u64),
1504                 Spontaneous(u64),
1505                 OnRetry(u64),
1506         }
1507
1508         struct OnAttempt(usize);
1509
1510         impl TestPayer {
1511                 fn new() -> Self {
1512                         Self {
1513                                 expectations: core::cell::RefCell::new(VecDeque::new()),
1514                                 attempts: core::cell::RefCell::new(0),
1515                                 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1516                         }
1517                 }
1518
1519                 fn expect_send(self, value_msat: Amount) -> Self {
1520                         self.expectations.borrow_mut().push_back(value_msat);
1521                         self
1522                 }
1523
1524                 fn fails_on_attempt(self, attempt: usize) -> Self {
1525                         let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1526                         self.fails_with(failure, OnAttempt(attempt))
1527                 }
1528
1529                 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1530                         self.fails_with(PaymentSendFailure::PartialFailure {
1531                                 results: vec![],
1532                                 failed_paths_retry: Some(retry),
1533                                 payment_id: PaymentId([1; 32]),
1534                         }, attempt)
1535                 }
1536
1537                 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1538                         self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1539                         self
1540                 }
1541
1542                 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1543                         let mut attempts = self.attempts.borrow_mut();
1544                         *attempts += 1;
1545
1546                         match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1547                                 Some(failure) => Err(failure),
1548                                 None => Ok(PaymentId([1; 32])),
1549                         }
1550                 }
1551
1552                 fn check_value_msats(&self, actual_value_msats: Amount) {
1553                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
1554                         if let Some(expected_value_msats) = expected_value_msats {
1555                                 assert_eq!(actual_value_msats, expected_value_msats);
1556                         } else {
1557                                 panic!("Unexpected amount: {:?}", actual_value_msats);
1558                         }
1559                 }
1560         }
1561
1562         impl Drop for TestPayer {
1563                 fn drop(&mut self) {
1564                         if std::thread::panicking() {
1565                                 return;
1566                         }
1567
1568                         if !self.expectations.borrow().is_empty() {
1569                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1570                         }
1571                 }
1572         }
1573
1574         impl Payer for TestPayer {
1575                 fn node_id(&self) -> PublicKey {
1576                         let secp_ctx = Secp256k1::new();
1577                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1578                 }
1579
1580                 fn first_hops(&self) -> Vec<ChannelDetails> {
1581                         Vec::new()
1582                 }
1583
1584                 fn send_payment(
1585                         &self, route: &Route, _payment_hash: PaymentHash,
1586                         _payment_secret: &Option<PaymentSecret>
1587                 ) -> Result<PaymentId, PaymentSendFailure> {
1588                         self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1589                         self.check_attempts()
1590                 }
1591
1592                 fn send_spontaneous_payment(
1593                         &self, route: &Route, _payment_preimage: PaymentPreimage,
1594                 ) -> Result<PaymentId, PaymentSendFailure> {
1595                         self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1596                         self.check_attempts()
1597                 }
1598
1599                 fn retry_payment(
1600                         &self, route: &Route, _payment_id: PaymentId
1601                 ) -> Result<(), PaymentSendFailure> {
1602                         self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1603                         self.check_attempts().map(|_| ())
1604                 }
1605
1606                 fn abandon_payment(&self, _payment_id: PaymentId) { }
1607         }
1608
1609         // *** Full Featured Functional Tests with a Real ChannelManager ***
1610         struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1611
1612         impl<S: Score> Router<S> for ManualRouter {
1613                 fn find_route(
1614                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1615                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1616                 ) -> Result<Route, LightningError> {
1617                         self.0.borrow_mut().pop_front().unwrap()
1618                 }
1619         }
1620         impl ManualRouter {
1621                 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1622                         self.0.borrow_mut().push_back(result);
1623                 }
1624         }
1625         impl Drop for ManualRouter {
1626                 fn drop(&mut self) {
1627                         if std::thread::panicking() {
1628                                 return;
1629                         }
1630                         assert!(self.0.borrow_mut().is_empty());
1631                 }
1632         }
1633
1634         #[test]
1635         fn retry_multi_path_single_failed_payment() {
1636                 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1637                 let chanmon_cfgs = create_chanmon_cfgs(2);
1638                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1639                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1640                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1641
1642                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1643                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1644                 let chans = nodes[0].node.list_usable_channels();
1645                 let mut route = Route {
1646                         paths: vec![
1647                                 vec![RouteHop {
1648                                         pubkey: nodes[1].node.get_our_node_id(),
1649                                         node_features: NodeFeatures::known(),
1650                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1651                                         channel_features: ChannelFeatures::known(),
1652                                         fee_msat: 10_000,
1653                                         cltv_expiry_delta: 100,
1654                                 }],
1655                                 vec![RouteHop {
1656                                         pubkey: nodes[1].node.get_our_node_id(),
1657                                         node_features: NodeFeatures::known(),
1658                                         short_channel_id: chans[1].short_channel_id.unwrap(),
1659                                         channel_features: ChannelFeatures::known(),
1660                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1661                                         cltv_expiry_delta: 100,
1662                                 }],
1663                         ],
1664                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1665                 };
1666                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1667                 router.expect_find_route(Ok(route.clone()));
1668                 // On retry, split the payment across both channels.
1669                 route.paths[0][0].fee_msat = 50_000_001;
1670                 route.paths[1][0].fee_msat = 50_000_000;
1671                 router.expect_find_route(Ok(route.clone()));
1672
1673                 let event_handler = |_: &_| { panic!(); };
1674                 let scorer = RefCell::new(TestScorer::new());
1675                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1676
1677                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1678                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1679                         duration_since_epoch(), 3600).unwrap())
1680                         .is_ok());
1681                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1682                 assert_eq!(htlc_msgs.len(), 2);
1683                 check_added_monitors!(nodes[0], 2);
1684         }
1685
1686         #[test]
1687         fn immediate_retry_on_failure() {
1688                 // Tests that we can/will retry immediately after a failure
1689                 let chanmon_cfgs = create_chanmon_cfgs(2);
1690                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1691                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1692                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1693
1694                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1695                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1696                 let chans = nodes[0].node.list_usable_channels();
1697                 let mut route = Route {
1698                         paths: vec![
1699                                 vec![RouteHop {
1700                                         pubkey: nodes[1].node.get_our_node_id(),
1701                                         node_features: NodeFeatures::known(),
1702                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1703                                         channel_features: ChannelFeatures::known(),
1704                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1705                                         cltv_expiry_delta: 100,
1706                                 }],
1707                         ],
1708                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1709                 };
1710                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1711                 router.expect_find_route(Ok(route.clone()));
1712                 // On retry, split the payment across both channels.
1713                 route.paths.push(route.paths[0].clone());
1714                 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1715                 route.paths[0][0].fee_msat = 50_000_000;
1716                 route.paths[1][0].fee_msat = 50_000_001;
1717                 router.expect_find_route(Ok(route.clone()));
1718
1719                 let event_handler = |_: &_| { panic!(); };
1720                 let scorer = RefCell::new(TestScorer::new());
1721                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1722
1723                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1724                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1725                         duration_since_epoch(), 3600).unwrap())
1726                         .is_ok());
1727                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1728                 assert_eq!(htlc_msgs.len(), 2);
1729                 check_added_monitors!(nodes[0], 2);
1730         }
1731
1732         #[test]
1733         fn no_extra_retries_on_back_to_back_fail() {
1734                 // In a previous release, we had a race where we may exceed the payment retry count if we
1735                 // get two failures in a row with the second having `all_paths_failed` set.
1736                 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1737                 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1738                 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1739                 // pending which we will see later. Thus, when we previously removed the retry tracking map
1740                 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1741                 // retry entry even though more events for the same payment were still pending. This led to
1742                 // us retrying a payment again even though we'd already given up on it.
1743                 //
1744                 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1745                 // is used to remove the payment retry counter entries instead. This tests for the specific
1746                 // excess-retry case while also testing `PaymentFailed` generation.
1747
1748                 let chanmon_cfgs = create_chanmon_cfgs(3);
1749                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1750                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1751                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1752
1753                 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;
1754                 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;
1755
1756                 let mut route = Route {
1757                         paths: vec![
1758                                 vec![RouteHop {
1759                                         pubkey: nodes[1].node.get_our_node_id(),
1760                                         node_features: NodeFeatures::known(),
1761                                         short_channel_id: chan_1_scid,
1762                                         channel_features: ChannelFeatures::known(),
1763                                         fee_msat: 0,
1764                                         cltv_expiry_delta: 100,
1765                                 }, RouteHop {
1766                                         pubkey: nodes[2].node.get_our_node_id(),
1767                                         node_features: NodeFeatures::known(),
1768                                         short_channel_id: chan_2_scid,
1769                                         channel_features: ChannelFeatures::known(),
1770                                         fee_msat: 100_000_000,
1771                                         cltv_expiry_delta: 100,
1772                                 }],
1773                                 vec![RouteHop {
1774                                         pubkey: nodes[1].node.get_our_node_id(),
1775                                         node_features: NodeFeatures::known(),
1776                                         short_channel_id: chan_1_scid,
1777                                         channel_features: ChannelFeatures::known(),
1778                                         fee_msat: 0,
1779                                         cltv_expiry_delta: 100,
1780                                 }, RouteHop {
1781                                         pubkey: nodes[2].node.get_our_node_id(),
1782                                         node_features: NodeFeatures::known(),
1783                                         short_channel_id: chan_2_scid,
1784                                         channel_features: ChannelFeatures::known(),
1785                                         fee_msat: 100_000_000,
1786                                         cltv_expiry_delta: 100,
1787                                 }]
1788                         ],
1789                         payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1790                 };
1791                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1792                 router.expect_find_route(Ok(route.clone()));
1793                 // On retry, we'll only be asked for one path
1794                 route.paths.remove(1);
1795                 router.expect_find_route(Ok(route.clone()));
1796
1797                 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1798                 let event_handler = |event: &Event| {
1799                         let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1800                         event_checker(event);
1801                 };
1802                 let scorer = RefCell::new(TestScorer::new());
1803                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1804
1805                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1806                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1807                         duration_since_epoch(), 3600).unwrap())
1808                         .is_ok());
1809                 let htlc_updates = SendEvent::from_node(&nodes[0]);
1810                 check_added_monitors!(nodes[0], 1);
1811                 assert_eq!(htlc_updates.msgs.len(), 1);
1812
1813                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1814                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1815                 check_added_monitors!(nodes[1], 1);
1816                 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1817
1818                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1819                 check_added_monitors!(nodes[0], 1);
1820                 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1821
1822                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1823                 check_added_monitors!(nodes[0], 1);
1824                 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1825
1826                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1827                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1828                 check_added_monitors!(nodes[1], 1);
1829                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1830
1831                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1832                 check_added_monitors!(nodes[1], 1);
1833                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1834
1835                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1836                 check_added_monitors!(nodes[0], 1);
1837
1838                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1839                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1840                 check_added_monitors!(nodes[0], 1);
1841                 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1842
1843                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1844                 check_added_monitors!(nodes[1], 1);
1845                 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1846
1847                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1848                 check_added_monitors!(nodes[1], 1);
1849                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1850
1851                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1852                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1853                 check_added_monitors!(nodes[0], 1);
1854
1855                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1856                 check_added_monitors!(nodes[0], 1);
1857                 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1858
1859                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1860                 check_added_monitors!(nodes[1], 1);
1861                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1862                 check_added_monitors!(nodes[1], 1);
1863                 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1864
1865                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1866                 check_added_monitors!(nodes[0], 1);
1867
1868                 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1869                 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1870                 // with it set. The first event will use up the only retry we are allowed, with the second
1871                 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1872                 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1873                 // if the final HTLC failed.
1874                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1875                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1876                                 assert!(!rejected_by_dest);
1877                                 assert!(all_paths_failed);
1878                         } else { panic!("Unexpected event"); }
1879                 });
1880                 nodes[0].node.process_pending_events(&invoice_payer);
1881                 assert!(expected_events.borrow().is_empty());
1882
1883                 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1884                 check_added_monitors!(nodes[0], 1);
1885
1886                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1887                 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1888                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1889                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1890                 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1891
1892                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1893                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1894                                 assert!(!rejected_by_dest);
1895                                 assert!(all_paths_failed);
1896                         } else { panic!("Unexpected event"); }
1897                 });
1898                 expected_events.borrow_mut().push_back(&|ev: &Event| {
1899                         if let Event::PaymentFailed { .. } = ev {
1900                         } else { panic!("Unexpected event"); }
1901                 });
1902                 nodes[0].node.process_pending_events(&invoice_payer);
1903                 assert!(expected_events.borrow().is_empty());
1904         }
1905 }