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