]> git.bitcoin.ninja Git - rust-lightning/blob - lightning-invoice/src/payment.rs
Remove unused payment_hash param from Router::find_route
[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`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
22 //!
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
28 //!
29 //! # Example
30 //!
31 //! ```
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
35 //! #
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InFlightHtlcs, InvoicePayer, Payer, Retry, Router};
48 //! # use secp256k1::PublicKey;
49 //! # use std::cell::RefCell;
50 //! # use std::ops::Deref;
51 //! #
52 //! # struct FakeEventProvider {}
53 //! # impl EventsProvider for FakeEventProvider {
54 //! #     fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
55 //! # }
56 //! #
57 //! # struct FakePayer {}
58 //! # impl Payer for FakePayer {
59 //! #     fn node_id(&self) -> PublicKey { unimplemented!() }
60 //! #     fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
61 //! #     fn send_payment(
62 //! #         &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
63 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
64 //! #     fn send_spontaneous_payment(
65 //! #         &self, route: &Route, payment_preimage: PaymentPreimage
66 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
67 //! #     fn retry_payment(
68 //! #         &self, route: &Route, payment_id: PaymentId
69 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
70 //! #     fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
71 //! # }
72 //! #
73 //! # struct FakeRouter {}
74 //! # impl Router for FakeRouter {
75 //! #     fn find_route(
76 //! #         &self, payer: &PublicKey, params: &RouteParameters,
77 //! #         first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
78 //! #     ) -> Result<Route, LightningError> { unimplemented!() }
79 //! #
80 //! #     fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {  unimplemented!() }
81 //! #     fn notify_payment_path_successful(&self, path: &[&RouteHop]) {  unimplemented!() }
82 //! #     fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {  unimplemented!() }
83 //! #     fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
84 //! # }
85 //! #
86 //! # struct FakeScorer {}
87 //! # impl Writeable for FakeScorer {
88 //! #     fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
89 //! # }
90 //! # impl Score for FakeScorer {
91 //! #     fn channel_penalty_msat(
92 //! #         &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
93 //! #     ) -> u64 { 0 }
94 //! #     fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
95 //! #     fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
96 //! #     fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
97 //! #     fn probe_successful(&mut self, _path: &[&RouteHop]) {}
98 //! # }
99 //! #
100 //! # struct FakeLogger {}
101 //! # impl Logger for FakeLogger {
102 //! #     fn log(&self, record: &Record) { unimplemented!() }
103 //! # }
104 //! #
105 //! # fn main() {
106 //! let event_handler = |event: &Event| {
107 //!     match event {
108 //!         Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
109 //!         Event::PaymentSent { .. } => println!("payment successful"),
110 //!         _ => {},
111 //!     }
112 //! };
113 //! # let payer = FakePayer {};
114 //! # let router = FakeRouter {};
115 //! # let scorer = RefCell::new(FakeScorer {});
116 //! # let logger = FakeLogger {};
117 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
118 //!
119 //! let invoice = "...";
120 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
121 //!     invoice_payer.pay_invoice(&invoice).unwrap();
122 //!
123 //! # let event_provider = FakeEventProvider {};
124 //!     loop {
125 //!         event_provider.process_pending_events(&invoice_payer);
126 //!     }
127 //! }
128 //! # }
129 //! ```
130 //!
131 //! # Note
132 //!
133 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
134 //! as updates to the network graph or changes to channel scores should be applied prior to
135 //! retries, typically by way of composing [`EventHandler`]s accordingly.
136
137 use crate::Invoice;
138
139 use bitcoin_hashes::Hash;
140 use bitcoin_hashes::sha256::Hash as Sha256;
141
142 use crate::prelude::*;
143 use lightning::io;
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::gossip::NodeId;
148 use lightning::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters};
149 use lightning::util::errors::APIError;
150 use lightning::util::events::{Event, EventHandler};
151 use lightning::util::logger::Logger;
152 use lightning::util::ser::Writeable;
153 use crate::time_utils::Time;
154 use crate::sync::Mutex;
155
156 use secp256k1::PublicKey;
157
158 use core::fmt;
159 use core::fmt::{Debug, Display, Formatter};
160 use core::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
164
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
166 ///
167 /// See [module-level documentation] for details.
168 ///
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
171
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
175 use crate::time_utils;
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
178
179 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
180 pub struct InvoicePayerUsingTime<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time>
181 where
182         P::Target: Payer,
183         L::Target: Logger,
184 {
185         payer: P,
186         router: R,
187         logger: L,
188         event_handler: E,
189         /// Caches the overall attempts at making a payment, which is updated prior to retrying.
190         payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
191         retry: Retry,
192 }
193
194 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
195 /// currently being made, or have outstanding paths that need retrying.
196 struct PaymentInfo<T: Time> {
197         attempts: PaymentAttempts<T>,
198         paths: Vec<Vec<RouteHop>>,
199 }
200
201 impl<T: Time> PaymentInfo<T> {
202         fn new() -> Self {
203                 PaymentInfo {
204                         attempts: PaymentAttempts::new(),
205                         paths: vec![],
206                 }
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 {
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,
274                 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
275         ) -> Result<Route, LightningError>;
276         /// Lets the router know that payment through a specific path has failed.
277         fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
278         /// Lets the router know that payment through a specific path was successful.
279         fn notify_payment_path_successful(&self, path: &[&RouteHop]);
280         /// Lets the router know that a payment probe was successful.
281         fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
282         /// Lets the router know that a payment probe failed.
283         fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
284 }
285
286 /// Strategies available to retry payment path failures for an [`Invoice`].
287 ///
288 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
289 pub enum Retry {
290         /// Max number of attempts to retry payment.
291         ///
292         /// Note that this is the number of *path* failures, not full payment retries. For multi-path
293         /// payments, if this is less than the total number of paths, we will never even retry all of the
294         /// payment's paths.
295         Attempts(usize),
296         #[cfg(feature = "std")]
297         /// Time elapsed before abandoning retries for a payment.
298         Timeout(Duration),
299 }
300
301 impl Retry {
302         fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
303                 match (self, attempts) {
304                         (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
305                                 max_retry_count >= &count
306                         },
307                         #[cfg(feature = "std")]
308                         (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
309                                 *max_duration >= T::now().duration_since(*first_attempted_at),
310                 }
311         }
312 }
313
314 /// An error that may occur when making a payment.
315 #[derive(Clone, Debug)]
316 pub enum PaymentError {
317         /// An error resulting from the provided [`Invoice`] or payment hash.
318         Invoice(&'static str),
319         /// An error occurring when finding a route.
320         Routing(LightningError),
321         /// An error occurring when sending a payment.
322         Sending(PaymentSendFailure),
323 }
324
325 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
326 where
327         P::Target: Payer,
328         L::Target: Logger,
329 {
330         /// Creates an invoice payer that retries failed payment paths.
331         ///
332         /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
333         /// `retry` has been exceeded for a given [`Invoice`].
334         pub fn new(
335                 payer: P, router: R, logger: L, event_handler: E, retry: Retry
336         ) -> Self {
337                 Self {
338                         payer,
339                         router,
340                         logger,
341                         event_handler,
342                         payment_cache: Mutex::new(HashMap::new()),
343                         retry,
344                 }
345         }
346
347         /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
348         ///
349         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
350         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
351         /// for you.
352         pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
353                 if invoice.amount_milli_satoshis().is_none() {
354                         Err(PaymentError::Invoice("amount missing"))
355                 } else {
356                         self.pay_invoice_using_amount(invoice, None)
357                 }
358         }
359
360         /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
361         /// case a retry is needed.
362         ///
363         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
364         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
365         /// for you.
366         pub fn pay_zero_value_invoice(
367                 &self, invoice: &Invoice, amount_msats: u64
368         ) -> Result<PaymentId, PaymentError> {
369                 if invoice.amount_milli_satoshis().is_some() {
370                         Err(PaymentError::Invoice("amount unexpected"))
371                 } else {
372                         self.pay_invoice_using_amount(invoice, Some(amount_msats))
373                 }
374         }
375
376         fn pay_invoice_using_amount(
377                 &self, invoice: &Invoice, amount_msats: Option<u64>
378         ) -> Result<PaymentId, PaymentError> {
379                 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
380
381                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
382                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
383                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
384                         hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
385                 };
386
387                 let payment_secret = Some(invoice.payment_secret().clone());
388                 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
389                         .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
390                         .with_route_hints(invoice.route_hints());
391                 if let Some(features) = invoice.features() {
392                         payment_params = payment_params.with_features(features.clone());
393                 }
394                 let route_params = RouteParameters {
395                         payment_params,
396                         final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
397                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
398                 };
399
400                 let send_payment = |route: &Route| {
401                         self.payer.send_payment(route, payment_hash, &payment_secret)
402                 };
403
404                 self.pay_internal(&route_params, payment_hash, send_payment)
405                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
406         }
407
408         /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
409         /// case a retry is needed.
410         ///
411         /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
412         /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
413         pub fn pay_pubkey(
414                 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
415                 final_cltv_expiry_delta: u32
416         ) -> Result<PaymentId, PaymentError> {
417                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
418                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
419                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
420                         hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
421                 };
422
423                 let route_params = RouteParameters {
424                         payment_params: PaymentParameters::for_keysend(pubkey),
425                         final_value_msat: amount_msats,
426                         final_cltv_expiry_delta,
427                 };
428
429                 let send_payment = |route: &Route| {
430                         self.payer.send_spontaneous_payment(route, payment_preimage)
431                 };
432                 self.pay_internal(&route_params, payment_hash, send_payment)
433                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
434         }
435
436         fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
437                 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
438         ) -> Result<PaymentId, PaymentError> {
439                 #[cfg(feature = "std")] {
440                         if has_expired(params) {
441                                 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
442                                 return Err(PaymentError::Invoice("Invoice expired prior to send"));
443                         }
444                 }
445
446                 let payer = self.payer.node_id();
447                 let first_hops = self.payer.first_hops();
448                 let inflight_htlcs = self.create_inflight_map();
449                 let route = self.router.find_route(
450                         &payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
451                 ).map_err(|e| PaymentError::Routing(e))?;
452
453                 match send_payment(&route) {
454                         Ok(payment_id) => {
455                                 for path in route.paths {
456                                         self.process_path_inflight_htlcs(payment_hash, path);
457                                 }
458                                 Ok(payment_id)
459                         },
460                         Err(e) => match e {
461                                 PaymentSendFailure::ParameterError(_) => Err(e),
462                                 PaymentSendFailure::PathParameterError(_) => Err(e),
463                                 PaymentSendFailure::AllFailedRetrySafe(_) => {
464                                         let mut payment_cache = self.payment_cache.lock().unwrap();
465                                         let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
466                                         payment_info.attempts.count += 1;
467                                         if self.retry.is_retryable_now(&payment_info.attempts) {
468                                                 core::mem::drop(payment_cache);
469                                                 Ok(self.pay_internal(params, payment_hash, send_payment)?)
470                                         } else {
471                                                 Err(e)
472                                         }
473                                 },
474                                 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
475                                         // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
476                                         // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
477                                         // means that we are still waiting for our channel monitor update to be completed.
478                                         for (result, path) in results.iter().zip(route.paths.into_iter()) {
479                                                 match result {
480                                                         Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
481                                                                 self.process_path_inflight_htlcs(payment_hash, path);
482                                                         },
483                                                         _ => {},
484                                                 }
485                                         }
486
487                                         if let Some(retry_data) = failed_paths_retry {
488                                                 // Some paths were sent, even if we failed to send the full MPP value our
489                                                 // recipient may misbehave and claim the funds, at which point we have to
490                                                 // consider the payment sent, so return `Ok()` here, ignoring any retry
491                                                 // errors.
492                                                 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
493                                                 Ok(payment_id)
494                                         } else {
495                                                 // This may happen if we send a payment and some paths fail, but
496                                                 // only due to a temporary monitor failure or the like, implying
497                                                 // they're really in-flight, but we haven't sent the initial
498                                                 // HTLC-Add messages yet.
499                                                 Ok(payment_id)
500                                         }
501                                 },
502                         },
503                 }.map_err(|e| PaymentError::Sending(e))
504         }
505
506         // Takes in a path to have its information stored in `payment_cache`. This is done for paths
507         // that are pending retry.
508         fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
509                 self.payment_cache.lock().unwrap().entry(payment_hash)
510                         .or_insert_with(|| PaymentInfo::new())
511                         .paths.push(path);
512         }
513
514         // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
515         fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
516                 self.payment_cache.lock().unwrap().entry(payment_hash)
517                         .and_modify(|payment_info| {
518                                 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
519                                         payment_info.paths.swap_remove(idx);
520                                 }
521                         });
522         }
523
524         fn retry_payment(
525                 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
526         ) -> Result<(), ()> {
527                 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
528                         .and_modify(|info| info.attempts.count += 1 )
529                         .or_insert_with(|| PaymentInfo {
530                                 attempts: PaymentAttempts {
531                                         count: 1,
532                                         first_attempted_at: T::now(),
533                                 },
534                                 paths: vec![],
535                         }).attempts;
536
537                 if !self.retry.is_retryable_now(&attempts) {
538                         log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
539                         return Err(());
540                 }
541
542                 #[cfg(feature = "std")] {
543                         if has_expired(params) {
544                                 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
545                                 return Err(());
546                         }
547                 }
548
549                 let payer = self.payer.node_id();
550                 let first_hops = self.payer.first_hops();
551                 let inflight_htlcs = self.create_inflight_map();
552
553                 let route = self.router.find_route(
554                         &payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
555                 );
556
557                 if route.is_err() {
558                         log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
559                         return Err(());
560                 }
561
562                 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
563                         Ok(()) => {
564                                 for path in route.unwrap().paths.into_iter() {
565                                         self.process_path_inflight_htlcs(payment_hash, path);
566                                 }
567                                 Ok(())
568                         },
569                         Err(PaymentSendFailure::ParameterError(_)) |
570                         Err(PaymentSendFailure::PathParameterError(_)) => {
571                                 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
572                                 Err(())
573                         },
574                         Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
575                                 self.retry_payment(payment_id, payment_hash, params)
576                         },
577                         Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
578                                 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
579                                 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
580                                 // means that we are still waiting for our channel monitor update to complete.
581                                 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
582                                         match result {
583                                                 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
584                                                         self.process_path_inflight_htlcs(payment_hash, path);
585                                                 },
586                                                 _ => {},
587                                         }
588                                 }
589
590                                 if let Some(retry) = failed_paths_retry {
591                                         // Always return Ok for the same reason as noted in pay_internal.
592                                         let _ = self.retry_payment(payment_id, payment_hash, &retry);
593                                 }
594                                 Ok(())
595                         },
596                 }
597         }
598
599         /// Removes the payment cached by the given payment hash.
600         ///
601         /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
602         /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
603         pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
604                 self.payment_cache.lock().unwrap().remove(payment_hash);
605         }
606
607         /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
608         /// channel id and direction to the amount being sent through it.
609         ///
610         /// This function should be called whenever we need information about currently used up liquidity
611         /// across payments.
612         fn create_inflight_map(&self) -> InFlightHtlcs {
613                 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
614                 // Make an attempt at finding existing payment information from `payment_cache`. If it
615                 // does not exist, it probably is a fresh payment and we can just return an empty
616                 // HashMap.
617                 for payment_info in self.payment_cache.lock().unwrap().values() {
618                         for path in &payment_info.paths {
619                                 if path.is_empty() { break };
620                                 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
621                                 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
622                                 // the router excludes the payer node. In the following lines, the payer's information is
623                                 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
624                                 // in our sliding window of two.
625                                 let our_node_id: PublicKey = self.payer.node_id();
626                                 let reversed_hops_with_payer = path.iter().rev().skip(1)
627                                         .map(|hop| hop.pubkey)
628                                         .chain(core::iter::once(our_node_id));
629                                 let mut cumulative_msat = 0;
630
631                                 // Taking the reversed vector from above, we zip it with just the reversed hops list to
632                                 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
633                                 // the total amount sent.
634                                 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
635                                         cumulative_msat += next_hop.fee_msat;
636                                         total_inflight_map
637                                                 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
638                                                 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
639                                                 .or_insert(cumulative_msat);
640                                 }
641                         }
642                 }
643
644                 InFlightHtlcs(total_inflight_map)
645         }
646 }
647
648 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
649         invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
650 }
651
652 #[cfg(feature = "std")]
653 fn has_expired(route_params: &RouteParameters) -> bool {
654         if let Some(expiry_time) = route_params.payment_params.expiry_time {
655                 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
656         } else { false }
657 }
658
659 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
660 where
661         P::Target: Payer,
662         L::Target: Logger,
663 {
664         fn handle_event(&self, event: &Event) {
665                 match event {
666                         Event::PaymentPathFailed { payment_hash, path, ..  }
667                         | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
668                         | Event::ProbeSuccessful { payment_hash, path, .. }
669                         | Event::ProbeFailed { payment_hash, path, .. } => {
670                                 self.remove_path_inflight_htlcs(*payment_hash, path);
671                         },
672                         _ => {},
673                 }
674
675                 match event {
676                         Event::PaymentPathFailed {
677                                 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
678                         } => {
679                                 if let Some(short_channel_id) = short_channel_id {
680                                         let path = path.iter().collect::<Vec<_>>();
681                                         self.router.notify_payment_path_failed(&path, *short_channel_id)
682                                 }
683
684                                 if payment_id.is_none() {
685                                         log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
686                                 } else if *payment_failed_permanently {
687                                         log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
688                                         self.payer.abandon_payment(payment_id.unwrap());
689                                 } else if retry.is_none() {
690                                         log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
691                                         self.payer.abandon_payment(payment_id.unwrap());
692                                 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
693                                         // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
694                                         return;
695                                 } else {
696                                         self.payer.abandon_payment(payment_id.unwrap());
697                                 }
698                         },
699                         Event::PaymentFailed { payment_hash, .. } => {
700                                 self.remove_cached_payment(&payment_hash);
701                         },
702                         Event::PaymentPathSuccessful { path, .. } => {
703                                 let path = path.iter().collect::<Vec<_>>();
704                                 self.router.notify_payment_path_successful(&path);
705                         },
706                         Event::PaymentSent { payment_hash, .. } => {
707                                 let mut payment_cache = self.payment_cache.lock().unwrap();
708                                 let attempts = payment_cache
709                                         .remove(payment_hash)
710                                         .map_or(1, |payment_info| payment_info.attempts.count + 1);
711                                 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
712                         },
713                         Event::ProbeSuccessful { payment_hash, path, .. } => {
714                                 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
715                                 let path = path.iter().collect::<Vec<_>>();
716                                 self.router.notify_payment_probe_successful(&path);
717                         },
718                         Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
719                                 if let Some(short_channel_id) = short_channel_id {
720                                         log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
721                                         let path = path.iter().collect::<Vec<_>>();
722                                         self.router.notify_payment_probe_failed(&path, *short_channel_id);
723                                 }
724                         },
725                         _ => {},
726                 }
727
728                 // Delegate to the decorated event handler unless the payment is retried.
729                 self.event_handler.handle_event(event)
730         }
731 }
732
733 /// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
734 /// is traveling in. The direction boolean is determined by checking if the HTLC source's public
735 /// key is less than its destination. See [`InFlightHtlcs::used_liquidity_msat`] for more
736 /// details.
737 pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
738
739 impl InFlightHtlcs {
740         /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
741         /// id.
742         pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
743                 self.0.get(&(channel_scid, source < target)).map(|v| *v)
744         }
745 }
746
747 impl Writeable for InFlightHtlcs {
748         fn write<W: lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
749 }
750
751 impl lightning::util::ser::Readable for InFlightHtlcs {
752         fn read<R: io::Read>(reader: &mut R) -> Result<Self, lightning::ln::msgs::DecodeError> {
753                 let infight_map: HashMap<(u64, bool), u64> = lightning::util::ser::Readable::read(reader)?;
754                 Ok(Self(infight_map))
755         }
756 }
757
758 #[cfg(test)]
759 mod tests {
760         use super::*;
761         use crate::{InvoiceBuilder, Currency};
762         use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
763         use bitcoin_hashes::sha256::Hash as Sha256;
764         use lightning::ln::PaymentPreimage;
765         use lightning::ln::channelmanager;
766         use lightning::ln::features::{ChannelFeatures, NodeFeatures};
767         use lightning::ln::functional_test_utils::*;
768         use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
769         use lightning::routing::gossip::{EffectiveCapacity, NodeId};
770         use lightning::routing::router::{PaymentParameters, Route, RouteHop};
771         use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
772         use lightning::util::test_utils::TestLogger;
773         use lightning::util::errors::APIError;
774         use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
775         use secp256k1::{SecretKey, PublicKey, Secp256k1};
776         use std::cell::RefCell;
777         use std::collections::VecDeque;
778         use std::ops::DerefMut;
779         use std::time::{SystemTime, Duration};
780         use crate::time_utils::tests::SinceEpoch;
781         use crate::DEFAULT_EXPIRY_TIME;
782         use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
783
784         fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
785                 let payment_hash = Sha256::hash(&payment_preimage.0);
786                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
787
788                 InvoiceBuilder::new(Currency::Bitcoin)
789                         .description("test".into())
790                         .payment_hash(payment_hash)
791                         .payment_secret(PaymentSecret([0; 32]))
792                         .duration_since_epoch(duration_since_epoch())
793                         .min_final_cltv_expiry(144)
794                         .amount_milli_satoshis(128)
795                         .build_signed(|hash| {
796                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
797                         })
798                         .unwrap()
799         }
800
801         fn duration_since_epoch() -> Duration {
802                 #[cfg(feature = "std")]
803                         let duration_since_epoch =
804                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
805                 #[cfg(not(feature = "std"))]
806                         let duration_since_epoch = Duration::from_secs(1234567);
807                 duration_since_epoch
808         }
809
810         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
811                 let payment_hash = Sha256::hash(&payment_preimage.0);
812                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
813
814                 InvoiceBuilder::new(Currency::Bitcoin)
815                         .description("test".into())
816                         .payment_hash(payment_hash)
817                         .payment_secret(PaymentSecret([0; 32]))
818                         .duration_since_epoch(duration_since_epoch())
819                         .min_final_cltv_expiry(144)
820                         .build_signed(|hash| {
821                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
822                         })
823                         .unwrap()
824         }
825
826         #[cfg(feature = "std")]
827         fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
828                 let payment_hash = Sha256::hash(&payment_preimage.0);
829                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
830                 let duration = duration_since_epoch()
831                         .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
832                         .unwrap();
833                 InvoiceBuilder::new(Currency::Bitcoin)
834                         .description("test".into())
835                         .payment_hash(payment_hash)
836                         .payment_secret(PaymentSecret([0; 32]))
837                         .duration_since_epoch(duration)
838                         .min_final_cltv_expiry(144)
839                         .amount_milli_satoshis(128)
840                         .build_signed(|hash| {
841                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
842                         })
843                         .unwrap()
844         }
845
846         fn pubkey() -> PublicKey {
847                 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
848         }
849
850         #[test]
851         fn pays_invoice_on_first_attempt() {
852                 let event_handled = core::cell::RefCell::new(false);
853                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
854
855                 let payment_preimage = PaymentPreimage([1; 32]);
856                 let invoice = invoice(payment_preimage);
857                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
858                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
859
860                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
861                 let router = TestRouter::new(TestScorer::new());
862                 let logger = TestLogger::new();
863                 let invoice_payer =
864                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
865
866                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
867                 assert_eq!(*payer.attempts.borrow(), 1);
868
869                 invoice_payer.handle_event(&Event::PaymentSent {
870                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
871                 });
872                 assert_eq!(*event_handled.borrow(), true);
873                 assert_eq!(*payer.attempts.borrow(), 1);
874         }
875
876         #[test]
877         fn pays_invoice_on_retry() {
878                 let event_handled = core::cell::RefCell::new(false);
879                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
880
881                 let payment_preimage = PaymentPreimage([1; 32]);
882                 let invoice = invoice(payment_preimage);
883                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
884                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
885
886                 let payer = TestPayer::new()
887                         .expect_send(Amount::ForInvoice(final_value_msat))
888                         .expect_send(Amount::OnRetry(final_value_msat / 2));
889                 let router = TestRouter::new(TestScorer::new());
890                 let logger = TestLogger::new();
891                 let invoice_payer =
892                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
893
894                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
895                 assert_eq!(*payer.attempts.borrow(), 1);
896
897                 let event = Event::PaymentPathFailed {
898                         payment_id,
899                         payment_hash,
900                         network_update: None,
901                         payment_failed_permanently: false,
902                         all_paths_failed: false,
903                         path: TestRouter::path_for_value(final_value_msat),
904                         short_channel_id: None,
905                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
906                 };
907                 invoice_payer.handle_event(&event);
908                 assert_eq!(*event_handled.borrow(), false);
909                 assert_eq!(*payer.attempts.borrow(), 2);
910
911                 invoice_payer.handle_event(&Event::PaymentSent {
912                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
913                 });
914                 assert_eq!(*event_handled.borrow(), true);
915                 assert_eq!(*payer.attempts.borrow(), 2);
916         }
917
918         #[test]
919         fn pays_invoice_on_partial_failure() {
920                 let event_handler = |_: &_| { panic!() };
921
922                 let payment_preimage = PaymentPreimage([1; 32]);
923                 let invoice = invoice(payment_preimage);
924                 let retry = TestRouter::retry_for_invoice(&invoice);
925                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
926
927                 let payer = TestPayer::new()
928                         .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
929                         .fails_with_partial_failure(retry, OnAttempt(2), None)
930                         .expect_send(Amount::ForInvoice(final_value_msat))
931                         .expect_send(Amount::OnRetry(final_value_msat / 2))
932                         .expect_send(Amount::OnRetry(final_value_msat / 2));
933                 let router = TestRouter::new(TestScorer::new());
934                 let logger = TestLogger::new();
935                 let invoice_payer =
936                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
937
938                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
939         }
940
941         #[test]
942         fn retries_payment_path_for_unknown_payment() {
943                 let event_handled = core::cell::RefCell::new(false);
944                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
945
946                 let payment_preimage = PaymentPreimage([1; 32]);
947                 let invoice = invoice(payment_preimage);
948                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
949                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
950
951                 let payer = TestPayer::new()
952                         .expect_send(Amount::OnRetry(final_value_msat / 2))
953                         .expect_send(Amount::OnRetry(final_value_msat / 2));
954                 let router = TestRouter::new(TestScorer::new());
955                 let logger = TestLogger::new();
956                 let invoice_payer =
957                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
958
959                 let payment_id = Some(PaymentId([1; 32]));
960                 let event = Event::PaymentPathFailed {
961                         payment_id,
962                         payment_hash,
963                         network_update: None,
964                         payment_failed_permanently: false,
965                         all_paths_failed: false,
966                         path: TestRouter::path_for_value(final_value_msat),
967                         short_channel_id: None,
968                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
969                 };
970                 invoice_payer.handle_event(&event);
971                 assert_eq!(*event_handled.borrow(), false);
972                 assert_eq!(*payer.attempts.borrow(), 1);
973
974                 invoice_payer.handle_event(&event);
975                 assert_eq!(*event_handled.borrow(), false);
976                 assert_eq!(*payer.attempts.borrow(), 2);
977
978                 invoice_payer.handle_event(&Event::PaymentSent {
979                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
980                 });
981                 assert_eq!(*event_handled.borrow(), true);
982                 assert_eq!(*payer.attempts.borrow(), 2);
983         }
984
985         #[test]
986         fn fails_paying_invoice_after_max_retry_counts() {
987                 let event_handled = core::cell::RefCell::new(false);
988                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
989
990                 let payment_preimage = PaymentPreimage([1; 32]);
991                 let invoice = invoice(payment_preimage);
992                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
993
994                 let payer = TestPayer::new()
995                         .expect_send(Amount::ForInvoice(final_value_msat))
996                         .expect_send(Amount::OnRetry(final_value_msat / 2))
997                         .expect_send(Amount::OnRetry(final_value_msat / 2));
998                 let router = TestRouter::new(TestScorer::new());
999                 let logger = TestLogger::new();
1000                 let invoice_payer =
1001                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1002
1003                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1004                 assert_eq!(*payer.attempts.borrow(), 1);
1005
1006                 let event = Event::PaymentPathFailed {
1007                         payment_id,
1008                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1009                         network_update: None,
1010                         payment_failed_permanently: false,
1011                         all_paths_failed: true,
1012                         path: TestRouter::path_for_value(final_value_msat),
1013                         short_channel_id: None,
1014                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1015                 };
1016                 invoice_payer.handle_event(&event);
1017                 assert_eq!(*event_handled.borrow(), false);
1018                 assert_eq!(*payer.attempts.borrow(), 2);
1019
1020                 let event = Event::PaymentPathFailed {
1021                         payment_id,
1022                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1023                         network_update: None,
1024                         payment_failed_permanently: false,
1025                         all_paths_failed: false,
1026                         path: TestRouter::path_for_value(final_value_msat / 2),
1027                         short_channel_id: None,
1028                         retry: Some(RouteParameters {
1029                                 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1030                         }),
1031                 };
1032                 invoice_payer.handle_event(&event);
1033                 assert_eq!(*event_handled.borrow(), false);
1034                 assert_eq!(*payer.attempts.borrow(), 3);
1035
1036                 invoice_payer.handle_event(&event);
1037                 assert_eq!(*event_handled.borrow(), true);
1038                 assert_eq!(*payer.attempts.borrow(), 3);
1039         }
1040
1041         #[cfg(feature = "std")]
1042         #[test]
1043         fn fails_paying_invoice_after_max_retry_timeout() {
1044                 let event_handled = core::cell::RefCell::new(false);
1045                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1046
1047                 let payment_preimage = PaymentPreimage([1; 32]);
1048                 let invoice = invoice(payment_preimage);
1049                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1050
1051                 let payer = TestPayer::new()
1052                         .expect_send(Amount::ForInvoice(final_value_msat))
1053                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1054
1055                 let router = TestRouter::new(TestScorer::new());
1056                 let logger = TestLogger::new();
1057                 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1058
1059                 let invoice_payer =
1060                         InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1061
1062                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1063                 assert_eq!(*payer.attempts.borrow(), 1);
1064
1065                 let event = Event::PaymentPathFailed {
1066                         payment_id,
1067                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1068                         network_update: None,
1069                         payment_failed_permanently: false,
1070                         all_paths_failed: true,
1071                         path: TestRouter::path_for_value(final_value_msat),
1072                         short_channel_id: None,
1073                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1074                 };
1075                 invoice_payer.handle_event(&event);
1076                 assert_eq!(*event_handled.borrow(), false);
1077                 assert_eq!(*payer.attempts.borrow(), 2);
1078
1079                 SinceEpoch::advance(Duration::from_secs(121));
1080
1081                 invoice_payer.handle_event(&event);
1082                 assert_eq!(*event_handled.borrow(), true);
1083                 assert_eq!(*payer.attempts.borrow(), 2);
1084         }
1085
1086         #[test]
1087         fn fails_paying_invoice_with_missing_retry_params() {
1088                 let event_handled = core::cell::RefCell::new(false);
1089                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1090
1091                 let payment_preimage = PaymentPreimage([1; 32]);
1092                 let invoice = invoice(payment_preimage);
1093                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1094
1095                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1096                 let router = TestRouter::new(TestScorer::new());
1097                 let logger = TestLogger::new();
1098                 let invoice_payer =
1099                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1100
1101                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1102                 assert_eq!(*payer.attempts.borrow(), 1);
1103
1104                 let event = Event::PaymentPathFailed {
1105                         payment_id,
1106                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1107                         network_update: None,
1108                         payment_failed_permanently: false,
1109                         all_paths_failed: false,
1110                         path: vec![],
1111                         short_channel_id: None,
1112                         retry: None,
1113                 };
1114                 invoice_payer.handle_event(&event);
1115                 assert_eq!(*event_handled.borrow(), true);
1116                 assert_eq!(*payer.attempts.borrow(), 1);
1117         }
1118
1119         // Expiration is checked only in an std environment
1120         #[cfg(feature = "std")]
1121         #[test]
1122         fn fails_paying_invoice_after_expiration() {
1123                 let event_handled = core::cell::RefCell::new(false);
1124                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1125
1126                 let payer = TestPayer::new();
1127                 let router = TestRouter::new(TestScorer::new());
1128                 let logger = TestLogger::new();
1129                 let invoice_payer =
1130                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1131
1132                 let payment_preimage = PaymentPreimage([1; 32]);
1133                 let invoice = expired_invoice(payment_preimage);
1134                 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1135                         assert_eq!(msg, "Invoice expired prior to send");
1136                 } else { panic!("Expected Invoice Error"); }
1137         }
1138
1139         // Expiration is checked only in an std environment
1140         #[cfg(feature = "std")]
1141         #[test]
1142         fn fails_retrying_invoice_after_expiration() {
1143                 let event_handled = core::cell::RefCell::new(false);
1144                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1145
1146                 let payment_preimage = PaymentPreimage([1; 32]);
1147                 let invoice = invoice(payment_preimage);
1148                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1149
1150                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1151                 let router = TestRouter::new(TestScorer::new());
1152                 let logger = TestLogger::new();
1153                 let invoice_payer =
1154                         InvoicePayer::new(&payer, router,  &logger, event_handler, Retry::Attempts(2));
1155
1156                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1157                 assert_eq!(*payer.attempts.borrow(), 1);
1158
1159                 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1160                 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1161                         .checked_sub(Duration::from_secs(2)).unwrap()
1162                         .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1163                 let event = Event::PaymentPathFailed {
1164                         payment_id,
1165                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1166                         network_update: None,
1167                         payment_failed_permanently: false,
1168                         all_paths_failed: false,
1169                         path: vec![],
1170                         short_channel_id: None,
1171                         retry: Some(retry_data),
1172                 };
1173                 invoice_payer.handle_event(&event);
1174                 assert_eq!(*event_handled.borrow(), true);
1175                 assert_eq!(*payer.attempts.borrow(), 1);
1176         }
1177
1178         #[test]
1179         fn fails_paying_invoice_after_retry_error() {
1180                 let event_handled = core::cell::RefCell::new(false);
1181                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1182
1183                 let payment_preimage = PaymentPreimage([1; 32]);
1184                 let invoice = invoice(payment_preimage);
1185                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1186
1187                 let payer = TestPayer::new()
1188                         .fails_on_attempt(2)
1189                         .expect_send(Amount::ForInvoice(final_value_msat))
1190                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1191                 let router = TestRouter::new(TestScorer::new());
1192                 let logger = TestLogger::new();
1193                 let invoice_payer =
1194                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1195
1196                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1197                 assert_eq!(*payer.attempts.borrow(), 1);
1198
1199                 let event = Event::PaymentPathFailed {
1200                         payment_id,
1201                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1202                         network_update: None,
1203                         payment_failed_permanently: false,
1204                         all_paths_failed: false,
1205                         path: TestRouter::path_for_value(final_value_msat / 2),
1206                         short_channel_id: None,
1207                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1208                 };
1209                 invoice_payer.handle_event(&event);
1210                 assert_eq!(*event_handled.borrow(), true);
1211                 assert_eq!(*payer.attempts.borrow(), 2);
1212         }
1213
1214         #[test]
1215         fn fails_paying_invoice_after_rejected_by_payee() {
1216                 let event_handled = core::cell::RefCell::new(false);
1217                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1218
1219                 let payment_preimage = PaymentPreimage([1; 32]);
1220                 let invoice = invoice(payment_preimage);
1221                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1222
1223                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1224                 let router = TestRouter::new(TestScorer::new());
1225                 let logger = TestLogger::new();
1226                 let invoice_payer =
1227                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1228
1229                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1230                 assert_eq!(*payer.attempts.borrow(), 1);
1231
1232                 let event = Event::PaymentPathFailed {
1233                         payment_id,
1234                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1235                         network_update: None,
1236                         payment_failed_permanently: true,
1237                         all_paths_failed: false,
1238                         path: vec![],
1239                         short_channel_id: None,
1240                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1241                 };
1242                 invoice_payer.handle_event(&event);
1243                 assert_eq!(*event_handled.borrow(), true);
1244                 assert_eq!(*payer.attempts.borrow(), 1);
1245         }
1246
1247         #[test]
1248         fn fails_repaying_invoice_with_pending_payment() {
1249                 let event_handled = core::cell::RefCell::new(false);
1250                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1251
1252                 let payment_preimage = PaymentPreimage([1; 32]);
1253                 let invoice = invoice(payment_preimage);
1254                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1255
1256                 let payer = TestPayer::new()
1257                         .expect_send(Amount::ForInvoice(final_value_msat))
1258                         .expect_send(Amount::ForInvoice(final_value_msat));
1259                 let router = TestRouter::new(TestScorer::new());
1260                 let logger = TestLogger::new();
1261                 let invoice_payer =
1262                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1263
1264                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1265
1266                 // Cannot repay an invoice pending payment.
1267                 match invoice_payer.pay_invoice(&invoice) {
1268                         Err(PaymentError::Invoice("payment pending")) => {},
1269                         Err(_) => panic!("unexpected error"),
1270                         Ok(_) => panic!("expected invoice error"),
1271                 }
1272
1273                 // Can repay an invoice once cleared from cache.
1274                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1275                 invoice_payer.remove_cached_payment(&payment_hash);
1276                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1277
1278                 // Cannot retry paying an invoice if cleared from cache.
1279                 invoice_payer.remove_cached_payment(&payment_hash);
1280                 let event = Event::PaymentPathFailed {
1281                         payment_id,
1282                         payment_hash,
1283                         network_update: None,
1284                         payment_failed_permanently: false,
1285                         all_paths_failed: false,
1286                         path: vec![],
1287                         short_channel_id: None,
1288                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1289                 };
1290                 invoice_payer.handle_event(&event);
1291                 assert_eq!(*event_handled.borrow(), true);
1292         }
1293
1294         #[test]
1295         fn fails_paying_invoice_with_routing_errors() {
1296                 let payer = TestPayer::new();
1297                 let router = FailingRouter {};
1298                 let logger = TestLogger::new();
1299                 let invoice_payer =
1300                         InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1301
1302                 let payment_preimage = PaymentPreimage([1; 32]);
1303                 let invoice = invoice(payment_preimage);
1304                 match invoice_payer.pay_invoice(&invoice) {
1305                         Err(PaymentError::Routing(_)) => {},
1306                         Err(_) => panic!("unexpected error"),
1307                         Ok(_) => panic!("expected routing error"),
1308                 }
1309         }
1310
1311         #[test]
1312         fn fails_paying_invoice_with_sending_errors() {
1313                 let payment_preimage = PaymentPreimage([1; 32]);
1314                 let invoice = invoice(payment_preimage);
1315                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1316
1317                 let payer = TestPayer::new()
1318                         .fails_on_attempt(1)
1319                         .expect_send(Amount::ForInvoice(final_value_msat));
1320                 let router = TestRouter::new(TestScorer::new());
1321                 let logger = TestLogger::new();
1322                 let invoice_payer =
1323                         InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1324
1325                 match invoice_payer.pay_invoice(&invoice) {
1326                         Err(PaymentError::Sending(_)) => {},
1327                         Err(_) => panic!("unexpected error"),
1328                         Ok(_) => panic!("expected sending error"),
1329                 }
1330         }
1331
1332         #[test]
1333         fn pays_zero_value_invoice_using_amount() {
1334                 let event_handled = core::cell::RefCell::new(false);
1335                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1336
1337                 let payment_preimage = PaymentPreimage([1; 32]);
1338                 let invoice = zero_value_invoice(payment_preimage);
1339                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1340                 let final_value_msat = 100;
1341
1342                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1343                 let router = TestRouter::new(TestScorer::new());
1344                 let logger = TestLogger::new();
1345                 let invoice_payer =
1346                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1347
1348                 let payment_id =
1349                         Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1350                 assert_eq!(*payer.attempts.borrow(), 1);
1351
1352                 invoice_payer.handle_event(&Event::PaymentSent {
1353                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1354                 });
1355                 assert_eq!(*event_handled.borrow(), true);
1356                 assert_eq!(*payer.attempts.borrow(), 1);
1357         }
1358
1359         #[test]
1360         fn fails_paying_zero_value_invoice_with_amount() {
1361                 let event_handled = core::cell::RefCell::new(false);
1362                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1363
1364                 let payer = TestPayer::new();
1365                 let router = TestRouter::new(TestScorer::new());
1366                 let logger = TestLogger::new();
1367                 let invoice_payer =
1368                         InvoicePayer::new(&payer, router,  &logger, event_handler, Retry::Attempts(0));
1369
1370                 let payment_preimage = PaymentPreimage([1; 32]);
1371                 let invoice = invoice(payment_preimage);
1372
1373                 // Cannot repay an invoice pending payment.
1374                 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1375                         Err(PaymentError::Invoice("amount unexpected")) => {},
1376                         Err(_) => panic!("unexpected error"),
1377                         Ok(_) => panic!("expected invoice error"),
1378                 }
1379         }
1380
1381         #[test]
1382         fn pays_pubkey_with_amount() {
1383                 let event_handled = core::cell::RefCell::new(false);
1384                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1385
1386                 let pubkey = pubkey();
1387                 let payment_preimage = PaymentPreimage([1; 32]);
1388                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1389                 let final_value_msat = 100;
1390                 let final_cltv_expiry_delta = 42;
1391
1392                 let payer = TestPayer::new()
1393                         .expect_send(Amount::Spontaneous(final_value_msat))
1394                         .expect_send(Amount::OnRetry(final_value_msat));
1395                 let router = TestRouter::new(TestScorer::new());
1396                 let logger = TestLogger::new();
1397                 let invoice_payer =
1398                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1399
1400                 let payment_id = Some(invoice_payer.pay_pubkey(
1401                                 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1402                         ).unwrap());
1403                 assert_eq!(*payer.attempts.borrow(), 1);
1404
1405                 let retry = RouteParameters {
1406                         payment_params: PaymentParameters::for_keysend(pubkey),
1407                         final_value_msat,
1408                         final_cltv_expiry_delta,
1409                 };
1410                 let event = Event::PaymentPathFailed {
1411                         payment_id,
1412                         payment_hash,
1413                         network_update: None,
1414                         payment_failed_permanently: false,
1415                         all_paths_failed: false,
1416                         path: vec![],
1417                         short_channel_id: None,
1418                         retry: Some(retry),
1419                 };
1420                 invoice_payer.handle_event(&event);
1421                 assert_eq!(*event_handled.borrow(), false);
1422                 assert_eq!(*payer.attempts.borrow(), 2);
1423
1424                 invoice_payer.handle_event(&Event::PaymentSent {
1425                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1426                 });
1427                 assert_eq!(*event_handled.borrow(), true);
1428                 assert_eq!(*payer.attempts.borrow(), 2);
1429         }
1430
1431         #[test]
1432         fn scores_failed_channel() {
1433                 let event_handled = core::cell::RefCell::new(false);
1434                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1435
1436                 let payment_preimage = PaymentPreimage([1; 32]);
1437                 let invoice = invoice(payment_preimage);
1438                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1439                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1440                 let path = TestRouter::path_for_value(final_value_msat);
1441                 let short_channel_id = Some(path[0].short_channel_id);
1442
1443                 // Expect that scorer is given short_channel_id upon handling the event.
1444                 let payer = TestPayer::new()
1445                         .expect_send(Amount::ForInvoice(final_value_msat))
1446                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1447                 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1448                         path: path.clone(), short_channel_id: path[0].short_channel_id,
1449                 });
1450                 let router = TestRouter::new(scorer);
1451                 let logger = TestLogger::new();
1452                 let invoice_payer =
1453                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1454
1455                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1456                 let event = Event::PaymentPathFailed {
1457                         payment_id,
1458                         payment_hash,
1459                         network_update: None,
1460                         payment_failed_permanently: false,
1461                         all_paths_failed: false,
1462                         path,
1463                         short_channel_id,
1464                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1465                 };
1466                 invoice_payer.handle_event(&event);
1467         }
1468
1469         #[test]
1470         fn scores_successful_channels() {
1471                 let event_handled = core::cell::RefCell::new(false);
1472                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1473
1474                 let payment_preimage = PaymentPreimage([1; 32]);
1475                 let invoice = invoice(payment_preimage);
1476                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1477                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1478                 let route = TestRouter::route_for_value(final_value_msat);
1479
1480                 // Expect that scorer is given short_channel_id upon handling the event.
1481                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1482                 let scorer = TestScorer::new()
1483                         .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1484                         .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1485                 let router = TestRouter::new(scorer);
1486                 let logger = TestLogger::new();
1487                 let invoice_payer =
1488                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1489
1490                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1491                 let event = Event::PaymentPathSuccessful {
1492                         payment_id, payment_hash, path: route.paths[0].clone()
1493                 };
1494                 invoice_payer.handle_event(&event);
1495                 let event = Event::PaymentPathSuccessful {
1496                         payment_id, payment_hash, path: route.paths[1].clone()
1497                 };
1498                 invoice_payer.handle_event(&event);
1499         }
1500
1501         #[test]
1502         fn generates_correct_inflight_map_data() {
1503                 let event_handled = core::cell::RefCell::new(false);
1504                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1505
1506                 let payment_preimage = PaymentPreimage([1; 32]);
1507                 let invoice = invoice(payment_preimage);
1508                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1509                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1510
1511                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1512                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1513                 let route = TestRouter::route_for_value(final_value_msat);
1514                 let router = TestRouter::new(TestScorer::new());
1515                 let logger = TestLogger::new();
1516                 let invoice_payer =
1517                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1518
1519                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1520
1521                 let inflight_map = invoice_payer.create_inflight_map();
1522                 // First path check
1523                 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1524                 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1525                 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1526
1527                 // Second path check
1528                 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1529                 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1530
1531                 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1532                         payment_id, payment_hash, path: route.paths[0].clone()
1533                 });
1534
1535                 let inflight_map = invoice_payer.create_inflight_map();
1536
1537                 assert_eq!(inflight_map.0.get(&(0, false)), None);
1538                 assert_eq!(inflight_map.0.get(&(1, true)), None);
1539                 assert_eq!(inflight_map.0.get(&(2, false)), None);
1540
1541                 // Second path should still be inflight
1542                 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1543                 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1544         }
1545
1546         #[test]
1547         fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1548                 // First, let's just send a payment through, but only make sure one of the path completes
1549                 let event_handled = core::cell::RefCell::new(false);
1550                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1551
1552                 let payment_preimage = PaymentPreimage([1; 32]);
1553                 let payment_invoice = invoice(payment_preimage);
1554                 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1555                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1556
1557                 let payer = TestPayer::new()
1558                         .expect_send(Amount::ForInvoice(final_value_msat))
1559                         .expect_send(Amount::ForInvoice(final_value_msat));
1560                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1561                 let route = TestRouter::route_for_value(final_value_msat);
1562                 let scorer = TestScorer::new()
1563                         // 1st invoice, 1st path
1564                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1565                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1566                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1567                         // 1st invoice, 2nd path
1568                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1569                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1570                         // 2nd invoice, 1st path
1571                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1572                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1573                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1574                         // 2nd invoice, 2nd path
1575                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1576                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1577                 let router = TestRouter::new(scorer);
1578                 let logger = TestLogger::new();
1579                 let invoice_payer =
1580                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1581
1582                 // Succeed 1st path, leave 2nd path inflight
1583                 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1584                 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1585                         payment_id, payment_hash, path: route.paths[0].clone()
1586                 });
1587
1588                 // Let's pay a second invoice that will be using the same path. This should trigger the
1589                 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1590                 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1591                 // have 64 msats inflight for paths considering the channel with scid of 1.
1592                 let payment_preimage_2 = PaymentPreimage([2; 32]);
1593                 let payment_invoice_2 = invoice(payment_preimage_2);
1594                 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1595         }
1596
1597         #[test]
1598         fn considers_inflight_htlcs_between_retries() {
1599                 // First, let's just send a payment through, but only make sure one of the path completes
1600                 let event_handled = core::cell::RefCell::new(false);
1601                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1602
1603                 let payment_preimage = PaymentPreimage([1; 32]);
1604                 let payment_invoice = invoice(payment_preimage);
1605                 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1606                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1607
1608                 let payer = TestPayer::new()
1609                         .expect_send(Amount::ForInvoice(final_value_msat))
1610                         .expect_send(Amount::OnRetry(final_value_msat / 2))
1611                         .expect_send(Amount::OnRetry(final_value_msat / 4));
1612                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1613                 let scorer = TestScorer::new()
1614                         // 1st invoice, 1st path
1615                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1616                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1617                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1618                         // 1st invoice, 2nd path
1619                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1620                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1621                         // Retry 1, 1st path
1622                         .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1623                         .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1624                         .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1625                         // Retry 1, 2nd path
1626                         .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1627                         .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1628                         // Retry 2, 1st path
1629                         .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1630                         .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1631                         .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1632                         // Retry 2, 2nd path
1633                         .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1634                         .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1635                 let router = TestRouter::new(scorer);
1636                 let logger = TestLogger::new();
1637                 let invoice_payer =
1638                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1639
1640                 // Fail 1st path, leave 2nd path inflight
1641                 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1642                 invoice_payer.handle_event(&Event::PaymentPathFailed {
1643                         payment_id,
1644                         payment_hash,
1645                         network_update: None,
1646                         payment_failed_permanently: false,
1647                         all_paths_failed: false,
1648                         path: TestRouter::path_for_value(final_value_msat),
1649                         short_channel_id: None,
1650                         retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1651                 });
1652
1653                 // Fails again the 1st path of our retry
1654                 invoice_payer.handle_event(&Event::PaymentPathFailed {
1655                         payment_id,
1656                         payment_hash,
1657                         network_update: None,
1658                         payment_failed_permanently: false,
1659                         all_paths_failed: false,
1660                         path: TestRouter::path_for_value(final_value_msat / 2),
1661                         short_channel_id: None,
1662                         retry: Some(RouteParameters {
1663                                 final_value_msat: final_value_msat / 4,
1664                                 ..TestRouter::retry_for_invoice(&payment_invoice)
1665                         }),
1666                 });
1667         }
1668
1669         #[test]
1670         fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1671                 let event_handled = core::cell::RefCell::new(false);
1672                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1673
1674                 let payment_preimage = PaymentPreimage([1; 32]);
1675                 let invoice_to_pay = invoice(payment_preimage);
1676                 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1677
1678                 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1679                 let payer = TestPayer::new()
1680                         .fails_with_partial_failure(
1681                                 retry.clone(), OnAttempt(1),
1682                                 Some(vec![
1683                                         Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1684                                 ]))
1685                         .expect_send(Amount::ForInvoice(final_value_msat));
1686
1687                 let router = TestRouter::new(TestScorer::new());
1688                 let logger = TestLogger::new();
1689                 let invoice_payer =
1690                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1691
1692                 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1693                 let inflight_map = invoice_payer.create_inflight_map();
1694
1695                 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1696                 // inflight map because retries are disabled.
1697                 assert_eq!(inflight_map.0.len(), 2);
1698         }
1699
1700         #[test]
1701         fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1702                 let event_handled = core::cell::RefCell::new(false);
1703                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1704
1705                 let payment_preimage = PaymentPreimage([1; 32]);
1706                 let invoice_to_pay = invoice(payment_preimage);
1707                 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1708
1709                 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1710                 let payer = TestPayer::new()
1711                         .fails_with_partial_failure(
1712                                 retry.clone(), OnAttempt(1),
1713                                 Some(vec![
1714                                         Ok(()), Err(MonitorUpdateInProgress)
1715                                 ]))
1716                         .expect_send(Amount::ForInvoice(final_value_msat));
1717
1718                 let router = TestRouter::new(TestScorer::new());
1719                 let logger = TestLogger::new();
1720                 let invoice_payer =
1721                         InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1722
1723                 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1724                 let inflight_map = invoice_payer.create_inflight_map();
1725
1726                 // All paths successful, hence we check of the existence of all 5 hops.
1727                 assert_eq!(inflight_map.0.len(), 5);
1728         }
1729
1730         struct TestRouter {
1731                 scorer: RefCell<TestScorer>,
1732         }
1733
1734         impl TestRouter {
1735                 fn new(scorer: TestScorer) -> Self {
1736                         TestRouter { scorer: RefCell::new(scorer) }
1737                 }
1738
1739                 fn route_for_value(final_value_msat: u64) -> Route {
1740                         Route {
1741                                 paths: vec![
1742                                         vec![
1743                                                 RouteHop {
1744                                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1745                                                         channel_features: ChannelFeatures::empty(),
1746                                                         node_features: NodeFeatures::empty(),
1747                                                         short_channel_id: 0,
1748                                                         fee_msat: 10,
1749                                                         cltv_expiry_delta: 0
1750                                                 },
1751                                                 RouteHop {
1752                                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1753                                                         channel_features: ChannelFeatures::empty(),
1754                                                         node_features: NodeFeatures::empty(),
1755                                                         short_channel_id: 1,
1756                                                         fee_msat: 20,
1757                                                         cltv_expiry_delta: 0
1758                                                 },
1759                                                 RouteHop {
1760                                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1761                                                         channel_features: ChannelFeatures::empty(),
1762                                                         node_features: NodeFeatures::empty(),
1763                                                         short_channel_id: 2,
1764                                                         fee_msat: final_value_msat / 2,
1765                                                         cltv_expiry_delta: 0
1766                                                 },
1767                                         ],
1768                                         vec![
1769                                                 RouteHop {
1770                                                         pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1771                                                         channel_features: ChannelFeatures::empty(),
1772                                                         node_features: NodeFeatures::empty(),
1773                                                         short_channel_id: 3,
1774                                                         fee_msat: 10,
1775                                                         cltv_expiry_delta: 144
1776                                                 },
1777                                                 RouteHop {
1778                                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1779                                                         channel_features: ChannelFeatures::empty(),
1780                                                         node_features: NodeFeatures::empty(),
1781                                                         short_channel_id: 4,
1782                                                         fee_msat: final_value_msat / 2,
1783                                                         cltv_expiry_delta: 144
1784                                                 }
1785                                         ],
1786                                 ],
1787                                 payment_params: None,
1788                         }
1789                 }
1790
1791                 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1792                         TestRouter::route_for_value(final_value_msat).paths[0].clone()
1793                 }
1794
1795                 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1796                         let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1797                                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1798                                 .with_route_hints(invoice.route_hints());
1799                         if let Some(features) = invoice.features() {
1800                                 payment_params = payment_params.with_features(features.clone());
1801                         }
1802                         let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1803                         RouteParameters {
1804                                 payment_params,
1805                                 final_value_msat,
1806                                 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1807                         }
1808                 }
1809         }
1810
1811         impl Router for TestRouter {
1812                 fn find_route(
1813                         &self, payer: &PublicKey, route_params: &RouteParameters,
1814                         _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1815                 ) -> Result<Route, LightningError> {
1816                         // Simulate calling the Scorer just as you would in find_route
1817                         let route = Self::route_for_value(route_params.final_value_msat);
1818                         let mut locked_scorer = self.scorer.lock();
1819                         let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1820                         for path in route.paths {
1821                                 let mut aggregate_msat = 0u64;
1822                                 for (idx, hop) in path.iter().rev().enumerate() {
1823                                         aggregate_msat += hop.fee_msat;
1824                                         let usage = ChannelUsage {
1825                                                 amount_msat: aggregate_msat,
1826                                                 inflight_htlc_msat: 0,
1827                                                 effective_capacity: EffectiveCapacity::Unknown,
1828                                         };
1829
1830                                         // Since the path is reversed, the last element in our iteration is the first
1831                                         // hop.
1832                                         if idx == path.len() - 1 {
1833                                                 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1834                                         } else {
1835                                                 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1836                                         }
1837                                 }
1838                         }
1839
1840                         Ok(Route {
1841                                 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1842                         })
1843                 }
1844
1845                 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1846                         self.scorer.lock().payment_path_failed(path, short_channel_id);
1847                 }
1848
1849                 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1850                         self.scorer.lock().payment_path_successful(path);
1851                 }
1852
1853                 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1854                         self.scorer.lock().probe_successful(path);
1855                 }
1856
1857                 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1858                         self.scorer.lock().probe_failed(path, short_channel_id);
1859                 }
1860         }
1861
1862         struct FailingRouter;
1863
1864         impl Router for FailingRouter {
1865                 fn find_route(
1866                         &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1867                         _inflight_htlcs: InFlightHtlcs
1868                 ) -> Result<Route, LightningError> {
1869                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1870                 }
1871
1872                 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1873
1874                 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1875
1876                 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1877
1878                 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1879         }
1880
1881         struct TestScorer {
1882                 event_expectations: Option<VecDeque<TestResult>>,
1883                 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1884         }
1885
1886         #[derive(Debug)]
1887         enum TestResult {
1888                 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1889                 PaymentSuccess { path: Vec<RouteHop> },
1890         }
1891
1892         impl TestScorer {
1893                 fn new() -> Self {
1894                         Self {
1895                                 event_expectations: None,
1896                                 scorer_expectations: RefCell::new(None),
1897                         }
1898                 }
1899
1900                 fn expect(mut self, expectation: TestResult) -> Self {
1901                         self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1902                         self
1903                 }
1904
1905                 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1906                         self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1907                         self
1908                 }
1909         }
1910
1911         #[cfg(c_bindings)]
1912         impl lightning::util::ser::Writeable for TestScorer {
1913                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1914         }
1915
1916         impl Score for TestScorer {
1917                 fn channel_penalty_msat(
1918                         &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1919                 ) -> u64 {
1920                         if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1921                                 match scorer_expectations.pop_front() {
1922                                         Some(expectation) => {
1923                                                 assert_eq!(expectation.amount_msat, usage.amount_msat);
1924                                                 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1925                                         },
1926                                         None => {},
1927                                 }
1928                         }
1929                         0
1930                 }
1931
1932                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1933                         if let Some(expectations) = &mut self.event_expectations {
1934                                 match expectations.pop_front() {
1935                                         Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1936                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1937                                                 assert_eq!(actual_short_channel_id, short_channel_id);
1938                                         },
1939                                         Some(TestResult::PaymentSuccess { path }) => {
1940                                                 panic!("Unexpected successful payment path: {:?}", path)
1941                                         },
1942                                         None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1943                                 }
1944                         }
1945                 }
1946
1947                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1948                         if let Some(expectations) = &mut self.event_expectations {
1949                                 match expectations.pop_front() {
1950                                         Some(TestResult::PaymentFailure { path, .. }) => {
1951                                                 panic!("Unexpected payment path failure: {:?}", path)
1952                                         },
1953                                         Some(TestResult::PaymentSuccess { path }) => {
1954                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1955                                         },
1956                                         None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1957                                 }
1958                         }
1959                 }
1960
1961                 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1962                         if let Some(expectations) = &mut self.event_expectations {
1963                                 match expectations.pop_front() {
1964                                         Some(TestResult::PaymentFailure { path, .. }) => {
1965                                                 panic!("Unexpected failed payment path: {:?}", path)
1966                                         },
1967                                         Some(TestResult::PaymentSuccess { path }) => {
1968                                                 panic!("Unexpected successful payment path: {:?}", path)
1969                                         },
1970                                         None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1971                                 }
1972                         }
1973                 }
1974                 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1975                         if let Some(expectations) = &mut self.event_expectations {
1976                                 match expectations.pop_front() {
1977                                         Some(TestResult::PaymentFailure { path, .. }) => {
1978                                                 panic!("Unexpected payment path failure: {:?}", path)
1979                                         },
1980                                         Some(TestResult::PaymentSuccess { path }) => {
1981                                                 panic!("Unexpected successful payment path: {:?}", path)
1982                                         },
1983                                         None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1984                                 }
1985                         }
1986                 }
1987         }
1988
1989         impl Drop for TestScorer {
1990                 fn drop(&mut self) {
1991                         if std::thread::panicking() {
1992                                 return;
1993                         }
1994
1995                         if let Some(event_expectations) = &self.event_expectations {
1996                                 if !event_expectations.is_empty() {
1997                                         panic!("Unsatisfied event expectations: {:?}", event_expectations);
1998                                 }
1999                         }
2000
2001                         if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2002                                 if !scorer_expectations.is_empty() {
2003                                         panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2004                                 }
2005                         }
2006                 }
2007         }
2008
2009         struct TestPayer {
2010                 expectations: core::cell::RefCell<VecDeque<Amount>>,
2011                 attempts: core::cell::RefCell<usize>,
2012                 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2013         }
2014
2015         #[derive(Clone, Debug, PartialEq, Eq)]
2016         enum Amount {
2017                 ForInvoice(u64),
2018                 Spontaneous(u64),
2019                 OnRetry(u64),
2020         }
2021
2022         struct OnAttempt(usize);
2023
2024         impl TestPayer {
2025                 fn new() -> Self {
2026                         Self {
2027                                 expectations: core::cell::RefCell::new(VecDeque::new()),
2028                                 attempts: core::cell::RefCell::new(0),
2029                                 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2030                         }
2031                 }
2032
2033                 fn expect_send(self, value_msat: Amount) -> Self {
2034                         self.expectations.borrow_mut().push_back(value_msat);
2035                         self
2036                 }
2037
2038                 fn fails_on_attempt(self, attempt: usize) -> Self {
2039                         let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2040                         self.fails_with(failure, OnAttempt(attempt))
2041                 }
2042
2043                 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2044                         self.fails_with(PaymentSendFailure::PartialFailure {
2045                                 results: results.unwrap_or(vec![]),
2046                                 failed_paths_retry: Some(retry),
2047                                 payment_id: PaymentId([1; 32]),
2048                         }, attempt)
2049                 }
2050
2051                 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2052                         self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2053                         self
2054                 }
2055
2056                 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2057                         let mut attempts = self.attempts.borrow_mut();
2058                         *attempts += 1;
2059
2060                         match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2061                                 Some(failure) => Err(failure),
2062                                 None => Ok(PaymentId([1; 32])),
2063                         }
2064                 }
2065
2066                 fn check_value_msats(&self, actual_value_msats: Amount) {
2067                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
2068                         if let Some(expected_value_msats) = expected_value_msats {
2069                                 assert_eq!(actual_value_msats, expected_value_msats);
2070                         } else {
2071                                 panic!("Unexpected amount: {:?}", actual_value_msats);
2072                         }
2073                 }
2074         }
2075
2076         impl Drop for TestPayer {
2077                 fn drop(&mut self) {
2078                         if std::thread::panicking() {
2079                                 return;
2080                         }
2081
2082                         if !self.expectations.borrow().is_empty() {
2083                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2084                         }
2085                 }
2086         }
2087
2088         impl Payer for TestPayer {
2089                 fn node_id(&self) -> PublicKey {
2090                         let secp_ctx = Secp256k1::new();
2091                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2092                 }
2093
2094                 fn first_hops(&self) -> Vec<ChannelDetails> {
2095                         Vec::new()
2096                 }
2097
2098                 fn send_payment(
2099                         &self, route: &Route, _payment_hash: PaymentHash,
2100                         _payment_secret: &Option<PaymentSecret>
2101                 ) -> Result<PaymentId, PaymentSendFailure> {
2102                         self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2103                         self.check_attempts()
2104                 }
2105
2106                 fn send_spontaneous_payment(
2107                         &self, route: &Route, _payment_preimage: PaymentPreimage,
2108                 ) -> Result<PaymentId, PaymentSendFailure> {
2109                         self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2110                         self.check_attempts()
2111                 }
2112
2113                 fn retry_payment(
2114                         &self, route: &Route, _payment_id: PaymentId
2115                 ) -> Result<(), PaymentSendFailure> {
2116                         self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2117                         self.check_attempts().map(|_| ())
2118                 }
2119
2120                 fn abandon_payment(&self, _payment_id: PaymentId) { }
2121         }
2122
2123         // *** Full Featured Functional Tests with a Real ChannelManager ***
2124         struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2125
2126         impl Router for ManualRouter {
2127                 fn find_route(
2128                         &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2129                         _inflight_htlcs: InFlightHtlcs
2130                 ) -> Result<Route, LightningError> {
2131                         self.0.borrow_mut().pop_front().unwrap()
2132                 }
2133
2134                 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2135
2136                 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2137
2138                 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2139
2140                 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2141         }
2142         impl ManualRouter {
2143                 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2144                         self.0.borrow_mut().push_back(result);
2145                 }
2146         }
2147         impl Drop for ManualRouter {
2148                 fn drop(&mut self) {
2149                         if std::thread::panicking() {
2150                                 return;
2151                         }
2152                         assert!(self.0.borrow_mut().is_empty());
2153                 }
2154         }
2155
2156         #[test]
2157         fn retry_multi_path_single_failed_payment() {
2158                 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2159                 let chanmon_cfgs = create_chanmon_cfgs(2);
2160                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2161                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2162                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2163
2164                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2165                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2166                 let chans = nodes[0].node.list_usable_channels();
2167                 let mut route = Route {
2168                         paths: vec![
2169                                 vec![RouteHop {
2170                                         pubkey: nodes[1].node.get_our_node_id(),
2171                                         node_features: channelmanager::provided_node_features(),
2172                                         short_channel_id: chans[0].short_channel_id.unwrap(),
2173                                         channel_features: channelmanager::provided_channel_features(),
2174                                         fee_msat: 10_000,
2175                                         cltv_expiry_delta: 100,
2176                                 }],
2177                                 vec![RouteHop {
2178                                         pubkey: nodes[1].node.get_our_node_id(),
2179                                         node_features: channelmanager::provided_node_features(),
2180                                         short_channel_id: chans[1].short_channel_id.unwrap(),
2181                                         channel_features: channelmanager::provided_channel_features(),
2182                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2183                                         cltv_expiry_delta: 100,
2184                                 }],
2185                         ],
2186                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2187                 };
2188                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2189                 router.expect_find_route(Ok(route.clone()));
2190                 // On retry, split the payment across both channels.
2191                 route.paths[0][0].fee_msat = 50_000_001;
2192                 route.paths[1][0].fee_msat = 50_000_000;
2193                 router.expect_find_route(Ok(route.clone()));
2194
2195                 let event_handler = |_: &_| { panic!(); };
2196                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2197
2198                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2199                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2200                         Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2201                         .is_ok());
2202                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2203                 assert_eq!(htlc_msgs.len(), 2);
2204                 check_added_monitors!(nodes[0], 2);
2205         }
2206
2207         #[test]
2208         fn immediate_retry_on_failure() {
2209                 // Tests that we can/will retry immediately after a failure
2210                 let chanmon_cfgs = create_chanmon_cfgs(2);
2211                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2212                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2213                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2214
2215                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2216                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2217                 let chans = nodes[0].node.list_usable_channels();
2218                 let mut route = Route {
2219                         paths: vec![
2220                                 vec![RouteHop {
2221                                         pubkey: nodes[1].node.get_our_node_id(),
2222                                         node_features: channelmanager::provided_node_features(),
2223                                         short_channel_id: chans[0].short_channel_id.unwrap(),
2224                                         channel_features: channelmanager::provided_channel_features(),
2225                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2226                                         cltv_expiry_delta: 100,
2227                                 }],
2228                         ],
2229                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2230                 };
2231                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2232                 router.expect_find_route(Ok(route.clone()));
2233                 // On retry, split the payment across both channels.
2234                 route.paths.push(route.paths[0].clone());
2235                 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2236                 route.paths[0][0].fee_msat = 50_000_000;
2237                 route.paths[1][0].fee_msat = 50_000_001;
2238                 router.expect_find_route(Ok(route.clone()));
2239
2240                 let event_handler = |_: &_| { panic!(); };
2241                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2242
2243                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2244                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2245                         Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2246                         .is_ok());
2247                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2248                 assert_eq!(htlc_msgs.len(), 2);
2249                 check_added_monitors!(nodes[0], 2);
2250         }
2251
2252         #[test]
2253         fn no_extra_retries_on_back_to_back_fail() {
2254                 // In a previous release, we had a race where we may exceed the payment retry count if we
2255                 // get two failures in a row with the second having `all_paths_failed` set.
2256                 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2257                 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2258                 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2259                 // pending which we will see later. Thus, when we previously removed the retry tracking map
2260                 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2261                 // retry entry even though more events for the same payment were still pending. This led to
2262                 // us retrying a payment again even though we'd already given up on it.
2263                 //
2264                 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2265                 // is used to remove the payment retry counter entries instead. This tests for the specific
2266                 // excess-retry case while also testing `PaymentFailed` generation.
2267
2268                 let chanmon_cfgs = create_chanmon_cfgs(3);
2269                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2270                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2271                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2272
2273                 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2274                 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2275
2276                 let mut route = Route {
2277                         paths: vec![
2278                                 vec![RouteHop {
2279                                         pubkey: nodes[1].node.get_our_node_id(),
2280                                         node_features: channelmanager::provided_node_features(),
2281                                         short_channel_id: chan_1_scid,
2282                                         channel_features: channelmanager::provided_channel_features(),
2283                                         fee_msat: 0,
2284                                         cltv_expiry_delta: 100,
2285                                 }, RouteHop {
2286                                         pubkey: nodes[2].node.get_our_node_id(),
2287                                         node_features: channelmanager::provided_node_features(),
2288                                         short_channel_id: chan_2_scid,
2289                                         channel_features: channelmanager::provided_channel_features(),
2290                                         fee_msat: 100_000_000,
2291                                         cltv_expiry_delta: 100,
2292                                 }],
2293                                 vec![RouteHop {
2294                                         pubkey: nodes[1].node.get_our_node_id(),
2295                                         node_features: channelmanager::provided_node_features(),
2296                                         short_channel_id: chan_1_scid,
2297                                         channel_features: channelmanager::provided_channel_features(),
2298                                         fee_msat: 0,
2299                                         cltv_expiry_delta: 100,
2300                                 }, RouteHop {
2301                                         pubkey: nodes[2].node.get_our_node_id(),
2302                                         node_features: channelmanager::provided_node_features(),
2303                                         short_channel_id: chan_2_scid,
2304                                         channel_features: channelmanager::provided_channel_features(),
2305                                         fee_msat: 100_000_000,
2306                                         cltv_expiry_delta: 100,
2307                                 }]
2308                         ],
2309                         payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2310                 };
2311                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2312                 router.expect_find_route(Ok(route.clone()));
2313                 // On retry, we'll only be asked for one path
2314                 route.paths.remove(1);
2315                 router.expect_find_route(Ok(route.clone()));
2316
2317                 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2318                 let event_handler = |event: &Event| {
2319                         let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2320                         event_checker(event);
2321                 };
2322                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2323
2324                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2325                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2326                         Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2327                         .is_ok());
2328                 let htlc_updates = SendEvent::from_node(&nodes[0]);
2329                 check_added_monitors!(nodes[0], 1);
2330                 assert_eq!(htlc_updates.msgs.len(), 1);
2331
2332                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2333                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2334                 check_added_monitors!(nodes[1], 1);
2335                 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2336
2337                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2338                 check_added_monitors!(nodes[0], 1);
2339                 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2340
2341                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2342                 check_added_monitors!(nodes[0], 1);
2343                 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2344
2345                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2346                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2347                 check_added_monitors!(nodes[1], 1);
2348                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2349
2350                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2351                 check_added_monitors!(nodes[1], 1);
2352                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2353
2354                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2355                 check_added_monitors!(nodes[0], 1);
2356
2357                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2358                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2359                 check_added_monitors!(nodes[0], 1);
2360                 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2361
2362                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2363                 check_added_monitors!(nodes[1], 1);
2364                 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2365
2366                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2367                 check_added_monitors!(nodes[1], 1);
2368                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2369
2370                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2371                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2372                 check_added_monitors!(nodes[0], 1);
2373
2374                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2375                 check_added_monitors!(nodes[0], 1);
2376                 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2377
2378                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2379                 check_added_monitors!(nodes[1], 1);
2380                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2381                 check_added_monitors!(nodes[1], 1);
2382                 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2383
2384                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2385                 check_added_monitors!(nodes[0], 1);
2386
2387                 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2388                 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2389                 // with it set. The first event will use up the only retry we are allowed, with the second
2390                 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2391                 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2392                 // if the final HTLC failed.
2393                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2394                         if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2395                                 assert!(!payment_failed_permanently);
2396                                 assert!(all_paths_failed);
2397                         } else { panic!("Unexpected event"); }
2398                 });
2399                 nodes[0].node.process_pending_events(&invoice_payer);
2400                 assert!(expected_events.borrow().is_empty());
2401
2402                 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2403                 check_added_monitors!(nodes[0], 1);
2404
2405                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2406                 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2407                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2408                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2409                 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2410
2411                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2412                         if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2413                                 assert!(!payment_failed_permanently);
2414                                 assert!(all_paths_failed);
2415                         } else { panic!("Unexpected event"); }
2416                 });
2417                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2418                         if let Event::PaymentFailed { .. } = ev {
2419                         } else { panic!("Unexpected event"); }
2420                 });
2421                 nodes[0].node.process_pending_events(&invoice_payer);
2422                 assert!(expected_events.borrow().is_empty());
2423         }
2424 }