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