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