1 // This file is Copyright its original authors, visible in version control
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
10 //! A module for paying Lightning invoices and sending spontaneous payments.
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
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.
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.
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
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;
50 //! # struct FakeEventProvider {}
51 //! # impl EventsProvider for FakeEventProvider {
52 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
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!() }
70 //! # struct FakeRouter {}
71 //! # impl<S: Score> Router<S> for FakeRouter {
73 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
74 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
75 //! # ) -> Result<Route, LightningError> { unimplemented!() }
78 //! # struct FakeScorer {}
79 //! # impl Writeable for FakeScorer {
80 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); }
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
86 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
87 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
90 //! # struct FakeLogger {}
91 //! # impl Logger for FakeLogger {
92 //! # fn log(&self, record: &Record) { unimplemented!() }
96 //! let event_handler = |event: &Event| {
98 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
99 //! Event::PaymentSent { .. } => println!("payment successful"),
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));
109 //! let invoice = "...";
110 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
111 //! invoice_payer.pay_invoice(&invoice).unwrap();
113 //! # let event_provider = FakeEventProvider {};
115 //! event_provider.process_pending_events(&invoice_payer);
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.
129 use bitcoin_hashes::Hash;
130 use bitcoin_hashes::sha256::Hash as Sha256;
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;
140 use secp256k1::key::PublicKey;
142 use std::collections::hash_map::{self, HashMap};
144 use std::sync::Mutex;
145 use std::time::{Duration, SystemTime};
147 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
149 /// See [module-level documentation] for details.
151 /// [module-level documentation]: crate::payment
152 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
155 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
156 S::Target: for <'a> LockableScore<'a>,
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,
170 /// A trait defining behavior of an [`Invoice`] payer.
172 /// Returns the payer's node id.
173 fn node_id(&self) -> PublicKey;
175 /// Returns the payer's channels.
176 fn first_hops(&self) -> Vec<ChannelDetails>;
178 /// Sends a payment over the Lightning Network using the given [`Route`].
180 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
181 ) -> Result<PaymentId, PaymentSendFailure>;
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>;
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>;
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.
196 &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
197 first_hops: Option<&[&ChannelDetails]>, scorer: &S
198 ) -> Result<Route, LightningError>;
201 /// Number of attempts to retry payment path failures for an [`Invoice`].
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
206 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
207 pub struct RetryAttempts(pub usize);
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),
220 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
223 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
224 S::Target: for <'a> LockableScore<'a>,
228 /// Creates an invoice payer that retries failed payment paths.
230 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
231 /// `retry_attempts` has been exceeded for a given [`Invoice`].
233 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
241 payment_cache: Mutex::new(HashMap::new()),
246 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
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
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"))
255 self.pay_invoice_using_amount(invoice, None)
259 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
260 /// case a retry is needed.
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
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"))
271 self.pay_invoice_using_amount(invoice, Some(amount_msats))
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());
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),
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());
293 let params = RouteParameters {
295 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
296 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
299 let send_payment = |route: &Route| {
300 self.payer.send_payment(route, payment_hash, &payment_secret)
302 self.pay_internal(¶ms, payment_hash, send_payment)
303 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
306 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
307 /// case a retry is needed.
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.
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),
321 let params = RouteParameters {
322 payee: Payee::for_keysend(pubkey),
323 final_value_msat: amount_msats,
324 final_cltv_expiry_delta,
327 let send_payment = |route: &Route| {
328 self.payer.send_spontaneous_payment(route, payment_preimage)
330 self.pay_internal(¶ms, payment_hash, send_payment)
331 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
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"));
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<_>>()),
347 ).map_err(|e| PaymentError::Routing(e))?;
349 match send_payment(&route) {
350 Ok(payment_id) => Ok(payment_id),
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 {
361 std::mem::drop(payment_cache);
362 Ok(self.pay_internal(params, payment_hash, send_payment)?)
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
371 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
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.
382 }.map_err(|e| PaymentError::Sending(e))
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()
391 .and_modify(|attempts| *attempts += 1)
394 if attempts >= max_payment_attempts {
395 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
399 if has_expired(params) {
400 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
404 let payer = self.payer.node_id();
405 let first_hops = self.payer.first_hops();
406 let route = self.router.find_route(
407 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
411 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
415 match self.payer.retry_payment(&route.unwrap(), payment_id) {
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));
422 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
423 self.retry_payment(payment_id, payment_hash, params)
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);
435 /// Removes the payment cached by the given payment hash.
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);
444 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
445 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
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))
454 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
457 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
458 S::Target: for <'a> LockableScore<'a>,
462 fn handle_event(&self, event: &Event) {
464 Event::PaymentPathFailed {
465 all_paths_failed, payment_id, payment_hash, rejected_by_dest, path,
466 short_channel_id, retry, ..
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);
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.
484 if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); }
486 Event::PaymentPathSuccessful { path, .. } => {
487 let path = path.iter().collect::<Vec<_>>();
488 self.scorer.lock().payment_path_successful(&path);
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);
500 // Delegate to the decorated event handler unless the payment is retried.
501 self.event_handler.handle_event(event)
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};
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]))
533 .min_final_cltv_expiry(144)
534 .amount_milli_satoshis(128)
535 .build_signed(|hash| {
536 Secp256k1::new().sign_recoverable(hash, &private_key)
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]))
549 .min_final_cltv_expiry(144)
550 .build_signed(|hash| {
551 Secp256k1::new().sign_recoverable(hash, &private_key)
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))
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)
575 fn pubkey() -> PublicKey {
576 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
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; };
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();
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();
594 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
596 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
597 assert_eq!(*payer.attempts.borrow(), 1);
599 invoice_payer.handle_event(&Event::PaymentSent {
600 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
602 assert_eq!(*event_handled.borrow(), true);
603 assert_eq!(*payer.attempts.borrow(), 1);
607 fn pays_invoice_on_retry() {
608 let event_handled = core::cell::RefCell::new(false);
609 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
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();
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();
623 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
625 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
626 assert_eq!(*payer.attempts.borrow(), 1);
628 let event = Event::PaymentPathFailed {
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)),
638 invoice_payer.handle_event(&event);
639 assert_eq!(*event_handled.borrow(), false);
640 assert_eq!(*payer.attempts.borrow(), 2);
642 invoice_payer.handle_event(&Event::PaymentSent {
643 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
645 assert_eq!(*event_handled.borrow(), true);
646 assert_eq!(*payer.attempts.borrow(), 2);
650 fn pays_invoice_on_partial_failure() {
651 let event_handler = |_: &_| { panic!() };
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();
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();
668 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
670 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
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; };
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();
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();
690 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
692 let payment_id = Some(PaymentId([1; 32]));
693 let event = Event::PaymentPathFailed {
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)),
703 invoice_payer.handle_event(&event);
704 assert_eq!(*event_handled.borrow(), false);
705 assert_eq!(*payer.attempts.borrow(), 1);
707 invoice_payer.handle_event(&event);
708 assert_eq!(*event_handled.borrow(), false);
709 assert_eq!(*payer.attempts.borrow(), 2);
711 invoice_payer.handle_event(&Event::PaymentSent {
712 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
714 assert_eq!(*event_handled.borrow(), true);
715 assert_eq!(*payer.attempts.borrow(), 2);
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; };
723 let payment_preimage = PaymentPreimage([1; 32]);
724 let invoice = invoice(payment_preimage);
725 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
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();
735 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
737 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
738 assert_eq!(*payer.attempts.borrow(), 1);
740 let event = Event::PaymentPathFailed {
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)),
750 invoice_payer.handle_event(&event);
751 assert_eq!(*event_handled.borrow(), false);
752 assert_eq!(*payer.attempts.borrow(), 2);
754 let event = Event::PaymentPathFailed {
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)
766 invoice_payer.handle_event(&event);
767 assert_eq!(*event_handled.borrow(), false);
768 assert_eq!(*payer.attempts.borrow(), 3);
770 invoice_payer.handle_event(&event);
771 assert_eq!(*event_handled.borrow(), true);
772 assert_eq!(*payer.attempts.borrow(), 3);
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; };
780 let payment_preimage = PaymentPreimage([1; 32]);
781 let invoice = invoice(payment_preimage);
782 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
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();
789 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
791 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
792 assert_eq!(*payer.attempts.borrow(), 1);
794 let event = Event::PaymentPathFailed {
796 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
797 network_update: None,
798 rejected_by_dest: false,
799 all_paths_failed: false,
801 short_channel_id: None,
804 invoice_payer.handle_event(&event);
805 assert_eq!(*event_handled.borrow(), true);
806 assert_eq!(*payer.attempts.borrow(), 1);
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; };
814 let payer = TestPayer::new();
815 let router = TestRouter {};
816 let scorer = RefCell::new(TestScorer::new());
817 let logger = TestLogger::new();
819 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
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"); }
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; };
833 let payment_preimage = PaymentPreimage([1; 32]);
834 let invoice = invoice(payment_preimage);
835 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
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();
842 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
844 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
845 assert_eq!(*payer.attempts.borrow(), 1);
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 {
853 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
854 network_update: None,
855 rejected_by_dest: false,
856 all_paths_failed: false,
858 short_channel_id: None,
859 retry: Some(retry_data),
861 invoice_payer.handle_event(&event);
862 assert_eq!(*event_handled.borrow(), true);
863 assert_eq!(*payer.attempts.borrow(), 1);
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; };
871 let payment_preimage = PaymentPreimage([1; 32]);
872 let invoice = invoice(payment_preimage);
873 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
875 let payer = TestPayer::new()
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();
883 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
885 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
886 assert_eq!(*payer.attempts.borrow(), 1);
888 let event = Event::PaymentPathFailed {
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)),
898 invoice_payer.handle_event(&event);
899 assert_eq!(*event_handled.borrow(), true);
900 assert_eq!(*payer.attempts.borrow(), 2);
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; };
908 let payment_preimage = PaymentPreimage([1; 32]);
909 let invoice = invoice(payment_preimage);
910 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
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();
917 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
919 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
920 assert_eq!(*payer.attempts.borrow(), 1);
922 let event = Event::PaymentPathFailed {
924 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
925 network_update: None,
926 rejected_by_dest: true,
927 all_paths_failed: false,
929 short_channel_id: None,
930 retry: Some(TestRouter::retry_for_invoice(&invoice)),
932 invoice_payer.handle_event(&event);
933 assert_eq!(*event_handled.borrow(), true);
934 assert_eq!(*payer.attempts.borrow(), 1);
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; };
942 let payment_preimage = PaymentPreimage([1; 32]);
943 let invoice = invoice(payment_preimage);
944 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
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();
953 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
955 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
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"),
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());
969 // Cannot retry paying an invoice if cleared from cache.
970 invoice_payer.remove_cached_payment(&payment_hash);
971 let event = Event::PaymentPathFailed {
974 network_update: None,
975 rejected_by_dest: false,
976 all_paths_failed: false,
978 short_channel_id: None,
979 retry: Some(TestRouter::retry_for_invoice(&invoice)),
981 invoice_payer.handle_event(&event);
982 assert_eq!(*event_handled.borrow(), true);
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();
992 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
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"),
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();
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();
1016 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1018 match invoice_payer.pay_invoice(&invoice) {
1019 Err(PaymentError::Sending(_)) => {},
1020 Err(_) => panic!("unexpected error"),
1021 Ok(_) => panic!("expected sending error"),
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; };
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;
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();
1040 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1043 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1044 assert_eq!(*payer.attempts.borrow(), 1);
1046 invoice_payer.handle_event(&Event::PaymentSent {
1047 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1049 assert_eq!(*event_handled.borrow(), true);
1050 assert_eq!(*payer.attempts.borrow(), 1);
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; };
1058 let payer = TestPayer::new();
1059 let router = TestRouter {};
1060 let scorer = RefCell::new(TestScorer::new());
1061 let logger = TestLogger::new();
1063 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1065 let payment_preimage = PaymentPreimage([1; 32]);
1066 let invoice = invoice(payment_preimage);
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"),
1077 fn pays_pubkey_with_amount() {
1078 let event_handled = core::cell::RefCell::new(false);
1079 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
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;
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();
1094 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1096 let payment_id = Some(invoice_payer.pay_pubkey(
1097 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1099 assert_eq!(*payer.attempts.borrow(), 1);
1101 let retry = RouteParameters {
1102 payee: Payee::for_keysend(pubkey),
1104 final_cltv_expiry_delta,
1106 let event = Event::PaymentPathFailed {
1109 network_update: None,
1110 rejected_by_dest: false,
1111 all_paths_failed: false,
1113 short_channel_id: None,
1116 invoice_payer.handle_event(&event);
1117 assert_eq!(*event_handled.borrow(), false);
1118 assert_eq!(*payer.attempts.borrow(), 2);
1120 invoice_payer.handle_event(&Event::PaymentSent {
1121 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1123 assert_eq!(*event_handled.borrow(), true);
1124 assert_eq!(*payer.attempts.borrow(), 2);
1128 fn scores_failed_channel() {
1129 let event_handled = core::cell::RefCell::new(false);
1130 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
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);
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,
1147 let logger = TestLogger::new();
1149 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1151 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1152 let event = Event::PaymentPathFailed {
1155 network_update: None,
1156 rejected_by_dest: false,
1157 all_paths_failed: false,
1160 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1162 invoice_payer.handle_event(&event);
1166 fn scores_successful_channels() {
1167 let event_handled = core::cell::RefCell::new(false);
1168 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
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);
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() })
1183 let logger = TestLogger::new();
1185 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
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()
1191 invoice_payer.handle_event(&event);
1192 let event = Event::PaymentPathSuccessful {
1193 payment_id, payment_hash, path: route.paths[1].clone()
1195 invoice_payer.handle_event(&event);
1201 fn route_for_value(final_value_msat: u64) -> Route {
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
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
1221 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1222 TestRouter::route_for_value(final_value_msat).paths[0].clone()
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());
1232 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1236 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1241 impl<S: Score> Router<S> for TestRouter {
1243 &self, _payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
1244 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1245 ) -> Result<Route, LightningError> {
1247 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1252 struct FailingRouter;
1254 impl<S: Score> Router<S> for FailingRouter {
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 })
1264 expectations: Option<VecDeque<PaymentPath>>,
1269 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1270 Success { path: Vec<RouteHop> },
1280 fn expect(mut self, expectation: PaymentPath) -> Self {
1281 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1287 impl lightning::util::ser::Writeable for TestScorer {
1288 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
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
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);
1303 Some(PaymentPath::Success { path }) => {
1304 panic!("Unexpected successful payment path: {:?}", path)
1306 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
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)
1317 Some(PaymentPath::Success { path }) => {
1318 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1320 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1326 impl Drop for TestScorer {
1327 fn drop(&mut self) {
1328 if std::thread::panicking() {
1332 if let Some(expectations) = &self.expectations {
1333 if !expectations.is_empty() {
1334 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1341 expectations: core::cell::RefCell<VecDeque<Amount>>,
1342 attempts: core::cell::RefCell<usize>,
1343 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1346 #[derive(Clone, Debug, PartialEq, Eq)]
1353 struct OnAttempt(usize);
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()),
1364 fn expect_send(self, value_msat: Amount) -> Self {
1365 self.expectations.borrow_mut().push_back(value_msat);
1369 fn fails_on_attempt(self, attempt: usize) -> Self {
1370 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1371 self.fails_with(failure, OnAttempt(attempt))
1374 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1375 self.fails_with(PaymentSendFailure::PartialFailure {
1377 failed_paths_retry: Some(retry),
1378 payment_id: PaymentId([1; 32]),
1382 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1383 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1387 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1388 let mut attempts = self.attempts.borrow_mut();
1391 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1392 Some(failure) => Err(failure),
1393 None => Ok(PaymentId([1; 32])),
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);
1402 panic!("Unexpected amount: {:?}", actual_value_msats);
1407 impl Drop for TestPayer {
1408 fn drop(&mut self) {
1409 if std::thread::panicking() {
1413 if !self.expectations.borrow().is_empty() {
1414 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
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())
1425 fn first_hops(&self) -> Vec<ChannelDetails> {
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()
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()
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(|_| ())
1452 // *** Full Featured Functional Tests with a Real ChannelManager ***
1453 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1455 impl<S: Score> Router<S> for ManualRouter {
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()
1464 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1465 self.0.borrow_mut().push_back(result);
1468 impl Drop for ManualRouter {
1469 fn drop(&mut self) {
1470 if std::thread::panicking() {
1473 assert!(self.0.borrow_mut().is_empty());
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);
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 {
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(),
1496 cltv_expiry_delta: 100,
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,
1507 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
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()));
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));
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())
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);
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);
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 {
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,
1550 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
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()));
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));
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())
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);