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