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