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