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