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