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