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