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