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