Make payment tests more realistic
[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 `MonitorUpdateFailed`, 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::MonitorUpdateFailed) => {
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 `MonitorUpdateFailed`, 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::MonitorUpdateFailed) => {
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, rejected_by_dest, 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 *rejected_by_dest {
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::features::{ChannelFeatures, NodeFeatures, InitFeatures};
784         use lightning::ln::functional_test_utils::*;
785         use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
786         use lightning::routing::gossip::{EffectiveCapacity, NodeId};
787         use lightning::routing::router::{PaymentParameters, Route, RouteHop};
788         use lightning::routing::scoring::ChannelUsage;
789         use lightning::util::test_utils::TestLogger;
790         use lightning::util::errors::APIError;
791         use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
792         use secp256k1::{SecretKey, PublicKey, Secp256k1};
793         use std::cell::RefCell;
794         use std::collections::VecDeque;
795         use std::time::{SystemTime, Duration};
796         use time_utils::tests::SinceEpoch;
797         use DEFAULT_EXPIRY_TIME;
798         use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateFailed};
799
800         fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
801                 let payment_hash = Sha256::hash(&payment_preimage.0);
802                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
803
804                 InvoiceBuilder::new(Currency::Bitcoin)
805                         .description("test".into())
806                         .payment_hash(payment_hash)
807                         .payment_secret(PaymentSecret([0; 32]))
808                         .duration_since_epoch(duration_since_epoch())
809                         .min_final_cltv_expiry(144)
810                         .amount_milli_satoshis(128)
811                         .build_signed(|hash| {
812                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
813                         })
814                         .unwrap()
815         }
816
817         fn duration_since_epoch() -> Duration {
818                 #[cfg(feature = "std")]
819                         let duration_since_epoch =
820                         SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
821                 #[cfg(not(feature = "std"))]
822                         let duration_since_epoch = Duration::from_secs(1234567);
823                 duration_since_epoch
824         }
825
826         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
827                 let payment_hash = Sha256::hash(&payment_preimage.0);
828                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
829
830                 InvoiceBuilder::new(Currency::Bitcoin)
831                         .description("test".into())
832                         .payment_hash(payment_hash)
833                         .payment_secret(PaymentSecret([0; 32]))
834                         .duration_since_epoch(duration_since_epoch())
835                         .min_final_cltv_expiry(144)
836                         .build_signed(|hash| {
837                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
838                         })
839                         .unwrap()
840         }
841
842         #[cfg(feature = "std")]
843         fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
844                 let payment_hash = Sha256::hash(&payment_preimage.0);
845                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
846                 let duration = duration_since_epoch()
847                         .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
848                         .unwrap();
849                 InvoiceBuilder::new(Currency::Bitcoin)
850                         .description("test".into())
851                         .payment_hash(payment_hash)
852                         .payment_secret(PaymentSecret([0; 32]))
853                         .duration_since_epoch(duration)
854                         .min_final_cltv_expiry(144)
855                         .amount_milli_satoshis(128)
856                         .build_signed(|hash| {
857                                 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
858                         })
859                         .unwrap()
860         }
861
862         fn pubkey() -> PublicKey {
863                 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
864         }
865
866         #[test]
867         fn pays_invoice_on_first_attempt() {
868                 let event_handled = core::cell::RefCell::new(false);
869                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
870
871                 let payment_preimage = PaymentPreimage([1; 32]);
872                 let invoice = invoice(payment_preimage);
873                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
874                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
875
876                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
877                 let router = TestRouter {};
878                 let scorer = RefCell::new(TestScorer::new());
879                 let logger = TestLogger::new();
880                 let invoice_payer =
881                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
882
883                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
884                 assert_eq!(*payer.attempts.borrow(), 1);
885
886                 invoice_payer.handle_event(&Event::PaymentSent {
887                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
888                 });
889                 assert_eq!(*event_handled.borrow(), true);
890                 assert_eq!(*payer.attempts.borrow(), 1);
891         }
892
893         #[test]
894         fn pays_invoice_on_retry() {
895                 let event_handled = core::cell::RefCell::new(false);
896                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
897
898                 let payment_preimage = PaymentPreimage([1; 32]);
899                 let invoice = invoice(payment_preimage);
900                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
901                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
902
903                 let payer = TestPayer::new()
904                         .expect_send(Amount::ForInvoice(final_value_msat))
905                         .expect_send(Amount::OnRetry(final_value_msat / 2));
906                 let router = TestRouter {};
907                 let scorer = RefCell::new(TestScorer::new());
908                 let logger = TestLogger::new();
909                 let invoice_payer =
910                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
911
912                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
913                 assert_eq!(*payer.attempts.borrow(), 1);
914
915                 let event = Event::PaymentPathFailed {
916                         payment_id,
917                         payment_hash,
918                         network_update: None,
919                         rejected_by_dest: false,
920                         all_paths_failed: false,
921                         path: TestRouter::path_for_value(final_value_msat),
922                         short_channel_id: None,
923                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
924                 };
925                 invoice_payer.handle_event(&event);
926                 assert_eq!(*event_handled.borrow(), false);
927                 assert_eq!(*payer.attempts.borrow(), 2);
928
929                 invoice_payer.handle_event(&Event::PaymentSent {
930                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
931                 });
932                 assert_eq!(*event_handled.borrow(), true);
933                 assert_eq!(*payer.attempts.borrow(), 2);
934         }
935
936         #[test]
937         fn pays_invoice_on_partial_failure() {
938                 let event_handler = |_: &_| { panic!() };
939
940                 let payment_preimage = PaymentPreimage([1; 32]);
941                 let invoice = invoice(payment_preimage);
942                 let retry = TestRouter::retry_for_invoice(&invoice);
943                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
944
945                 let payer = TestPayer::new()
946                         .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
947                         .fails_with_partial_failure(retry, OnAttempt(2), None)
948                         .expect_send(Amount::ForInvoice(final_value_msat))
949                         .expect_send(Amount::OnRetry(final_value_msat / 2))
950                         .expect_send(Amount::OnRetry(final_value_msat / 2));
951                 let router = TestRouter {};
952                 let scorer = RefCell::new(TestScorer::new());
953                 let logger = TestLogger::new();
954                 let invoice_payer =
955                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
956
957                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
958         }
959
960         #[test]
961         fn retries_payment_path_for_unknown_payment() {
962                 let event_handled = core::cell::RefCell::new(false);
963                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
964
965                 let payment_preimage = PaymentPreimage([1; 32]);
966                 let invoice = invoice(payment_preimage);
967                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
968                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
969
970                 let payer = TestPayer::new()
971                         .expect_send(Amount::OnRetry(final_value_msat / 2))
972                         .expect_send(Amount::OnRetry(final_value_msat / 2));
973                 let router = TestRouter {};
974                 let scorer = RefCell::new(TestScorer::new());
975                 let logger = TestLogger::new();
976                 let invoice_payer =
977                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
978
979                 let payment_id = Some(PaymentId([1; 32]));
980                 let event = Event::PaymentPathFailed {
981                         payment_id,
982                         payment_hash,
983                         network_update: None,
984                         rejected_by_dest: false,
985                         all_paths_failed: false,
986                         path: TestRouter::path_for_value(final_value_msat),
987                         short_channel_id: None,
988                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
989                 };
990                 invoice_payer.handle_event(&event);
991                 assert_eq!(*event_handled.borrow(), false);
992                 assert_eq!(*payer.attempts.borrow(), 1);
993
994                 invoice_payer.handle_event(&event);
995                 assert_eq!(*event_handled.borrow(), false);
996                 assert_eq!(*payer.attempts.borrow(), 2);
997
998                 invoice_payer.handle_event(&Event::PaymentSent {
999                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1000                 });
1001                 assert_eq!(*event_handled.borrow(), true);
1002                 assert_eq!(*payer.attempts.borrow(), 2);
1003         }
1004
1005         #[test]
1006         fn fails_paying_invoice_after_max_retry_counts() {
1007                 let event_handled = core::cell::RefCell::new(false);
1008                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1009
1010                 let payment_preimage = PaymentPreimage([1; 32]);
1011                 let invoice = invoice(payment_preimage);
1012                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1013
1014                 let payer = TestPayer::new()
1015                         .expect_send(Amount::ForInvoice(final_value_msat))
1016                         .expect_send(Amount::OnRetry(final_value_msat / 2))
1017                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1018                 let router = TestRouter {};
1019                 let scorer = RefCell::new(TestScorer::new());
1020                 let logger = TestLogger::new();
1021                 let invoice_payer =
1022                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1023
1024                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1025                 assert_eq!(*payer.attempts.borrow(), 1);
1026
1027                 let event = Event::PaymentPathFailed {
1028                         payment_id,
1029                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1030                         network_update: None,
1031                         rejected_by_dest: false,
1032                         all_paths_failed: true,
1033                         path: TestRouter::path_for_value(final_value_msat),
1034                         short_channel_id: None,
1035                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1036                 };
1037                 invoice_payer.handle_event(&event);
1038                 assert_eq!(*event_handled.borrow(), false);
1039                 assert_eq!(*payer.attempts.borrow(), 2);
1040
1041                 let event = Event::PaymentPathFailed {
1042                         payment_id,
1043                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1044                         network_update: None,
1045                         rejected_by_dest: false,
1046                         all_paths_failed: false,
1047                         path: TestRouter::path_for_value(final_value_msat / 2),
1048                         short_channel_id: None,
1049                         retry: Some(RouteParameters {
1050                                 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1051                         }),
1052                 };
1053                 invoice_payer.handle_event(&event);
1054                 assert_eq!(*event_handled.borrow(), false);
1055                 assert_eq!(*payer.attempts.borrow(), 3);
1056
1057                 invoice_payer.handle_event(&event);
1058                 assert_eq!(*event_handled.borrow(), true);
1059                 assert_eq!(*payer.attempts.borrow(), 3);
1060         }
1061
1062         #[cfg(feature = "std")]
1063         #[test]
1064         fn fails_paying_invoice_after_max_retry_timeout() {
1065                 let event_handled = core::cell::RefCell::new(false);
1066                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1067
1068                 let payment_preimage = PaymentPreimage([1; 32]);
1069                 let invoice = invoice(payment_preimage);
1070                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1071
1072                 let payer = TestPayer::new()
1073                         .expect_send(Amount::ForInvoice(final_value_msat))
1074                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1075
1076                 let router = TestRouter {};
1077                 let scorer = RefCell::new(TestScorer::new());
1078                 let logger = TestLogger::new();
1079                 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
1080
1081                 let invoice_payer =
1082                         InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1083
1084                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1085                 assert_eq!(*payer.attempts.borrow(), 1);
1086
1087                 let event = Event::PaymentPathFailed {
1088                         payment_id,
1089                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1090                         network_update: None,
1091                         rejected_by_dest: false,
1092                         all_paths_failed: true,
1093                         path: TestRouter::path_for_value(final_value_msat),
1094                         short_channel_id: None,
1095                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1096                 };
1097                 invoice_payer.handle_event(&event);
1098                 assert_eq!(*event_handled.borrow(), false);
1099                 assert_eq!(*payer.attempts.borrow(), 2);
1100
1101                 SinceEpoch::advance(Duration::from_secs(121));
1102
1103                 invoice_payer.handle_event(&event);
1104                 assert_eq!(*event_handled.borrow(), true);
1105                 assert_eq!(*payer.attempts.borrow(), 2);
1106         }
1107
1108         #[test]
1109         fn fails_paying_invoice_with_missing_retry_params() {
1110                 let event_handled = core::cell::RefCell::new(false);
1111                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1112
1113                 let payment_preimage = PaymentPreimage([1; 32]);
1114                 let invoice = invoice(payment_preimage);
1115                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1116
1117                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1118                 let router = TestRouter {};
1119                 let scorer = RefCell::new(TestScorer::new());
1120                 let logger = TestLogger::new();
1121                 let invoice_payer =
1122                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1123
1124                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1125                 assert_eq!(*payer.attempts.borrow(), 1);
1126
1127                 let event = Event::PaymentPathFailed {
1128                         payment_id,
1129                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1130                         network_update: None,
1131                         rejected_by_dest: false,
1132                         all_paths_failed: false,
1133                         path: vec![],
1134                         short_channel_id: None,
1135                         retry: None,
1136                 };
1137                 invoice_payer.handle_event(&event);
1138                 assert_eq!(*event_handled.borrow(), true);
1139                 assert_eq!(*payer.attempts.borrow(), 1);
1140         }
1141
1142         // Expiration is checked only in an std environment
1143         #[cfg(feature = "std")]
1144         #[test]
1145         fn fails_paying_invoice_after_expiration() {
1146                 let event_handled = core::cell::RefCell::new(false);
1147                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1148
1149                 let payer = TestPayer::new();
1150                 let router = TestRouter {};
1151                 let scorer = RefCell::new(TestScorer::new());
1152                 let logger = TestLogger::new();
1153                 let invoice_payer =
1154                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1155
1156                 let payment_preimage = PaymentPreimage([1; 32]);
1157                 let invoice = expired_invoice(payment_preimage);
1158                 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1159                         assert_eq!(msg, "Invoice expired prior to send");
1160                 } else { panic!("Expected Invoice Error"); }
1161         }
1162
1163         // Expiration is checked only in an std environment
1164         #[cfg(feature = "std")]
1165         #[test]
1166         fn fails_retrying_invoice_after_expiration() {
1167                 let event_handled = core::cell::RefCell::new(false);
1168                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1169
1170                 let payment_preimage = PaymentPreimage([1; 32]);
1171                 let invoice = invoice(payment_preimage);
1172                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1173
1174                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1175                 let router = TestRouter {};
1176                 let scorer = RefCell::new(TestScorer::new());
1177                 let logger = TestLogger::new();
1178                 let invoice_payer =
1179                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1180
1181                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1182                 assert_eq!(*payer.attempts.borrow(), 1);
1183
1184                 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1185                 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1186                         .checked_sub(Duration::from_secs(2)).unwrap()
1187                         .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1188                 let event = Event::PaymentPathFailed {
1189                         payment_id,
1190                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1191                         network_update: None,
1192                         rejected_by_dest: false,
1193                         all_paths_failed: false,
1194                         path: vec![],
1195                         short_channel_id: None,
1196                         retry: Some(retry_data),
1197                 };
1198                 invoice_payer.handle_event(&event);
1199                 assert_eq!(*event_handled.borrow(), true);
1200                 assert_eq!(*payer.attempts.borrow(), 1);
1201         }
1202
1203         #[test]
1204         fn fails_paying_invoice_after_retry_error() {
1205                 let event_handled = core::cell::RefCell::new(false);
1206                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1207
1208                 let payment_preimage = PaymentPreimage([1; 32]);
1209                 let invoice = invoice(payment_preimage);
1210                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1211
1212                 let payer = TestPayer::new()
1213                         .fails_on_attempt(2)
1214                         .expect_send(Amount::ForInvoice(final_value_msat))
1215                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1216                 let router = TestRouter {};
1217                 let scorer = RefCell::new(TestScorer::new());
1218                 let logger = TestLogger::new();
1219                 let invoice_payer =
1220                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1221
1222                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1223                 assert_eq!(*payer.attempts.borrow(), 1);
1224
1225                 let event = Event::PaymentPathFailed {
1226                         payment_id,
1227                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1228                         network_update: None,
1229                         rejected_by_dest: false,
1230                         all_paths_failed: false,
1231                         path: TestRouter::path_for_value(final_value_msat / 2),
1232                         short_channel_id: None,
1233                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1234                 };
1235                 invoice_payer.handle_event(&event);
1236                 assert_eq!(*event_handled.borrow(), true);
1237                 assert_eq!(*payer.attempts.borrow(), 2);
1238         }
1239
1240         #[test]
1241         fn fails_paying_invoice_after_rejected_by_payee() {
1242                 let event_handled = core::cell::RefCell::new(false);
1243                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1244
1245                 let payment_preimage = PaymentPreimage([1; 32]);
1246                 let invoice = invoice(payment_preimage);
1247                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1248
1249                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1250                 let router = TestRouter {};
1251                 let scorer = RefCell::new(TestScorer::new());
1252                 let logger = TestLogger::new();
1253                 let invoice_payer =
1254                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1255
1256                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1257                 assert_eq!(*payer.attempts.borrow(), 1);
1258
1259                 let event = Event::PaymentPathFailed {
1260                         payment_id,
1261                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1262                         network_update: None,
1263                         rejected_by_dest: true,
1264                         all_paths_failed: false,
1265                         path: vec![],
1266                         short_channel_id: None,
1267                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1268                 };
1269                 invoice_payer.handle_event(&event);
1270                 assert_eq!(*event_handled.borrow(), true);
1271                 assert_eq!(*payer.attempts.borrow(), 1);
1272         }
1273
1274         #[test]
1275         fn fails_repaying_invoice_with_pending_payment() {
1276                 let event_handled = core::cell::RefCell::new(false);
1277                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1278
1279                 let payment_preimage = PaymentPreimage([1; 32]);
1280                 let invoice = invoice(payment_preimage);
1281                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1282
1283                 let payer = TestPayer::new()
1284                         .expect_send(Amount::ForInvoice(final_value_msat))
1285                         .expect_send(Amount::ForInvoice(final_value_msat));
1286                 let router = TestRouter {};
1287                 let scorer = RefCell::new(TestScorer::new());
1288                 let logger = TestLogger::new();
1289                 let invoice_payer =
1290                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1291
1292                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1293
1294                 // Cannot repay an invoice pending payment.
1295                 match invoice_payer.pay_invoice(&invoice) {
1296                         Err(PaymentError::Invoice("payment pending")) => {},
1297                         Err(_) => panic!("unexpected error"),
1298                         Ok(_) => panic!("expected invoice error"),
1299                 }
1300
1301                 // Can repay an invoice once cleared from cache.
1302                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1303                 invoice_payer.remove_cached_payment(&payment_hash);
1304                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1305
1306                 // Cannot retry paying an invoice if cleared from cache.
1307                 invoice_payer.remove_cached_payment(&payment_hash);
1308                 let event = Event::PaymentPathFailed {
1309                         payment_id,
1310                         payment_hash,
1311                         network_update: None,
1312                         rejected_by_dest: false,
1313                         all_paths_failed: false,
1314                         path: vec![],
1315                         short_channel_id: None,
1316                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1317                 };
1318                 invoice_payer.handle_event(&event);
1319                 assert_eq!(*event_handled.borrow(), true);
1320         }
1321
1322         #[test]
1323         fn fails_paying_invoice_with_routing_errors() {
1324                 let payer = TestPayer::new();
1325                 let router = FailingRouter {};
1326                 let scorer = RefCell::new(TestScorer::new());
1327                 let logger = TestLogger::new();
1328                 let invoice_payer =
1329                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1330
1331                 let payment_preimage = PaymentPreimage([1; 32]);
1332                 let invoice = invoice(payment_preimage);
1333                 match invoice_payer.pay_invoice(&invoice) {
1334                         Err(PaymentError::Routing(_)) => {},
1335                         Err(_) => panic!("unexpected error"),
1336                         Ok(_) => panic!("expected routing error"),
1337                 }
1338         }
1339
1340         #[test]
1341         fn fails_paying_invoice_with_sending_errors() {
1342                 let payment_preimage = PaymentPreimage([1; 32]);
1343                 let invoice = invoice(payment_preimage);
1344                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1345
1346                 let payer = TestPayer::new()
1347                         .fails_on_attempt(1)
1348                         .expect_send(Amount::ForInvoice(final_value_msat));
1349                 let router = TestRouter {};
1350                 let scorer = RefCell::new(TestScorer::new());
1351                 let logger = TestLogger::new();
1352                 let invoice_payer =
1353                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1354
1355                 match invoice_payer.pay_invoice(&invoice) {
1356                         Err(PaymentError::Sending(_)) => {},
1357                         Err(_) => panic!("unexpected error"),
1358                         Ok(_) => panic!("expected sending error"),
1359                 }
1360         }
1361
1362         #[test]
1363         fn pays_zero_value_invoice_using_amount() {
1364                 let event_handled = core::cell::RefCell::new(false);
1365                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1366
1367                 let payment_preimage = PaymentPreimage([1; 32]);
1368                 let invoice = zero_value_invoice(payment_preimage);
1369                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1370                 let final_value_msat = 100;
1371
1372                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1373                 let router = TestRouter {};
1374                 let scorer = RefCell::new(TestScorer::new());
1375                 let logger = TestLogger::new();
1376                 let invoice_payer =
1377                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1378
1379                 let payment_id =
1380                         Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1381                 assert_eq!(*payer.attempts.borrow(), 1);
1382
1383                 invoice_payer.handle_event(&Event::PaymentSent {
1384                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1385                 });
1386                 assert_eq!(*event_handled.borrow(), true);
1387                 assert_eq!(*payer.attempts.borrow(), 1);
1388         }
1389
1390         #[test]
1391         fn fails_paying_zero_value_invoice_with_amount() {
1392                 let event_handled = core::cell::RefCell::new(false);
1393                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1394
1395                 let payer = TestPayer::new();
1396                 let router = TestRouter {};
1397                 let scorer = RefCell::new(TestScorer::new());
1398                 let logger = TestLogger::new();
1399                 let invoice_payer =
1400                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1401
1402                 let payment_preimage = PaymentPreimage([1; 32]);
1403                 let invoice = invoice(payment_preimage);
1404
1405                 // Cannot repay an invoice pending payment.
1406                 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1407                         Err(PaymentError::Invoice("amount unexpected")) => {},
1408                         Err(_) => panic!("unexpected error"),
1409                         Ok(_) => panic!("expected invoice error"),
1410                 }
1411         }
1412
1413         #[test]
1414         fn pays_pubkey_with_amount() {
1415                 let event_handled = core::cell::RefCell::new(false);
1416                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1417
1418                 let pubkey = pubkey();
1419                 let payment_preimage = PaymentPreimage([1; 32]);
1420                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1421                 let final_value_msat = 100;
1422                 let final_cltv_expiry_delta = 42;
1423
1424                 let payer = TestPayer::new()
1425                         .expect_send(Amount::Spontaneous(final_value_msat))
1426                         .expect_send(Amount::OnRetry(final_value_msat));
1427                 let router = TestRouter {};
1428                 let scorer = RefCell::new(TestScorer::new());
1429                 let logger = TestLogger::new();
1430                 let invoice_payer =
1431                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1432
1433                 let payment_id = Some(invoice_payer.pay_pubkey(
1434                                 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1435                         ).unwrap());
1436                 assert_eq!(*payer.attempts.borrow(), 1);
1437
1438                 let retry = RouteParameters {
1439                         payment_params: PaymentParameters::for_keysend(pubkey),
1440                         final_value_msat,
1441                         final_cltv_expiry_delta,
1442                 };
1443                 let event = Event::PaymentPathFailed {
1444                         payment_id,
1445                         payment_hash,
1446                         network_update: None,
1447                         rejected_by_dest: false,
1448                         all_paths_failed: false,
1449                         path: vec![],
1450                         short_channel_id: None,
1451                         retry: Some(retry),
1452                 };
1453                 invoice_payer.handle_event(&event);
1454                 assert_eq!(*event_handled.borrow(), false);
1455                 assert_eq!(*payer.attempts.borrow(), 2);
1456
1457                 invoice_payer.handle_event(&Event::PaymentSent {
1458                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1459                 });
1460                 assert_eq!(*event_handled.borrow(), true);
1461                 assert_eq!(*payer.attempts.borrow(), 2);
1462         }
1463
1464         #[test]
1465         fn scores_failed_channel() {
1466                 let event_handled = core::cell::RefCell::new(false);
1467                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1468
1469                 let payment_preimage = PaymentPreimage([1; 32]);
1470                 let invoice = invoice(payment_preimage);
1471                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1472                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1473                 let path = TestRouter::path_for_value(final_value_msat);
1474                 let short_channel_id = Some(path[0].short_channel_id);
1475
1476                 // Expect that scorer is given short_channel_id upon handling the event.
1477                 let payer = TestPayer::new()
1478                         .expect_send(Amount::ForInvoice(final_value_msat))
1479                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1480                 let router = TestRouter {};
1481                 let scorer = RefCell::new(TestScorer::new().expect(TestResult::PaymentFailure {
1482                         path: path.clone(), short_channel_id: path[0].short_channel_id,
1483                 }));
1484                 let logger = TestLogger::new();
1485                 let invoice_payer =
1486                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1487
1488                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1489                 let event = Event::PaymentPathFailed {
1490                         payment_id,
1491                         payment_hash,
1492                         network_update: None,
1493                         rejected_by_dest: false,
1494                         all_paths_failed: false,
1495                         path,
1496                         short_channel_id,
1497                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1498                 };
1499                 invoice_payer.handle_event(&event);
1500         }
1501
1502         #[test]
1503         fn scores_successful_channels() {
1504                 let event_handled = core::cell::RefCell::new(false);
1505                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1506
1507                 let payment_preimage = PaymentPreimage([1; 32]);
1508                 let invoice = invoice(payment_preimage);
1509                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1510                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1511                 let route = TestRouter::route_for_value(final_value_msat);
1512
1513                 // Expect that scorer is given short_channel_id upon handling the event.
1514                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1515                 let router = TestRouter {};
1516                 let scorer = RefCell::new(TestScorer::new()
1517                         .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1518                         .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() })
1519                 );
1520                 let logger = TestLogger::new();
1521                 let invoice_payer =
1522                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1523
1524                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1525                 let event = Event::PaymentPathSuccessful {
1526                         payment_id, payment_hash, path: route.paths[0].clone()
1527                 };
1528                 invoice_payer.handle_event(&event);
1529                 let event = Event::PaymentPathSuccessful {
1530                         payment_id, payment_hash, path: route.paths[1].clone()
1531                 };
1532                 invoice_payer.handle_event(&event);
1533         }
1534
1535         #[test]
1536         fn generates_correct_inflight_map_data() {
1537                 let event_handled = core::cell::RefCell::new(false);
1538                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1539
1540                 let payment_preimage = PaymentPreimage([1; 32]);
1541                 let invoice = invoice(payment_preimage);
1542                 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1543                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1544
1545                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1546                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1547                 let route = TestRouter::route_for_value(final_value_msat);
1548                 let router = TestRouter {};
1549                 let scorer = RefCell::new(TestScorer::new());
1550                 let logger = TestLogger::new();
1551                 let invoice_payer =
1552                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1553
1554                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1555
1556                 let inflight_map = invoice_payer.create_inflight_map();
1557                 // First path check
1558                 assert_eq!(inflight_map.get(&(0, false)).unwrap().clone(), 94);
1559                 assert_eq!(inflight_map.get(&(1, true)).unwrap().clone(), 84);
1560                 assert_eq!(inflight_map.get(&(2, false)).unwrap().clone(), 64);
1561
1562                 // Second path check
1563                 assert_eq!(inflight_map.get(&(3, false)).unwrap().clone(), 74);
1564                 assert_eq!(inflight_map.get(&(4, false)).unwrap().clone(), 64);
1565
1566                 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1567                         payment_id, payment_hash, path: route.paths[0].clone()
1568                 });
1569
1570                 let inflight_map = invoice_payer.create_inflight_map();
1571
1572                 assert_eq!(inflight_map.get(&(0, false)), None);
1573                 assert_eq!(inflight_map.get(&(1, true)), None);
1574                 assert_eq!(inflight_map.get(&(2, false)), None);
1575
1576                 // Second path should still be inflight
1577                 assert_eq!(inflight_map.get(&(3, false)).unwrap().clone(), 74);
1578                 assert_eq!(inflight_map.get(&(4, false)).unwrap().clone(), 64)
1579         }
1580
1581         #[test]
1582         fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1583                 // First, let's just send a payment through, but only make sure one of the path completes
1584                 let event_handled = core::cell::RefCell::new(false);
1585                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1586
1587                 let payment_preimage = PaymentPreimage([1; 32]);
1588                 let payment_invoice = invoice(payment_preimage);
1589                 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1590                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1591
1592                 let payer = TestPayer::new()
1593                         .expect_send(Amount::ForInvoice(final_value_msat))
1594                         .expect_send(Amount::ForInvoice(final_value_msat));
1595                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1596                 let route = TestRouter::route_for_value(final_value_msat);
1597                 let router = TestRouter {};
1598                 let scorer = RefCell::new(TestScorer::new()
1599                         // 1st invoice, 1st path
1600                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1601                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1602                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1603                         // 1st invoice, 2nd path
1604                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1605                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1606                         // 2nd invoice, 1st path
1607                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1608                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1609                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1610                         // 2nd invoice, 2nd path
1611                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1612                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } )
1613                 );
1614                 let logger = TestLogger::new();
1615                 let invoice_payer =
1616                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1617
1618                 // Succeed 1st path, leave 2nd path inflight
1619                 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1620                 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1621                         payment_id, payment_hash, path: route.paths[0].clone()
1622                 });
1623
1624                 // Let's pay a second invoice that will be using the same path. This should trigger the
1625                 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1626                 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1627                 // have 64 msats inflight for paths considering the channel with scid of 1.
1628                 let payment_preimage_2 = PaymentPreimage([2; 32]);
1629                 let payment_invoice_2 = invoice(payment_preimage_2);
1630                 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1631         }
1632
1633         #[test]
1634         fn considers_inflight_htlcs_between_retries() {
1635                 // First, let's just send a payment through, but only make sure one of the path completes
1636                 let event_handled = core::cell::RefCell::new(false);
1637                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1638
1639                 let payment_preimage = PaymentPreimage([1; 32]);
1640                 let payment_invoice = invoice(payment_preimage);
1641                 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1642                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1643
1644                 let payer = TestPayer::new()
1645                         .expect_send(Amount::ForInvoice(final_value_msat))
1646                         .expect_send(Amount::OnRetry(final_value_msat / 2))
1647                         .expect_send(Amount::OnRetry(final_value_msat / 4));
1648                 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1649                 let router = TestRouter {};
1650                 let scorer = RefCell::new(TestScorer::new()
1651                         // 1st invoice, 1st path
1652                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1653                         .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1654                         .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1655                         // 1st invoice, 2nd path
1656                         .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1657                         .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1658                         // Retry 1, 1st path
1659                         .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1660                         .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1661                         .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1662                         // Retry 1, 2nd path
1663                         .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1664                         .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1665                         // Retry 2, 1st path
1666                         .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1667                         .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1668                         .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1669                         // Retry 2, 2nd path
1670                         .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1671                         .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1672                 );
1673                 let logger = TestLogger::new();
1674                 let invoice_payer =
1675                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1676
1677                 // Fail 1st path, leave 2nd path inflight
1678                 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1679                 invoice_payer.handle_event(&Event::PaymentPathFailed {
1680                         payment_id,
1681                         payment_hash,
1682                         network_update: None,
1683                         rejected_by_dest: false,
1684                         all_paths_failed: false,
1685                         path: TestRouter::path_for_value(final_value_msat),
1686                         short_channel_id: None,
1687                         retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1688                 });
1689
1690                 // Fails again the 1st path of our retry
1691                 invoice_payer.handle_event(&Event::PaymentPathFailed {
1692                         payment_id,
1693                         payment_hash,
1694                         network_update: None,
1695                         rejected_by_dest: false,
1696                         all_paths_failed: false,
1697                         path: TestRouter::path_for_value(final_value_msat / 2),
1698                         short_channel_id: None,
1699                         retry: Some(RouteParameters {
1700                                 final_value_msat: final_value_msat / 4,
1701                                 ..TestRouter::retry_for_invoice(&payment_invoice)
1702                         }),
1703                 });
1704         }
1705
1706         #[test]
1707         fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1708                 let event_handled = core::cell::RefCell::new(false);
1709                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1710
1711                 let payment_preimage = PaymentPreimage([1; 32]);
1712                 let invoice_to_pay = invoice(payment_preimage);
1713                 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1714
1715                 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1716                 let payer = TestPayer::new()
1717                         .fails_with_partial_failure(
1718                                 retry.clone(), OnAttempt(1),
1719                                 Some(vec![
1720                                         Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateFailed)
1721                                 ]))
1722                         .expect_send(Amount::ForInvoice(final_value_msat));
1723
1724                 let router = TestRouter {};
1725                 let scorer = RefCell::new(TestScorer::new());
1726                 let logger = TestLogger::new();
1727                 let invoice_payer =
1728                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1729
1730                 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1731                 let inflight_map = invoice_payer.create_inflight_map();
1732
1733                 // Only the second path, which failed with `MonitorUpdateFailed` should be added to our
1734                 // inflight map because retries are disabled.
1735                 assert_eq!(inflight_map.len(), 2);
1736         }
1737
1738         #[test]
1739         fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1740                 let event_handled = core::cell::RefCell::new(false);
1741                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1742
1743                 let payment_preimage = PaymentPreimage([1; 32]);
1744                 let invoice_to_pay = invoice(payment_preimage);
1745                 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1746
1747                 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1748                 let payer = TestPayer::new()
1749                         .fails_with_partial_failure(
1750                                 retry.clone(), OnAttempt(1),
1751                                 Some(vec![
1752                                         Ok(()), Err(MonitorUpdateFailed)
1753                                 ]))
1754                         .expect_send(Amount::ForInvoice(final_value_msat));
1755
1756                 let router = TestRouter {};
1757                 let scorer = RefCell::new(TestScorer::new());
1758                 let logger = TestLogger::new();
1759                 let invoice_payer =
1760                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1761
1762                 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1763                 let inflight_map = invoice_payer.create_inflight_map();
1764
1765                 // All paths successful, hence we check of the existence of all 5 hops.
1766                 assert_eq!(inflight_map.len(), 5);
1767         }
1768
1769         struct TestRouter;
1770
1771         impl TestRouter {
1772                 fn route_for_value(final_value_msat: u64) -> Route {
1773                         Route {
1774                                 paths: vec![
1775                                         vec![
1776                                                 RouteHop {
1777                                                         pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1778                                                         channel_features: ChannelFeatures::empty(),
1779                                                         node_features: NodeFeatures::empty(),
1780                                                         short_channel_id: 0,
1781                                                         fee_msat: 10,
1782                                                         cltv_expiry_delta: 0
1783                                                 },
1784                                                 RouteHop {
1785                                                         pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1786                                                         channel_features: ChannelFeatures::empty(),
1787                                                         node_features: NodeFeatures::empty(),
1788                                                         short_channel_id: 1,
1789                                                         fee_msat: 20,
1790                                                         cltv_expiry_delta: 0
1791                                                 },
1792                                                 RouteHop {
1793                                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1794                                                         channel_features: ChannelFeatures::empty(),
1795                                                         node_features: NodeFeatures::empty(),
1796                                                         short_channel_id: 2,
1797                                                         fee_msat: final_value_msat / 2,
1798                                                         cltv_expiry_delta: 0
1799                                                 },
1800                                         ],
1801                                         vec![
1802                                                 RouteHop {
1803                                                         pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1804                                                         channel_features: ChannelFeatures::empty(),
1805                                                         node_features: NodeFeatures::empty(),
1806                                                         short_channel_id: 3,
1807                                                         fee_msat: 10,
1808                                                         cltv_expiry_delta: 144
1809                                                 },
1810                                                 RouteHop {
1811                                                         pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1812                                                         channel_features: ChannelFeatures::empty(),
1813                                                         node_features: NodeFeatures::empty(),
1814                                                         short_channel_id: 4,
1815                                                         fee_msat: final_value_msat / 2,
1816                                                         cltv_expiry_delta: 144
1817                                                 }
1818                                         ],
1819                                 ],
1820                                 payment_params: None,
1821                         }
1822                 }
1823
1824                 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1825                         TestRouter::route_for_value(final_value_msat).paths[0].clone()
1826                 }
1827
1828                 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1829                         let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1830                                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1831                                 .with_route_hints(invoice.route_hints());
1832                         if let Some(features) = invoice.features() {
1833                                 payment_params = payment_params.with_features(features.clone());
1834                         }
1835                         let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1836                         RouteParameters {
1837                                 payment_params,
1838                                 final_value_msat,
1839                                 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1840                         }
1841                 }
1842         }
1843
1844         impl Router for TestRouter {
1845                 fn find_route<S: Score>(
1846                         &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1847                         _first_hops: Option<&[&ChannelDetails]>, scorer: &S
1848                 ) -> Result<Route, LightningError> {
1849                         // Simulate calling the Scorer just as you would in find_route
1850                         let route = Self::route_for_value(route_params.final_value_msat);
1851                         for path in route.paths {
1852                                 let mut aggregate_msat = 0u64;
1853                                 for (idx, hop) in path.iter().rev().enumerate() {
1854                                         aggregate_msat += hop.fee_msat;
1855                                         let usage = ChannelUsage {
1856                                                 amount_msat: aggregate_msat,
1857                                                 inflight_htlc_msat: 0,
1858                                                 effective_capacity: EffectiveCapacity::Unknown,
1859                                         };
1860
1861                                         // Since the path is reversed, the last element in our iteration is the first
1862                                         // hop.
1863                                         if idx == path.len() - 1 {
1864                                                 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1865                                         } else {
1866                                                 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1867                                         }
1868                                 }
1869                         }
1870
1871                         Ok(Route {
1872                                 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1873                         })
1874                 }
1875         }
1876
1877         struct FailingRouter;
1878
1879         impl Router for FailingRouter {
1880                 fn find_route<S: Score>(
1881                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1882                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1883                 ) -> Result<Route, LightningError> {
1884                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1885                 }
1886         }
1887
1888         struct TestScorer {
1889                 event_expectations: Option<VecDeque<TestResult>>,
1890                 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1891         }
1892
1893         #[derive(Debug)]
1894         enum TestResult {
1895                 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1896                 PaymentSuccess { path: Vec<RouteHop> },
1897         }
1898
1899         impl TestScorer {
1900                 fn new() -> Self {
1901                         Self {
1902                                 event_expectations: None,
1903                                 scorer_expectations: RefCell::new(None),
1904                         }
1905                 }
1906
1907                 fn expect(mut self, expectation: TestResult) -> Self {
1908                         self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1909                         self
1910                 }
1911
1912                 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1913                         self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1914                         self
1915                 }
1916         }
1917
1918         #[cfg(c_bindings)]
1919         impl lightning::util::ser::Writeable for TestScorer {
1920                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1921         }
1922
1923         impl Score for TestScorer {
1924                 fn channel_penalty_msat(
1925                         &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1926                 ) -> u64 {
1927                         if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1928                                 match scorer_expectations.pop_front() {
1929                                         Some(expectation) => {
1930                                                 assert_eq!(expectation.amount_msat, usage.amount_msat);
1931                                                 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1932                                         },
1933                                         None => {},
1934                                 }
1935                         }
1936                         0
1937                 }
1938
1939                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1940                         if let Some(expectations) = &mut self.event_expectations {
1941                                 match expectations.pop_front() {
1942                                         Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1943                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1944                                                 assert_eq!(actual_short_channel_id, short_channel_id);
1945                                         },
1946                                         Some(TestResult::PaymentSuccess { path }) => {
1947                                                 panic!("Unexpected successful payment path: {:?}", path)
1948                                         },
1949                                         None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1950                                 }
1951                         }
1952                 }
1953
1954                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1955                         if let Some(expectations) = &mut self.event_expectations {
1956                                 match expectations.pop_front() {
1957                                         Some(TestResult::PaymentFailure { path, .. }) => {
1958                                                 panic!("Unexpected payment path failure: {:?}", path)
1959                                         },
1960                                         Some(TestResult::PaymentSuccess { path }) => {
1961                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1962                                         },
1963                                         None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1964                                 }
1965                         }
1966                 }
1967
1968                 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1969                         if let Some(expectations) = &mut self.event_expectations {
1970                                 match expectations.pop_front() {
1971                                         Some(TestResult::PaymentFailure { path, .. }) => {
1972                                                 panic!("Unexpected failed payment path: {:?}", path)
1973                                         },
1974                                         Some(TestResult::PaymentSuccess { path }) => {
1975                                                 panic!("Unexpected successful payment path: {:?}", path)
1976                                         },
1977                                         None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1978                                 }
1979                         }
1980                 }
1981                 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1982                         if let Some(expectations) = &mut self.event_expectations {
1983                                 match expectations.pop_front() {
1984                                         Some(TestResult::PaymentFailure { path, .. }) => {
1985                                                 panic!("Unexpected payment path failure: {:?}", path)
1986                                         },
1987                                         Some(TestResult::PaymentSuccess { path }) => {
1988                                                 panic!("Unexpected successful payment path: {:?}", path)
1989                                         },
1990                                         None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1991                                 }
1992                         }
1993                 }
1994         }
1995
1996         impl Drop for TestScorer {
1997                 fn drop(&mut self) {
1998                         if std::thread::panicking() {
1999                                 return;
2000                         }
2001
2002                         if let Some(event_expectations) = &self.event_expectations {
2003                                 if !event_expectations.is_empty() {
2004                                         panic!("Unsatisfied event expectations: {:?}", event_expectations);
2005                                 }
2006                         }
2007
2008                         if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2009                                 if !scorer_expectations.is_empty() {
2010                                         panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2011                                 }
2012                         }
2013                 }
2014         }
2015
2016         struct TestPayer {
2017                 expectations: core::cell::RefCell<VecDeque<Amount>>,
2018                 attempts: core::cell::RefCell<usize>,
2019                 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2020         }
2021
2022         #[derive(Clone, Debug, PartialEq, Eq)]
2023         enum Amount {
2024                 ForInvoice(u64),
2025                 Spontaneous(u64),
2026                 OnRetry(u64),
2027         }
2028
2029         struct OnAttempt(usize);
2030
2031         impl TestPayer {
2032                 fn new() -> Self {
2033                         Self {
2034                                 expectations: core::cell::RefCell::new(VecDeque::new()),
2035                                 attempts: core::cell::RefCell::new(0),
2036                                 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2037                         }
2038                 }
2039
2040                 fn expect_send(self, value_msat: Amount) -> Self {
2041                         self.expectations.borrow_mut().push_back(value_msat);
2042                         self
2043                 }
2044
2045                 fn fails_on_attempt(self, attempt: usize) -> Self {
2046                         let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
2047                         self.fails_with(failure, OnAttempt(attempt))
2048                 }
2049
2050                 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2051                         self.fails_with(PaymentSendFailure::PartialFailure {
2052                                 results: results.unwrap_or(vec![]),
2053                                 failed_paths_retry: Some(retry),
2054                                 payment_id: PaymentId([1; 32]),
2055                         }, attempt)
2056                 }
2057
2058                 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2059                         self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2060                         self
2061                 }
2062
2063                 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2064                         let mut attempts = self.attempts.borrow_mut();
2065                         *attempts += 1;
2066
2067                         match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2068                                 Some(failure) => Err(failure),
2069                                 None => Ok(PaymentId([1; 32])),
2070                         }
2071                 }
2072
2073                 fn check_value_msats(&self, actual_value_msats: Amount) {
2074                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
2075                         if let Some(expected_value_msats) = expected_value_msats {
2076                                 assert_eq!(actual_value_msats, expected_value_msats);
2077                         } else {
2078                                 panic!("Unexpected amount: {:?}", actual_value_msats);
2079                         }
2080                 }
2081         }
2082
2083         impl Drop for TestPayer {
2084                 fn drop(&mut self) {
2085                         if std::thread::panicking() {
2086                                 return;
2087                         }
2088
2089                         if !self.expectations.borrow().is_empty() {
2090                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2091                         }
2092                 }
2093         }
2094
2095         impl Payer for TestPayer {
2096                 fn node_id(&self) -> PublicKey {
2097                         let secp_ctx = Secp256k1::new();
2098                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2099                 }
2100
2101                 fn first_hops(&self) -> Vec<ChannelDetails> {
2102                         Vec::new()
2103                 }
2104
2105                 fn send_payment(
2106                         &self, route: &Route, _payment_hash: PaymentHash,
2107                         _payment_secret: &Option<PaymentSecret>
2108                 ) -> Result<PaymentId, PaymentSendFailure> {
2109                         self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2110                         self.check_attempts()
2111                 }
2112
2113                 fn send_spontaneous_payment(
2114                         &self, route: &Route, _payment_preimage: PaymentPreimage,
2115                 ) -> Result<PaymentId, PaymentSendFailure> {
2116                         self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2117                         self.check_attempts()
2118                 }
2119
2120                 fn retry_payment(
2121                         &self, route: &Route, _payment_id: PaymentId
2122                 ) -> Result<(), PaymentSendFailure> {
2123                         self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2124                         self.check_attempts().map(|_| ())
2125                 }
2126
2127                 fn abandon_payment(&self, _payment_id: PaymentId) { }
2128         }
2129
2130         // *** Full Featured Functional Tests with a Real ChannelManager ***
2131         struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2132
2133         impl Router for ManualRouter {
2134                 fn find_route<S: Score>(
2135                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
2136                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
2137                 ) -> Result<Route, LightningError> {
2138                         self.0.borrow_mut().pop_front().unwrap()
2139                 }
2140         }
2141         impl ManualRouter {
2142                 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2143                         self.0.borrow_mut().push_back(result);
2144                 }
2145         }
2146         impl Drop for ManualRouter {
2147                 fn drop(&mut self) {
2148                         if std::thread::panicking() {
2149                                 return;
2150                         }
2151                         assert!(self.0.borrow_mut().is_empty());
2152                 }
2153         }
2154
2155         #[test]
2156         fn retry_multi_path_single_failed_payment() {
2157                 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2158                 let chanmon_cfgs = create_chanmon_cfgs(2);
2159                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2160                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2161                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2162
2163                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2164                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2165                 let chans = nodes[0].node.list_usable_channels();
2166                 let mut route = Route {
2167                         paths: vec![
2168                                 vec![RouteHop {
2169                                         pubkey: nodes[1].node.get_our_node_id(),
2170                                         node_features: NodeFeatures::known(),
2171                                         short_channel_id: chans[0].short_channel_id.unwrap(),
2172                                         channel_features: ChannelFeatures::known(),
2173                                         fee_msat: 10_000,
2174                                         cltv_expiry_delta: 100,
2175                                 }],
2176                                 vec![RouteHop {
2177                                         pubkey: nodes[1].node.get_our_node_id(),
2178                                         node_features: NodeFeatures::known(),
2179                                         short_channel_id: chans[1].short_channel_id.unwrap(),
2180                                         channel_features: ChannelFeatures::known(),
2181                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2182                                         cltv_expiry_delta: 100,
2183                                 }],
2184                         ],
2185                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2186                 };
2187                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2188                 router.expect_find_route(Ok(route.clone()));
2189                 // On retry, split the payment across both channels.
2190                 route.paths[0][0].fee_msat = 50_000_001;
2191                 route.paths[1][0].fee_msat = 50_000_000;
2192                 router.expect_find_route(Ok(route.clone()));
2193
2194                 let event_handler = |_: &_| { panic!(); };
2195                 let scorer = RefCell::new(TestScorer::new());
2196                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2197
2198                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2199                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2200                         duration_since_epoch(), 3600).unwrap())
2201                         .is_ok());
2202                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2203                 assert_eq!(htlc_msgs.len(), 2);
2204                 check_added_monitors!(nodes[0], 2);
2205         }
2206
2207         #[test]
2208         fn immediate_retry_on_failure() {
2209                 // Tests that we can/will retry immediately after a failure
2210                 let chanmon_cfgs = create_chanmon_cfgs(2);
2211                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2212                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2213                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2214
2215                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2216                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2217                 let chans = nodes[0].node.list_usable_channels();
2218                 let mut route = Route {
2219                         paths: vec![
2220                                 vec![RouteHop {
2221                                         pubkey: nodes[1].node.get_our_node_id(),
2222                                         node_features: NodeFeatures::known(),
2223                                         short_channel_id: chans[0].short_channel_id.unwrap(),
2224                                         channel_features: ChannelFeatures::known(),
2225                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2226                                         cltv_expiry_delta: 100,
2227                                 }],
2228                         ],
2229                         payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2230                 };
2231                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2232                 router.expect_find_route(Ok(route.clone()));
2233                 // On retry, split the payment across both channels.
2234                 route.paths.push(route.paths[0].clone());
2235                 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2236                 route.paths[0][0].fee_msat = 50_000_000;
2237                 route.paths[1][0].fee_msat = 50_000_001;
2238                 router.expect_find_route(Ok(route.clone()));
2239
2240                 let event_handler = |_: &_| { panic!(); };
2241                 let scorer = RefCell::new(TestScorer::new());
2242                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2243
2244                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2245                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2246                         duration_since_epoch(), 3600).unwrap())
2247                         .is_ok());
2248                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2249                 assert_eq!(htlc_msgs.len(), 2);
2250                 check_added_monitors!(nodes[0], 2);
2251         }
2252
2253         #[test]
2254         fn no_extra_retries_on_back_to_back_fail() {
2255                 // In a previous release, we had a race where we may exceed the payment retry count if we
2256                 // get two failures in a row with the second having `all_paths_failed` set.
2257                 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2258                 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2259                 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2260                 // pending which we will see later. Thus, when we previously removed the retry tracking map
2261                 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2262                 // retry entry even though more events for the same payment were still pending. This led to
2263                 // us retrying a payment again even though we'd already given up on it.
2264                 //
2265                 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2266                 // is used to remove the payment retry counter entries instead. This tests for the specific
2267                 // excess-retry case while also testing `PaymentFailed` generation.
2268
2269                 let chanmon_cfgs = create_chanmon_cfgs(3);
2270                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2271                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2272                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2273
2274                 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
2275                 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
2276
2277                 let mut route = Route {
2278                         paths: vec![
2279                                 vec![RouteHop {
2280                                         pubkey: nodes[1].node.get_our_node_id(),
2281                                         node_features: NodeFeatures::known(),
2282                                         short_channel_id: chan_1_scid,
2283                                         channel_features: ChannelFeatures::known(),
2284                                         fee_msat: 0,
2285                                         cltv_expiry_delta: 100,
2286                                 }, RouteHop {
2287                                         pubkey: nodes[2].node.get_our_node_id(),
2288                                         node_features: NodeFeatures::known(),
2289                                         short_channel_id: chan_2_scid,
2290                                         channel_features: ChannelFeatures::known(),
2291                                         fee_msat: 100_000_000,
2292                                         cltv_expiry_delta: 100,
2293                                 }],
2294                                 vec![RouteHop {
2295                                         pubkey: nodes[1].node.get_our_node_id(),
2296                                         node_features: NodeFeatures::known(),
2297                                         short_channel_id: chan_1_scid,
2298                                         channel_features: ChannelFeatures::known(),
2299                                         fee_msat: 0,
2300                                         cltv_expiry_delta: 100,
2301                                 }, RouteHop {
2302                                         pubkey: nodes[2].node.get_our_node_id(),
2303                                         node_features: NodeFeatures::known(),
2304                                         short_channel_id: chan_2_scid,
2305                                         channel_features: ChannelFeatures::known(),
2306                                         fee_msat: 100_000_000,
2307                                         cltv_expiry_delta: 100,
2308                                 }]
2309                         ],
2310                         payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2311                 };
2312                 let router = ManualRouter(RefCell::new(VecDeque::new()));
2313                 router.expect_find_route(Ok(route.clone()));
2314                 // On retry, we'll only be asked for one path
2315                 route.paths.remove(1);
2316                 router.expect_find_route(Ok(route.clone()));
2317
2318                 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2319                 let event_handler = |event: &Event| {
2320                         let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2321                         event_checker(event);
2322                 };
2323                 let scorer = RefCell::new(TestScorer::new());
2324                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2325
2326                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2327                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2328                         duration_since_epoch(), 3600).unwrap())
2329                         .is_ok());
2330                 let htlc_updates = SendEvent::from_node(&nodes[0]);
2331                 check_added_monitors!(nodes[0], 1);
2332                 assert_eq!(htlc_updates.msgs.len(), 1);
2333
2334                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2335                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2336                 check_added_monitors!(nodes[1], 1);
2337                 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2338
2339                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2340                 check_added_monitors!(nodes[0], 1);
2341                 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2342
2343                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2344                 check_added_monitors!(nodes[0], 1);
2345                 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2346
2347                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2348                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2349                 check_added_monitors!(nodes[1], 1);
2350                 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2351
2352                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2353                 check_added_monitors!(nodes[1], 1);
2354                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2355
2356                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2357                 check_added_monitors!(nodes[0], 1);
2358
2359                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2360                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2361                 check_added_monitors!(nodes[0], 1);
2362                 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2363
2364                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2365                 check_added_monitors!(nodes[1], 1);
2366                 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2367
2368                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2369                 check_added_monitors!(nodes[1], 1);
2370                 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2371
2372                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2373                 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2374                 check_added_monitors!(nodes[0], 1);
2375
2376                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2377                 check_added_monitors!(nodes[0], 1);
2378                 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2379
2380                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2381                 check_added_monitors!(nodes[1], 1);
2382                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2383                 check_added_monitors!(nodes[1], 1);
2384                 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2385
2386                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2387                 check_added_monitors!(nodes[0], 1);
2388
2389                 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2390                 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2391                 // with it set. The first event will use up the only retry we are allowed, with the second
2392                 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2393                 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2394                 // if the final HTLC failed.
2395                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2396                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
2397                                 assert!(!rejected_by_dest);
2398                                 assert!(all_paths_failed);
2399                         } else { panic!("Unexpected event"); }
2400                 });
2401                 nodes[0].node.process_pending_events(&invoice_payer);
2402                 assert!(expected_events.borrow().is_empty());
2403
2404                 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2405                 check_added_monitors!(nodes[0], 1);
2406
2407                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2408                 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2409                 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2410                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2411                 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2412
2413                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2414                         if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
2415                                 assert!(!rejected_by_dest);
2416                                 assert!(all_paths_failed);
2417                         } else { panic!("Unexpected event"); }
2418                 });
2419                 expected_events.borrow_mut().push_back(&|ev: &Event| {
2420                         if let Event::PaymentFailed { .. } = ev {
2421                         } else { panic!("Unexpected event"); }
2422                 });
2423                 nodes[0].node.process_pending_events(&invoice_payer);
2424                 assert!(expected_events.borrow().is_empty());
2425         }
2426 }