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