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