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