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