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