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