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