Merge pull request #1197 from jkczyz/2021-11-score-successful-payment-path
[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 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
36 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
37 //! # use lightning::ln::msgs::LightningError;
38 //! # use lightning::routing::scoring::Score;
39 //! # use lightning::routing::network_graph::NodeId;
40 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
41 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
42 //! # use lightning::util::logger::{Logger, Record};
43 //! # use lightning::util::ser::{Writeable, Writer};
44 //! # use lightning_invoice::Invoice;
45 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
46 //! # use secp256k1::key::PublicKey;
47 //! # use std::cell::RefCell;
48 //! # use std::ops::Deref;
49 //! #
50 //! # struct FakeEventProvider {}
51 //! # impl EventsProvider for FakeEventProvider {
52 //! #     fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
53 //! # }
54 //! #
55 //! # struct FakePayer {}
56 //! # impl Payer for FakePayer {
57 //! #     fn node_id(&self) -> PublicKey { unimplemented!() }
58 //! #     fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
59 //! #     fn send_payment(
60 //! #         &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
61 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
62 //! #     fn send_spontaneous_payment(
63 //! #         &self, route: &Route, payment_preimage: PaymentPreimage
64 //! #     ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
65 //! #     fn retry_payment(
66 //! #         &self, route: &Route, payment_id: PaymentId
67 //! #     ) -> Result<(), PaymentSendFailure> { unimplemented!() }
68 //! # }
69 //! #
70 //! # struct FakeRouter {}
71 //! # impl<S: Score> Router<S> for FakeRouter {
72 //! #     fn find_route(
73 //! #         &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
74 //! #         first_hops: Option<&[&ChannelDetails]>, scorer: &S
75 //! #     ) -> Result<Route, LightningError> { unimplemented!() }
76 //! # }
77 //! #
78 //! # struct FakeScorer {}
79 //! # impl Writeable for FakeScorer {
80 //! #     fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); }
81 //! # }
82 //! # impl Score for FakeScorer {
83 //! #     fn channel_penalty_msat(
84 //! #         &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
85 //! #     ) -> u64 { 0 }
86 //! #     fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
87 //! #     fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
88 //! # }
89 //! #
90 //! # struct FakeLogger {}
91 //! # impl Logger for FakeLogger {
92 //! #     fn log(&self, record: &Record) { unimplemented!() }
93 //! # }
94 //! #
95 //! # fn main() {
96 //! let event_handler = |event: &Event| {
97 //!     match event {
98 //!         Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
99 //!         Event::PaymentSent { .. } => println!("payment successful"),
100 //!         _ => {},
101 //!     }
102 //! };
103 //! # let payer = FakePayer {};
104 //! # let router = FakeRouter {};
105 //! # let scorer = RefCell::new(FakeScorer {});
106 //! # let logger = FakeLogger {};
107 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
108 //!
109 //! let invoice = "...";
110 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
111 //!     invoice_payer.pay_invoice(&invoice).unwrap();
112 //!
113 //! # let event_provider = FakeEventProvider {};
114 //!     loop {
115 //!         event_provider.process_pending_events(&invoice_payer);
116 //!     }
117 //! }
118 //! # }
119 //! ```
120 //!
121 //! # Note
122 //!
123 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
124 //! as updates to the network graph or changes to channel scores should be applied prior to
125 //! retries, typically by way of composing [`EventHandler`]s accordingly.
126
127 use crate::Invoice;
128
129 use bitcoin_hashes::Hash;
130 use bitcoin_hashes::sha256::Hash as Sha256;
131
132 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
133 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
134 use lightning::ln::msgs::LightningError;
135 use lightning::routing::scoring::{LockableScore, Score};
136 use lightning::routing::router::{Payee, Route, RouteParameters};
137 use lightning::util::events::{Event, EventHandler};
138 use lightning::util::logger::Logger;
139
140 use secp256k1::key::PublicKey;
141
142 use std::collections::hash_map::{self, HashMap};
143 use std::ops::Deref;
144 use std::sync::Mutex;
145 use std::time::{Duration, SystemTime};
146
147 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
148 ///
149 /// See [module-level documentation] for details.
150 ///
151 /// [module-level documentation]: crate::payment
152 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
153 where
154         P::Target: Payer,
155         R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
156         S::Target: for <'a> LockableScore<'a>,
157         L::Target: Logger,
158         E: EventHandler,
159 {
160         payer: P,
161         router: R,
162         scorer: S,
163         logger: L,
164         event_handler: E,
165         /// Caches the overall attempts at making a payment, which is updated prior to retrying.
166         payment_cache: Mutex<HashMap<PaymentHash, usize>>,
167         retry_attempts: RetryAttempts,
168 }
169
170 /// A trait defining behavior of an [`Invoice`] payer.
171 pub trait Payer {
172         /// Returns the payer's node id.
173         fn node_id(&self) -> PublicKey;
174
175         /// Returns the payer's channels.
176         fn first_hops(&self) -> Vec<ChannelDetails>;
177
178         /// Sends a payment over the Lightning Network using the given [`Route`].
179         fn send_payment(
180                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
181         ) -> Result<PaymentId, PaymentSendFailure>;
182
183         /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
184         fn send_spontaneous_payment(
185                 &self, route: &Route, payment_preimage: PaymentPreimage
186         ) -> Result<PaymentId, PaymentSendFailure>;
187
188         /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
189         fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
190 }
191
192 /// A trait defining behavior for routing an [`Invoice`] payment.
193 pub trait Router<S: Score> {
194         /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
195         fn find_route(
196                 &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
197                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
198         ) -> Result<Route, LightningError>;
199 }
200
201 /// Number of attempts to retry payment path failures for an [`Invoice`].
202 ///
203 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
204 /// payments, if this is less than the total number of paths, we will never even retry all of the
205 /// payment's paths.
206 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
207 pub struct RetryAttempts(pub usize);
208
209 /// An error that may occur when making a payment.
210 #[derive(Clone, Debug)]
211 pub enum PaymentError {
212         /// An error resulting from the provided [`Invoice`] or payment hash.
213         Invoice(&'static str),
214         /// An error occurring when finding a route.
215         Routing(LightningError),
216         /// An error occurring when sending a payment.
217         Sending(PaymentSendFailure),
218 }
219
220 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
221 where
222         P::Target: Payer,
223         R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
224         S::Target: for <'a> LockableScore<'a>,
225         L::Target: Logger,
226         E: EventHandler,
227 {
228         /// Creates an invoice payer that retries failed payment paths.
229         ///
230         /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
231         /// `retry_attempts` has been exceeded for a given [`Invoice`].
232         pub fn new(
233                 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
234         ) -> Self {
235                 Self {
236                         payer,
237                         router,
238                         scorer,
239                         logger,
240                         event_handler,
241                         payment_cache: Mutex::new(HashMap::new()),
242                         retry_attempts,
243                 }
244         }
245
246         /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
247         ///
248         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
249         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
250         /// for you.
251         pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
252                 if invoice.amount_milli_satoshis().is_none() {
253                         Err(PaymentError::Invoice("amount missing"))
254                 } else {
255                         self.pay_invoice_using_amount(invoice, None)
256                 }
257         }
258
259         /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
260         /// case a retry is needed.
261         ///
262         /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
263         /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
264         /// for you.
265         pub fn pay_zero_value_invoice(
266                 &self, invoice: &Invoice, amount_msats: u64
267         ) -> Result<PaymentId, PaymentError> {
268                 if invoice.amount_milli_satoshis().is_some() {
269                         Err(PaymentError::Invoice("amount unexpected"))
270                 } else {
271                         self.pay_invoice_using_amount(invoice, Some(amount_msats))
272                 }
273         }
274
275         fn pay_invoice_using_amount(
276                 &self, invoice: &Invoice, amount_msats: Option<u64>
277         ) -> Result<PaymentId, PaymentError> {
278                 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
279
280                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
281                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
282                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
283                         hash_map::Entry::Vacant(entry) => entry.insert(0),
284                 };
285
286                 let payment_secret = Some(invoice.payment_secret().clone());
287                 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
288                         .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
289                         .with_route_hints(invoice.route_hints());
290                 if let Some(features) = invoice.features() {
291                         payee = payee.with_features(features.clone());
292                 }
293                 let params = RouteParameters {
294                         payee,
295                         final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
296                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
297                 };
298
299                 let send_payment = |route: &Route| {
300                         self.payer.send_payment(route, payment_hash, &payment_secret)
301                 };
302                 self.pay_internal(&params, payment_hash, send_payment)
303                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
304         }
305
306         /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
307         /// case a retry is needed.
308         ///
309         /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
310         /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
311         pub fn pay_pubkey(
312                 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
313                 final_cltv_expiry_delta: u32
314         ) -> Result<PaymentId, PaymentError> {
315                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
316                 match self.payment_cache.lock().unwrap().entry(payment_hash) {
317                         hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
318                         hash_map::Entry::Vacant(entry) => entry.insert(0),
319                 };
320
321                 let params = RouteParameters {
322                         payee: Payee::for_keysend(pubkey),
323                         final_value_msat: amount_msats,
324                         final_cltv_expiry_delta,
325                 };
326
327                 let send_payment = |route: &Route| {
328                         self.payer.send_spontaneous_payment(route, payment_preimage)
329                 };
330                 self.pay_internal(&params, payment_hash, send_payment)
331                         .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
332         }
333
334         fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
335                 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
336         ) -> Result<PaymentId, PaymentError> {
337                 if has_expired(params) {
338                         log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
339                         return Err(PaymentError::Invoice("Invoice expired prior to send"));
340                 }
341
342                 let payer = self.payer.node_id();
343                 let first_hops = self.payer.first_hops();
344                 let route = self.router.find_route(
345                         &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
346                         &self.scorer.lock()
347                 ).map_err(|e| PaymentError::Routing(e))?;
348
349                 match send_payment(&route) {
350                         Ok(payment_id) => Ok(payment_id),
351                         Err(e) => match e {
352                                 PaymentSendFailure::ParameterError(_) => Err(e),
353                                 PaymentSendFailure::PathParameterError(_) => Err(e),
354                                 PaymentSendFailure::AllFailedRetrySafe(_) => {
355                                         let mut payment_cache = self.payment_cache.lock().unwrap();
356                                         let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
357                                         if *retry_count >= self.retry_attempts.0 {
358                                                 Err(e)
359                                         } else {
360                                                 *retry_count += 1;
361                                                 std::mem::drop(payment_cache);
362                                                 Ok(self.pay_internal(params, payment_hash, send_payment)?)
363                                         }
364                                 },
365                                 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
366                                         if let Some(retry_data) = failed_paths_retry {
367                                                 // Some paths were sent, even if we failed to send the full MPP value our
368                                                 // recipient may misbehave and claim the funds, at which point we have to
369                                                 // consider the payment sent, so return `Ok()` here, ignoring any retry
370                                                 // errors.
371                                                 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
372                                                 Ok(payment_id)
373                                         } else {
374                                                 // This may happen if we send a payment and some paths fail, but
375                                                 // only due to a temporary monitor failure or the like, implying
376                                                 // they're really in-flight, but we haven't sent the initial
377                                                 // HTLC-Add messages yet.
378                                                 Ok(payment_id)
379                                         }
380                                 },
381                         },
382                 }.map_err(|e| PaymentError::Sending(e))
383         }
384
385         fn retry_payment(
386                 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
387         ) -> Result<(), ()> {
388                 let max_payment_attempts = self.retry_attempts.0 + 1;
389                 let attempts = *self.payment_cache.lock().unwrap()
390                         .entry(payment_hash)
391                         .and_modify(|attempts| *attempts += 1)
392                         .or_insert(1);
393
394                 if attempts >= max_payment_attempts {
395                         log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
396                         return Err(());
397                 }
398
399                 if has_expired(params) {
400                         log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
401                         return Err(());
402                 }
403
404                 let payer = self.payer.node_id();
405                 let first_hops = self.payer.first_hops();
406                 let route = self.router.find_route(
407                         &payer, &params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
408                         &self.scorer.lock()
409                 );
410                 if route.is_err() {
411                         log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
412                         return Err(());
413                 }
414
415                 match self.payer.retry_payment(&route.unwrap(), payment_id) {
416                         Ok(()) => Ok(()),
417                         Err(PaymentSendFailure::ParameterError(_)) |
418                         Err(PaymentSendFailure::PathParameterError(_)) => {
419                                 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
420                                 Err(())
421                         },
422                         Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
423                                 self.retry_payment(payment_id, payment_hash, params)
424                         },
425                         Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
426                                 if let Some(retry) = failed_paths_retry {
427                                         // Always return Ok for the same reason as noted in pay_internal.
428                                         let _ = self.retry_payment(payment_id, payment_hash, &retry);
429                                 }
430                                 Ok(())
431                         },
432                 }
433         }
434
435         /// Removes the payment cached by the given payment hash.
436         ///
437         /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
438         /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
439         pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
440                 self.payment_cache.lock().unwrap().remove(payment_hash);
441         }
442 }
443
444 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
445         invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
446 }
447
448 fn has_expired(params: &RouteParameters) -> bool {
449         if let Some(expiry_time) = params.payee.expiry_time {
450                 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
451         } else { false }
452 }
453
454 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
455 where
456         P::Target: Payer,
457         R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
458         S::Target: for <'a> LockableScore<'a>,
459         L::Target: Logger,
460         E: EventHandler,
461 {
462         fn handle_event(&self, event: &Event) {
463                 match event {
464                         Event::PaymentPathFailed {
465                                 all_paths_failed, payment_id, payment_hash, rejected_by_dest, path,
466                                 short_channel_id, retry, ..
467                         } => {
468                                 if let Some(short_channel_id) = short_channel_id {
469                                         let path = path.iter().collect::<Vec<_>>();
470                                         self.scorer.lock().payment_path_failed(&path, *short_channel_id);
471                                 }
472
473                                 if *rejected_by_dest {
474                                         log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
475                                 } else if payment_id.is_none() {
476                                         log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
477                                 } else if retry.is_none() {
478                                         log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
479                                 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
480                                         // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
481                                         return;
482                                 }
483
484                                 if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); }
485                         },
486                         Event::PaymentPathSuccessful { path, .. } => {
487                                 let path = path.iter().collect::<Vec<_>>();
488                                 self.scorer.lock().payment_path_successful(&path);
489                         },
490                         Event::PaymentSent { payment_hash, .. } => {
491                                 let mut payment_cache = self.payment_cache.lock().unwrap();
492                                 let attempts = payment_cache
493                                         .remove(payment_hash)
494                                         .map_or(1, |attempts| attempts + 1);
495                                 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
496                         },
497                         _ => {},
498                 }
499
500                 // Delegate to the decorated event handler unless the payment is retried.
501                 self.event_handler.handle_event(event)
502         }
503 }
504
505 #[cfg(test)]
506 mod tests {
507         use super::*;
508         use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
509         use utils::create_invoice_from_channelmanager;
510         use bitcoin_hashes::sha256::Hash as Sha256;
511         use lightning::ln::PaymentPreimage;
512         use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
513         use lightning::ln::functional_test_utils::*;
514         use lightning::ln::msgs::{ErrorAction, LightningError};
515         use lightning::routing::network_graph::NodeId;
516         use lightning::routing::router::{Payee, Route, RouteHop};
517         use lightning::util::test_utils::TestLogger;
518         use lightning::util::errors::APIError;
519         use lightning::util::events::{Event, MessageSendEventsProvider};
520         use secp256k1::{SecretKey, PublicKey, Secp256k1};
521         use std::cell::RefCell;
522         use std::collections::VecDeque;
523         use std::time::{SystemTime, Duration};
524
525         fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
526                 let payment_hash = Sha256::hash(&payment_preimage.0);
527                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
528                 InvoiceBuilder::new(Currency::Bitcoin)
529                         .description("test".into())
530                         .payment_hash(payment_hash)
531                         .payment_secret(PaymentSecret([0; 32]))
532                         .current_timestamp()
533                         .min_final_cltv_expiry(144)
534                         .amount_milli_satoshis(128)
535                         .build_signed(|hash| {
536                                 Secp256k1::new().sign_recoverable(hash, &private_key)
537                         })
538                         .unwrap()
539         }
540
541         fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
542                 let payment_hash = Sha256::hash(&payment_preimage.0);
543                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
544                 InvoiceBuilder::new(Currency::Bitcoin)
545                         .description("test".into())
546                         .payment_hash(payment_hash)
547                         .payment_secret(PaymentSecret([0; 32]))
548                         .current_timestamp()
549                         .min_final_cltv_expiry(144)
550                         .build_signed(|hash| {
551                                 Secp256k1::new().sign_recoverable(hash, &private_key)
552                         })
553                         .unwrap()
554         }
555
556         fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
557                 let payment_hash = Sha256::hash(&payment_preimage.0);
558                 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
559                 let timestamp = SystemTime::now()
560                         .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
561                         .unwrap();
562                 InvoiceBuilder::new(Currency::Bitcoin)
563                         .description("test".into())
564                         .payment_hash(payment_hash)
565                         .payment_secret(PaymentSecret([0; 32]))
566                         .timestamp(timestamp)
567                         .min_final_cltv_expiry(144)
568                         .amount_milli_satoshis(128)
569                         .build_signed(|hash| {
570                                 Secp256k1::new().sign_recoverable(hash, &private_key)
571                         })
572                         .unwrap()
573         }
574
575         fn pubkey() -> PublicKey {
576                 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
577         }
578
579         #[test]
580         fn pays_invoice_on_first_attempt() {
581                 let event_handled = core::cell::RefCell::new(false);
582                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
583
584                 let payment_preimage = PaymentPreimage([1; 32]);
585                 let invoice = invoice(payment_preimage);
586                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
587                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
588
589                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
590                 let router = TestRouter {};
591                 let scorer = RefCell::new(TestScorer::new());
592                 let logger = TestLogger::new();
593                 let invoice_payer =
594                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
595
596                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
597                 assert_eq!(*payer.attempts.borrow(), 1);
598
599                 invoice_payer.handle_event(&Event::PaymentSent {
600                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
601                 });
602                 assert_eq!(*event_handled.borrow(), true);
603                 assert_eq!(*payer.attempts.borrow(), 1);
604         }
605
606         #[test]
607         fn pays_invoice_on_retry() {
608                 let event_handled = core::cell::RefCell::new(false);
609                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
610
611                 let payment_preimage = PaymentPreimage([1; 32]);
612                 let invoice = invoice(payment_preimage);
613                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
614                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
615
616                 let payer = TestPayer::new()
617                         .expect_send(Amount::ForInvoice(final_value_msat))
618                         .expect_send(Amount::OnRetry(final_value_msat / 2));
619                 let router = TestRouter {};
620                 let scorer = RefCell::new(TestScorer::new());
621                 let logger = TestLogger::new();
622                 let invoice_payer =
623                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
624
625                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
626                 assert_eq!(*payer.attempts.borrow(), 1);
627
628                 let event = Event::PaymentPathFailed {
629                         payment_id,
630                         payment_hash,
631                         network_update: None,
632                         rejected_by_dest: false,
633                         all_paths_failed: false,
634                         path: TestRouter::path_for_value(final_value_msat),
635                         short_channel_id: None,
636                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
637                 };
638                 invoice_payer.handle_event(&event);
639                 assert_eq!(*event_handled.borrow(), false);
640                 assert_eq!(*payer.attempts.borrow(), 2);
641
642                 invoice_payer.handle_event(&Event::PaymentSent {
643                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
644                 });
645                 assert_eq!(*event_handled.borrow(), true);
646                 assert_eq!(*payer.attempts.borrow(), 2);
647         }
648
649         #[test]
650         fn pays_invoice_on_partial_failure() {
651                 let event_handler = |_: &_| { panic!() };
652
653                 let payment_preimage = PaymentPreimage([1; 32]);
654                 let invoice = invoice(payment_preimage);
655                 let retry = TestRouter::retry_for_invoice(&invoice);
656                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
657
658                 let payer = TestPayer::new()
659                         .fails_with_partial_failure(retry.clone(), OnAttempt(1))
660                         .fails_with_partial_failure(retry, OnAttempt(2))
661                         .expect_send(Amount::ForInvoice(final_value_msat))
662                         .expect_send(Amount::OnRetry(final_value_msat / 2))
663                         .expect_send(Amount::OnRetry(final_value_msat / 2));
664                 let router = TestRouter {};
665                 let scorer = RefCell::new(TestScorer::new());
666                 let logger = TestLogger::new();
667                 let invoice_payer =
668                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
669
670                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
671         }
672
673         #[test]
674         fn retries_payment_path_for_unknown_payment() {
675                 let event_handled = core::cell::RefCell::new(false);
676                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
677
678                 let payment_preimage = PaymentPreimage([1; 32]);
679                 let invoice = invoice(payment_preimage);
680                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
681                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
682
683                 let payer = TestPayer::new()
684                         .expect_send(Amount::OnRetry(final_value_msat / 2))
685                         .expect_send(Amount::OnRetry(final_value_msat / 2));
686                 let router = TestRouter {};
687                 let scorer = RefCell::new(TestScorer::new());
688                 let logger = TestLogger::new();
689                 let invoice_payer =
690                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
691
692                 let payment_id = Some(PaymentId([1; 32]));
693                 let event = Event::PaymentPathFailed {
694                         payment_id,
695                         payment_hash,
696                         network_update: None,
697                         rejected_by_dest: false,
698                         all_paths_failed: false,
699                         path: TestRouter::path_for_value(final_value_msat),
700                         short_channel_id: None,
701                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
702                 };
703                 invoice_payer.handle_event(&event);
704                 assert_eq!(*event_handled.borrow(), false);
705                 assert_eq!(*payer.attempts.borrow(), 1);
706
707                 invoice_payer.handle_event(&event);
708                 assert_eq!(*event_handled.borrow(), false);
709                 assert_eq!(*payer.attempts.borrow(), 2);
710
711                 invoice_payer.handle_event(&Event::PaymentSent {
712                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
713                 });
714                 assert_eq!(*event_handled.borrow(), true);
715                 assert_eq!(*payer.attempts.borrow(), 2);
716         }
717
718         #[test]
719         fn fails_paying_invoice_after_max_retries() {
720                 let event_handled = core::cell::RefCell::new(false);
721                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
722
723                 let payment_preimage = PaymentPreimage([1; 32]);
724                 let invoice = invoice(payment_preimage);
725                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
726
727                 let payer = TestPayer::new()
728                         .expect_send(Amount::ForInvoice(final_value_msat))
729                         .expect_send(Amount::OnRetry(final_value_msat / 2))
730                         .expect_send(Amount::OnRetry(final_value_msat / 2));
731                 let router = TestRouter {};
732                 let scorer = RefCell::new(TestScorer::new());
733                 let logger = TestLogger::new();
734                 let invoice_payer =
735                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
736
737                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
738                 assert_eq!(*payer.attempts.borrow(), 1);
739
740                 let event = Event::PaymentPathFailed {
741                         payment_id,
742                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
743                         network_update: None,
744                         rejected_by_dest: false,
745                         all_paths_failed: true,
746                         path: TestRouter::path_for_value(final_value_msat),
747                         short_channel_id: None,
748                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
749                 };
750                 invoice_payer.handle_event(&event);
751                 assert_eq!(*event_handled.borrow(), false);
752                 assert_eq!(*payer.attempts.borrow(), 2);
753
754                 let event = Event::PaymentPathFailed {
755                         payment_id,
756                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
757                         network_update: None,
758                         rejected_by_dest: false,
759                         all_paths_failed: false,
760                         path: TestRouter::path_for_value(final_value_msat / 2),
761                         short_channel_id: None,
762                         retry: Some(RouteParameters {
763                                 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
764                         }),
765                 };
766                 invoice_payer.handle_event(&event);
767                 assert_eq!(*event_handled.borrow(), false);
768                 assert_eq!(*payer.attempts.borrow(), 3);
769
770                 invoice_payer.handle_event(&event);
771                 assert_eq!(*event_handled.borrow(), true);
772                 assert_eq!(*payer.attempts.borrow(), 3);
773         }
774
775         #[test]
776         fn fails_paying_invoice_with_missing_retry_params() {
777                 let event_handled = core::cell::RefCell::new(false);
778                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
779
780                 let payment_preimage = PaymentPreimage([1; 32]);
781                 let invoice = invoice(payment_preimage);
782                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
783
784                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
785                 let router = TestRouter {};
786                 let scorer = RefCell::new(TestScorer::new());
787                 let logger = TestLogger::new();
788                 let invoice_payer =
789                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
790
791                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
792                 assert_eq!(*payer.attempts.borrow(), 1);
793
794                 let event = Event::PaymentPathFailed {
795                         payment_id,
796                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
797                         network_update: None,
798                         rejected_by_dest: false,
799                         all_paths_failed: false,
800                         path: vec![],
801                         short_channel_id: None,
802                         retry: None,
803                 };
804                 invoice_payer.handle_event(&event);
805                 assert_eq!(*event_handled.borrow(), true);
806                 assert_eq!(*payer.attempts.borrow(), 1);
807         }
808
809         #[test]
810         fn fails_paying_invoice_after_expiration() {
811                 let event_handled = core::cell::RefCell::new(false);
812                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
813
814                 let payer = TestPayer::new();
815                 let router = TestRouter {};
816                 let scorer = RefCell::new(TestScorer::new());
817                 let logger = TestLogger::new();
818                 let invoice_payer =
819                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
820
821                 let payment_preimage = PaymentPreimage([1; 32]);
822                 let invoice = expired_invoice(payment_preimage);
823                 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
824                         assert_eq!(msg, "Invoice expired prior to send");
825                 } else { panic!("Expected Invoice Error"); }
826         }
827
828         #[test]
829         fn fails_retrying_invoice_after_expiration() {
830                 let event_handled = core::cell::RefCell::new(false);
831                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
832
833                 let payment_preimage = PaymentPreimage([1; 32]);
834                 let invoice = invoice(payment_preimage);
835                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
836
837                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
838                 let router = TestRouter {};
839                 let scorer = RefCell::new(TestScorer::new());
840                 let logger = TestLogger::new();
841                 let invoice_payer =
842                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
843
844                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
845                 assert_eq!(*payer.attempts.borrow(), 1);
846
847                 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
848                 retry_data.payee.expiry_time = Some(SystemTime::now()
849                         .checked_sub(Duration::from_secs(2)).unwrap()
850                         .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
851                 let event = Event::PaymentPathFailed {
852                         payment_id,
853                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
854                         network_update: None,
855                         rejected_by_dest: false,
856                         all_paths_failed: false,
857                         path: vec![],
858                         short_channel_id: None,
859                         retry: Some(retry_data),
860                 };
861                 invoice_payer.handle_event(&event);
862                 assert_eq!(*event_handled.borrow(), true);
863                 assert_eq!(*payer.attempts.borrow(), 1);
864         }
865
866         #[test]
867         fn fails_paying_invoice_after_retry_error() {
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 final_value_msat = invoice.amount_milli_satoshis().unwrap();
874
875                 let payer = TestPayer::new()
876                         .fails_on_attempt(2)
877                         .expect_send(Amount::ForInvoice(final_value_msat))
878                         .expect_send(Amount::OnRetry(final_value_msat / 2));
879                 let router = TestRouter {};
880                 let scorer = RefCell::new(TestScorer::new());
881                 let logger = TestLogger::new();
882                 let invoice_payer =
883                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
884
885                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
886                 assert_eq!(*payer.attempts.borrow(), 1);
887
888                 let event = Event::PaymentPathFailed {
889                         payment_id,
890                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
891                         network_update: None,
892                         rejected_by_dest: false,
893                         all_paths_failed: false,
894                         path: TestRouter::path_for_value(final_value_msat / 2),
895                         short_channel_id: None,
896                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
897                 };
898                 invoice_payer.handle_event(&event);
899                 assert_eq!(*event_handled.borrow(), true);
900                 assert_eq!(*payer.attempts.borrow(), 2);
901         }
902
903         #[test]
904         fn fails_paying_invoice_after_rejected_by_payee() {
905                 let event_handled = core::cell::RefCell::new(false);
906                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
907
908                 let payment_preimage = PaymentPreimage([1; 32]);
909                 let invoice = invoice(payment_preimage);
910                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
911
912                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
913                 let router = TestRouter {};
914                 let scorer = RefCell::new(TestScorer::new());
915                 let logger = TestLogger::new();
916                 let invoice_payer =
917                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
918
919                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
920                 assert_eq!(*payer.attempts.borrow(), 1);
921
922                 let event = Event::PaymentPathFailed {
923                         payment_id,
924                         payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
925                         network_update: None,
926                         rejected_by_dest: true,
927                         all_paths_failed: false,
928                         path: vec![],
929                         short_channel_id: None,
930                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
931                 };
932                 invoice_payer.handle_event(&event);
933                 assert_eq!(*event_handled.borrow(), true);
934                 assert_eq!(*payer.attempts.borrow(), 1);
935         }
936
937         #[test]
938         fn fails_repaying_invoice_with_pending_payment() {
939                 let event_handled = core::cell::RefCell::new(false);
940                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
941
942                 let payment_preimage = PaymentPreimage([1; 32]);
943                 let invoice = invoice(payment_preimage);
944                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
945
946                 let payer = TestPayer::new()
947                         .expect_send(Amount::ForInvoice(final_value_msat))
948                         .expect_send(Amount::ForInvoice(final_value_msat));
949                 let router = TestRouter {};
950                 let scorer = RefCell::new(TestScorer::new());
951                 let logger = TestLogger::new();
952                 let invoice_payer =
953                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
954
955                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
956
957                 // Cannot repay an invoice pending payment.
958                 match invoice_payer.pay_invoice(&invoice) {
959                         Err(PaymentError::Invoice("payment pending")) => {},
960                         Err(_) => panic!("unexpected error"),
961                         Ok(_) => panic!("expected invoice error"),
962                 }
963
964                 // Can repay an invoice once cleared from cache.
965                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
966                 invoice_payer.remove_cached_payment(&payment_hash);
967                 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
968
969                 // Cannot retry paying an invoice if cleared from cache.
970                 invoice_payer.remove_cached_payment(&payment_hash);
971                 let event = Event::PaymentPathFailed {
972                         payment_id,
973                         payment_hash,
974                         network_update: None,
975                         rejected_by_dest: false,
976                         all_paths_failed: false,
977                         path: vec![],
978                         short_channel_id: None,
979                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
980                 };
981                 invoice_payer.handle_event(&event);
982                 assert_eq!(*event_handled.borrow(), true);
983         }
984
985         #[test]
986         fn fails_paying_invoice_with_routing_errors() {
987                 let payer = TestPayer::new();
988                 let router = FailingRouter {};
989                 let scorer = RefCell::new(TestScorer::new());
990                 let logger = TestLogger::new();
991                 let invoice_payer =
992                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
993
994                 let payment_preimage = PaymentPreimage([1; 32]);
995                 let invoice = invoice(payment_preimage);
996                 match invoice_payer.pay_invoice(&invoice) {
997                         Err(PaymentError::Routing(_)) => {},
998                         Err(_) => panic!("unexpected error"),
999                         Ok(_) => panic!("expected routing error"),
1000                 }
1001         }
1002
1003         #[test]
1004         fn fails_paying_invoice_with_sending_errors() {
1005                 let payment_preimage = PaymentPreimage([1; 32]);
1006                 let invoice = invoice(payment_preimage);
1007                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1008
1009                 let payer = TestPayer::new()
1010                         .fails_on_attempt(1)
1011                         .expect_send(Amount::ForInvoice(final_value_msat));
1012                 let router = TestRouter {};
1013                 let scorer = RefCell::new(TestScorer::new());
1014                 let logger = TestLogger::new();
1015                 let invoice_payer =
1016                         InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1017
1018                 match invoice_payer.pay_invoice(&invoice) {
1019                         Err(PaymentError::Sending(_)) => {},
1020                         Err(_) => panic!("unexpected error"),
1021                         Ok(_) => panic!("expected sending error"),
1022                 }
1023         }
1024
1025         #[test]
1026         fn pays_zero_value_invoice_using_amount() {
1027                 let event_handled = core::cell::RefCell::new(false);
1028                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1029
1030                 let payment_preimage = PaymentPreimage([1; 32]);
1031                 let invoice = zero_value_invoice(payment_preimage);
1032                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1033                 let final_value_msat = 100;
1034
1035                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1036                 let router = TestRouter {};
1037                 let scorer = RefCell::new(TestScorer::new());
1038                 let logger = TestLogger::new();
1039                 let invoice_payer =
1040                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1041
1042                 let payment_id =
1043                         Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1044                 assert_eq!(*payer.attempts.borrow(), 1);
1045
1046                 invoice_payer.handle_event(&Event::PaymentSent {
1047                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1048                 });
1049                 assert_eq!(*event_handled.borrow(), true);
1050                 assert_eq!(*payer.attempts.borrow(), 1);
1051         }
1052
1053         #[test]
1054         fn fails_paying_zero_value_invoice_with_amount() {
1055                 let event_handled = core::cell::RefCell::new(false);
1056                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1057
1058                 let payer = TestPayer::new();
1059                 let router = TestRouter {};
1060                 let scorer = RefCell::new(TestScorer::new());
1061                 let logger = TestLogger::new();
1062                 let invoice_payer =
1063                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1064
1065                 let payment_preimage = PaymentPreimage([1; 32]);
1066                 let invoice = invoice(payment_preimage);
1067
1068                 // Cannot repay an invoice pending payment.
1069                 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1070                         Err(PaymentError::Invoice("amount unexpected")) => {},
1071                         Err(_) => panic!("unexpected error"),
1072                         Ok(_) => panic!("expected invoice error"),
1073                 }
1074         }
1075
1076         #[test]
1077         fn pays_pubkey_with_amount() {
1078                 let event_handled = core::cell::RefCell::new(false);
1079                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1080
1081                 let pubkey = pubkey();
1082                 let payment_preimage = PaymentPreimage([1; 32]);
1083                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1084                 let final_value_msat = 100;
1085                 let final_cltv_expiry_delta = 42;
1086
1087                 let payer = TestPayer::new()
1088                         .expect_send(Amount::Spontaneous(final_value_msat))
1089                         .expect_send(Amount::OnRetry(final_value_msat));
1090                 let router = TestRouter {};
1091                 let scorer = RefCell::new(TestScorer::new());
1092                 let logger = TestLogger::new();
1093                 let invoice_payer =
1094                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1095
1096                 let payment_id = Some(invoice_payer.pay_pubkey(
1097                                 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1098                         ).unwrap());
1099                 assert_eq!(*payer.attempts.borrow(), 1);
1100
1101                 let retry = RouteParameters {
1102                         payee: Payee::for_keysend(pubkey),
1103                         final_value_msat,
1104                         final_cltv_expiry_delta,
1105                 };
1106                 let event = Event::PaymentPathFailed {
1107                         payment_id,
1108                         payment_hash,
1109                         network_update: None,
1110                         rejected_by_dest: false,
1111                         all_paths_failed: false,
1112                         path: vec![],
1113                         short_channel_id: None,
1114                         retry: Some(retry),
1115                 };
1116                 invoice_payer.handle_event(&event);
1117                 assert_eq!(*event_handled.borrow(), false);
1118                 assert_eq!(*payer.attempts.borrow(), 2);
1119
1120                 invoice_payer.handle_event(&Event::PaymentSent {
1121                         payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1122                 });
1123                 assert_eq!(*event_handled.borrow(), true);
1124                 assert_eq!(*payer.attempts.borrow(), 2);
1125         }
1126
1127         #[test]
1128         fn scores_failed_channel() {
1129                 let event_handled = core::cell::RefCell::new(false);
1130                 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1131
1132                 let payment_preimage = PaymentPreimage([1; 32]);
1133                 let invoice = invoice(payment_preimage);
1134                 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1135                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1136                 let path = TestRouter::path_for_value(final_value_msat);
1137                 let short_channel_id = Some(path[0].short_channel_id);
1138
1139                 // Expect that scorer is given short_channel_id upon handling the event.
1140                 let payer = TestPayer::new()
1141                         .expect_send(Amount::ForInvoice(final_value_msat))
1142                         .expect_send(Amount::OnRetry(final_value_msat / 2));
1143                 let router = TestRouter {};
1144                 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1145                         path: path.clone(), short_channel_id: path[0].short_channel_id,
1146                 }));
1147                 let logger = TestLogger::new();
1148                 let invoice_payer =
1149                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1150
1151                 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1152                 let event = Event::PaymentPathFailed {
1153                         payment_id,
1154                         payment_hash,
1155                         network_update: None,
1156                         rejected_by_dest: false,
1157                         all_paths_failed: false,
1158                         path,
1159                         short_channel_id,
1160                         retry: Some(TestRouter::retry_for_invoice(&invoice)),
1161                 };
1162                 invoice_payer.handle_event(&event);
1163         }
1164
1165         #[test]
1166         fn scores_successful_channels() {
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 payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1173                 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1174                 let route = TestRouter::route_for_value(final_value_msat);
1175
1176                 // Expect that scorer is given short_channel_id upon handling the event.
1177                 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1178                 let router = TestRouter {};
1179                 let scorer = RefCell::new(TestScorer::new()
1180                         .expect(PaymentPath::Success { path: route.paths[0].clone() })
1181                         .expect(PaymentPath::Success { path: route.paths[1].clone() })
1182                 );
1183                 let logger = TestLogger::new();
1184                 let invoice_payer =
1185                         InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1186
1187                 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1188                 let event = Event::PaymentPathSuccessful {
1189                         payment_id, payment_hash, path: route.paths[0].clone()
1190                 };
1191                 invoice_payer.handle_event(&event);
1192                 let event = Event::PaymentPathSuccessful {
1193                         payment_id, payment_hash, path: route.paths[1].clone()
1194                 };
1195                 invoice_payer.handle_event(&event);
1196         }
1197
1198         struct TestRouter;
1199
1200         impl TestRouter {
1201                 fn route_for_value(final_value_msat: u64) -> Route {
1202                         Route {
1203                                 paths: vec![
1204                                         vec![RouteHop {
1205                                                 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1206                                                 channel_features: ChannelFeatures::empty(),
1207                                                 node_features: NodeFeatures::empty(),
1208                                                 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1209                                         }],
1210                                         vec![RouteHop {
1211                                                 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1212                                                 channel_features: ChannelFeatures::empty(),
1213                                                 node_features: NodeFeatures::empty(),
1214                                                 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1215                                         }],
1216                                 ],
1217                                 payee: None,
1218                         }
1219                 }
1220
1221                 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1222                         TestRouter::route_for_value(final_value_msat).paths[0].clone()
1223                 }
1224
1225                 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1226                         let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1227                                 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1228                                 .with_route_hints(invoice.route_hints());
1229                         if let Some(features) = invoice.features() {
1230                                 payee = payee.with_features(features.clone());
1231                         }
1232                         let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1233                         RouteParameters {
1234                                 payee,
1235                                 final_value_msat,
1236                                 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1237                         }
1238                 }
1239         }
1240
1241         impl<S: Score> Router<S> for TestRouter {
1242                 fn find_route(
1243                         &self, _payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
1244                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1245                 ) -> Result<Route, LightningError> {
1246                         Ok(Route {
1247                                 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1248                         })
1249                 }
1250         }
1251
1252         struct FailingRouter;
1253
1254         impl<S: Score> Router<S> for FailingRouter {
1255                 fn find_route(
1256                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1257                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1258                 ) -> Result<Route, LightningError> {
1259                         Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1260                 }
1261         }
1262
1263         struct TestScorer {
1264                 expectations: Option<VecDeque<PaymentPath>>,
1265         }
1266
1267         #[derive(Debug)]
1268         enum PaymentPath {
1269                 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1270                 Success { path: Vec<RouteHop> },
1271         }
1272
1273         impl TestScorer {
1274                 fn new() -> Self {
1275                         Self {
1276                                 expectations: None,
1277                         }
1278                 }
1279
1280                 fn expect(mut self, expectation: PaymentPath) -> Self {
1281                         self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1282                         self
1283                 }
1284         }
1285
1286         #[cfg(c_bindings)]
1287         impl lightning::util::ser::Writeable for TestScorer {
1288                 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1289         }
1290
1291         impl Score for TestScorer {
1292                 fn channel_penalty_msat(
1293                         &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
1294                 ) -> u64 { 0 }
1295
1296                 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1297                         if let Some(expectations) = &mut self.expectations {
1298                                 match expectations.pop_front() {
1299                                         Some(PaymentPath::Failure { path, short_channel_id }) => {
1300                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1301                                                 assert_eq!(actual_short_channel_id, short_channel_id);
1302                                         },
1303                                         Some(PaymentPath::Success { path }) => {
1304                                                 panic!("Unexpected successful payment path: {:?}", path)
1305                                         },
1306                                         None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1307                                 }
1308                         }
1309                 }
1310
1311                 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1312                         if let Some(expectations) = &mut self.expectations {
1313                                 match expectations.pop_front() {
1314                                         Some(PaymentPath::Failure { path, .. }) => {
1315                                                 panic!("Unexpected payment path failure: {:?}", path)
1316                                         },
1317                                         Some(PaymentPath::Success { path }) => {
1318                                                 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1319                                         },
1320                                         None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1321                                 }
1322                         }
1323                 }
1324         }
1325
1326         impl Drop for TestScorer {
1327                 fn drop(&mut self) {
1328                         if std::thread::panicking() {
1329                                 return;
1330                         }
1331
1332                         if let Some(expectations) = &self.expectations {
1333                                 if !expectations.is_empty() {
1334                                         panic!("Unsatisfied scorer expectations: {:?}", expectations);
1335                                 }
1336                         }
1337                 }
1338         }
1339
1340         struct TestPayer {
1341                 expectations: core::cell::RefCell<VecDeque<Amount>>,
1342                 attempts: core::cell::RefCell<usize>,
1343                 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1344         }
1345
1346         #[derive(Clone, Debug, PartialEq, Eq)]
1347         enum Amount {
1348                 ForInvoice(u64),
1349                 Spontaneous(u64),
1350                 OnRetry(u64),
1351         }
1352
1353         struct OnAttempt(usize);
1354
1355         impl TestPayer {
1356                 fn new() -> Self {
1357                         Self {
1358                                 expectations: core::cell::RefCell::new(VecDeque::new()),
1359                                 attempts: core::cell::RefCell::new(0),
1360                                 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1361                         }
1362                 }
1363
1364                 fn expect_send(self, value_msat: Amount) -> Self {
1365                         self.expectations.borrow_mut().push_back(value_msat);
1366                         self
1367                 }
1368
1369                 fn fails_on_attempt(self, attempt: usize) -> Self {
1370                         let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1371                         self.fails_with(failure, OnAttempt(attempt))
1372                 }
1373
1374                 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1375                         self.fails_with(PaymentSendFailure::PartialFailure {
1376                                 results: vec![],
1377                                 failed_paths_retry: Some(retry),
1378                                 payment_id: PaymentId([1; 32]),
1379                         }, attempt)
1380                 }
1381
1382                 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1383                         self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1384                         self
1385                 }
1386
1387                 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1388                         let mut attempts = self.attempts.borrow_mut();
1389                         *attempts += 1;
1390
1391                         match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1392                                 Some(failure) => Err(failure),
1393                                 None => Ok(PaymentId([1; 32])),
1394                         }
1395                 }
1396
1397                 fn check_value_msats(&self, actual_value_msats: Amount) {
1398                         let expected_value_msats = self.expectations.borrow_mut().pop_front();
1399                         if let Some(expected_value_msats) = expected_value_msats {
1400                                 assert_eq!(actual_value_msats, expected_value_msats);
1401                         } else {
1402                                 panic!("Unexpected amount: {:?}", actual_value_msats);
1403                         }
1404                 }
1405         }
1406
1407         impl Drop for TestPayer {
1408                 fn drop(&mut self) {
1409                         if std::thread::panicking() {
1410                                 return;
1411                         }
1412
1413                         if !self.expectations.borrow().is_empty() {
1414                                 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1415                         }
1416                 }
1417         }
1418
1419         impl Payer for TestPayer {
1420                 fn node_id(&self) -> PublicKey {
1421                         let secp_ctx = Secp256k1::new();
1422                         PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1423                 }
1424
1425                 fn first_hops(&self) -> Vec<ChannelDetails> {
1426                         Vec::new()
1427                 }
1428
1429                 fn send_payment(
1430                         &self, route: &Route, _payment_hash: PaymentHash,
1431                         _payment_secret: &Option<PaymentSecret>
1432                 ) -> Result<PaymentId, PaymentSendFailure> {
1433                         self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1434                         self.check_attempts()
1435                 }
1436
1437                 fn send_spontaneous_payment(
1438                         &self, route: &Route, _payment_preimage: PaymentPreimage,
1439                 ) -> Result<PaymentId, PaymentSendFailure> {
1440                         self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1441                         self.check_attempts()
1442                 }
1443
1444                 fn retry_payment(
1445                         &self, route: &Route, _payment_id: PaymentId
1446                 ) -> Result<(), PaymentSendFailure> {
1447                         self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1448                         self.check_attempts().map(|_| ())
1449                 }
1450         }
1451
1452         // *** Full Featured Functional Tests with a Real ChannelManager ***
1453         struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1454
1455         impl<S: Score> Router<S> for ManualRouter {
1456                 fn find_route(
1457                         &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1458                         _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1459                 ) -> Result<Route, LightningError> {
1460                         self.0.borrow_mut().pop_front().unwrap()
1461                 }
1462         }
1463         impl ManualRouter {
1464                 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1465                         self.0.borrow_mut().push_back(result);
1466                 }
1467         }
1468         impl Drop for ManualRouter {
1469                 fn drop(&mut self) {
1470                         if std::thread::panicking() {
1471                                 return;
1472                         }
1473                         assert!(self.0.borrow_mut().is_empty());
1474                 }
1475         }
1476
1477         #[test]
1478         fn retry_multi_path_single_failed_payment() {
1479                 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1480                 let chanmon_cfgs = create_chanmon_cfgs(2);
1481                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1482                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1483                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1484
1485                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1486                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1487                 let chans = nodes[0].node.list_usable_channels();
1488                 let mut route = Route {
1489                         paths: vec![
1490                                 vec![RouteHop {
1491                                         pubkey: nodes[1].node.get_our_node_id(),
1492                                         node_features: NodeFeatures::known(),
1493                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1494                                         channel_features: ChannelFeatures::known(),
1495                                         fee_msat: 10_000,
1496                                         cltv_expiry_delta: 100,
1497                                 }],
1498                                 vec![RouteHop {
1499                                         pubkey: nodes[1].node.get_our_node_id(),
1500                                         node_features: NodeFeatures::known(),
1501                                         short_channel_id: chans[1].short_channel_id.unwrap(),
1502                                         channel_features: ChannelFeatures::known(),
1503                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1504                                         cltv_expiry_delta: 100,
1505                                 }],
1506                         ],
1507                         payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1508                 };
1509                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1510                 router.expect_find_route(Ok(route.clone()));
1511                 // On retry, split the payment across both channels.
1512                 route.paths[0][0].fee_msat = 50_000_001;
1513                 route.paths[1][0].fee_msat = 50_000_000;
1514                 router.expect_find_route(Ok(route.clone()));
1515
1516                 let event_handler = |_: &_| { panic!(); };
1517                 let scorer = RefCell::new(TestScorer::new());
1518                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1519
1520                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1521                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1522                         .is_ok());
1523                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1524                 assert_eq!(htlc_msgs.len(), 2);
1525                 check_added_monitors!(nodes[0], 2);
1526         }
1527
1528         #[test]
1529         fn immediate_retry_on_failure() {
1530                 // Tests that we can/will retry immediately after a failure
1531                 let chanmon_cfgs = create_chanmon_cfgs(2);
1532                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1533                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1534                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1535
1536                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1537                 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1538                 let chans = nodes[0].node.list_usable_channels();
1539                 let mut route = Route {
1540                         paths: vec![
1541                                 vec![RouteHop {
1542                                         pubkey: nodes[1].node.get_our_node_id(),
1543                                         node_features: NodeFeatures::known(),
1544                                         short_channel_id: chans[0].short_channel_id.unwrap(),
1545                                         channel_features: ChannelFeatures::known(),
1546                                         fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1547                                         cltv_expiry_delta: 100,
1548                                 }],
1549                         ],
1550                         payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1551                 };
1552                 let router = ManualRouter(RefCell::new(VecDeque::new()));
1553                 router.expect_find_route(Ok(route.clone()));
1554                 // On retry, split the payment across both channels.
1555                 route.paths.push(route.paths[0].clone());
1556                 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1557                 route.paths[0][0].fee_msat = 50_000_000;
1558                 route.paths[1][0].fee_msat = 50_000_001;
1559                 router.expect_find_route(Ok(route.clone()));
1560
1561                 let event_handler = |_: &_| { panic!(); };
1562                 let scorer = RefCell::new(TestScorer::new());
1563                 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1564
1565                 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1566                         &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1567                         .is_ok());
1568                 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1569                 assert_eq!(htlc_msgs.len(), 2);
1570                 check_added_monitors!(nodes[0], 2);
1571         }
1572 }