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