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 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.
27 //! # extern crate lightning;
28 //! # extern crate lightning_invoice;
29 //! # extern crate secp256k1;
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;
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_invoice::Invoice;
40 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
41 //! # use secp256k1::key::PublicKey;
42 //! # use std::cell::RefCell;
43 //! # use std::ops::Deref;
45 //! # struct FakeEventProvider {}
46 //! # impl EventsProvider for FakeEventProvider {
47 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
50 //! # struct FakePayer {}
51 //! # impl Payer for FakePayer {
52 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
53 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
54 //! # fn send_payment(
55 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
56 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
57 //! # fn send_spontaneous_payment(
58 //! # &self, route: &Route, payment_preimage: PaymentPreimage
59 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
60 //! # fn retry_payment(
61 //! # &self, route: &Route, payment_id: PaymentId
62 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
65 //! # struct FakeRouter {};
66 //! # impl<S: routing::Score> Router<S> for FakeRouter {
68 //! # &self, payer: &PublicKey, params: &RouteParameters,
69 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
70 //! # ) -> Result<Route, LightningError> { unimplemented!() }
73 //! # struct FakeScorer {};
74 //! # impl routing::Score for FakeScorer {
75 //! # fn channel_penalty_msat(
76 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId
78 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
81 //! # struct FakeLogger {};
82 //! # impl Logger for FakeLogger {
83 //! # fn log(&self, record: &Record) { unimplemented!() }
87 //! let event_handler = |event: &Event| {
89 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
90 //! Event::PaymentSent { .. } => println!("payment successful"),
94 //! # let payer = FakePayer {};
95 //! # let router = FakeRouter {};
96 //! # let scorer = RefCell::new(FakeScorer {});
97 //! # let logger = FakeLogger {};
98 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
100 //! let invoice = "...";
101 //! let invoice = invoice.parse::<Invoice>().unwrap();
102 //! invoice_payer.pay_invoice(&invoice).unwrap();
104 //! # let event_provider = FakeEventProvider {};
106 //! event_provider.process_pending_events(&invoice_payer);
113 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
114 //! as updates to the network graph or changes to channel scores should be applied prior to
115 //! retries, typically by way of composing [`EventHandler`]s accordingly.
119 use bitcoin_hashes::Hash;
120 use bitcoin_hashes::sha256::Hash as Sha256;
122 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
123 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
124 use lightning::ln::msgs::LightningError;
125 use lightning::routing;
126 use lightning::routing::{LockableScore, Score};
127 use lightning::routing::router::{Payee, Route, RouteParameters};
128 use lightning::util::events::{Event, EventHandler};
129 use lightning::util::logger::Logger;
131 use secp256k1::key::PublicKey;
133 use std::collections::hash_map::{self, HashMap};
135 use std::sync::Mutex;
136 use std::time::{Duration, SystemTime};
138 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
139 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
142 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
143 S::Target: for <'a> routing::LockableScore<'a>,
152 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
153 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
154 retry_attempts: RetryAttempts,
157 /// A trait defining behavior of an [`Invoice`] payer.
159 /// Returns the payer's node id.
160 fn node_id(&self) -> PublicKey;
162 /// Returns the payer's channels.
163 fn first_hops(&self) -> Vec<ChannelDetails>;
165 /// Sends a payment over the Lightning Network using the given [`Route`].
167 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
168 ) -> Result<PaymentId, PaymentSendFailure>;
170 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
171 fn send_spontaneous_payment(
172 &self, route: &Route, payment_preimage: PaymentPreimage
173 ) -> Result<PaymentId, PaymentSendFailure>;
175 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
176 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
179 /// A trait defining behavior for routing an [`Invoice`] payment.
180 pub trait Router<S: routing::Score> {
181 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
183 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
185 ) -> Result<Route, LightningError>;
188 /// Number of attempts to retry payment path failures for an [`Invoice`].
190 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
191 /// payments, if this is less than the total number of paths, we will never even retry all of the
193 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
194 pub struct RetryAttempts(pub usize);
196 /// An error that may occur when making a payment.
197 #[derive(Clone, Debug)]
198 pub enum PaymentError {
199 /// An error resulting from the provided [`Invoice`] or payment hash.
200 Invoice(&'static str),
201 /// An error occurring when finding a route.
202 Routing(LightningError),
203 /// An error occurring when sending a payment.
204 Sending(PaymentSendFailure),
207 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
210 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
211 S::Target: for <'a> routing::LockableScore<'a>,
215 /// Creates an invoice payer that retries failed payment paths.
217 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
218 /// `retry_attempts` has been exceeded for a given [`Invoice`].
220 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
228 payment_cache: Mutex::new(HashMap::new()),
233 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
235 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
236 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
238 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
239 if invoice.amount_milli_satoshis().is_none() {
240 Err(PaymentError::Invoice("amount missing"))
242 self.pay_invoice_using_amount(invoice, None)
246 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
247 /// case a retry is needed.
249 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
250 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
252 pub fn pay_zero_value_invoice(
253 &self, invoice: &Invoice, amount_msats: u64
254 ) -> Result<PaymentId, PaymentError> {
255 if invoice.amount_milli_satoshis().is_some() {
256 Err(PaymentError::Invoice("amount unexpected"))
258 self.pay_invoice_using_amount(invoice, Some(amount_msats))
262 fn pay_invoice_using_amount(
263 &self, invoice: &Invoice, amount_msats: Option<u64>
264 ) -> Result<PaymentId, PaymentError> {
265 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
267 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
268 match self.payment_cache.lock().unwrap().entry(payment_hash) {
269 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
270 hash_map::Entry::Vacant(entry) => entry.insert(0),
273 let payment_secret = Some(invoice.payment_secret().clone());
274 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
275 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
276 .with_route_hints(invoice.route_hints());
277 if let Some(features) = invoice.features() {
278 payee = payee.with_features(features.clone());
280 let params = RouteParameters {
282 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
283 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
286 let send_payment = |route: &Route| {
287 self.payer.send_payment(route, payment_hash, &payment_secret)
289 self.pay_internal(¶ms, payment_hash, send_payment)
290 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
293 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
294 /// case a retry is needed.
296 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
297 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
299 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
300 final_cltv_expiry_delta: u32
301 ) -> Result<PaymentId, PaymentError> {
302 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
303 match self.payment_cache.lock().unwrap().entry(payment_hash) {
304 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
305 hash_map::Entry::Vacant(entry) => entry.insert(0),
308 let params = RouteParameters {
309 payee: Payee::for_keysend(pubkey),
310 final_value_msat: amount_msats,
311 final_cltv_expiry_delta,
314 let send_payment = |route: &Route| {
315 self.payer.send_spontaneous_payment(route, payment_preimage)
317 self.pay_internal(¶ms, payment_hash, send_payment)
318 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
321 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
322 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
323 ) -> Result<PaymentId, PaymentError> {
324 if has_expired(params) {
325 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
326 return Err(PaymentError::Invoice("Invoice expired prior to send"));
329 let payer = self.payer.node_id();
330 let first_hops = self.payer.first_hops();
331 let route = self.router.find_route(
334 Some(&first_hops.iter().collect::<Vec<_>>()),
336 ).map_err(|e| PaymentError::Routing(e))?;
338 match send_payment(&route) {
339 Ok(payment_id) => Ok(payment_id),
341 PaymentSendFailure::ParameterError(_) => Err(e),
342 PaymentSendFailure::PathParameterError(_) => Err(e),
343 PaymentSendFailure::AllFailedRetrySafe(_) => {
344 let mut payment_cache = self.payment_cache.lock().unwrap();
345 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
346 if *retry_count >= self.retry_attempts.0 {
350 std::mem::drop(payment_cache);
351 Ok(self.pay_internal(params, payment_hash, send_payment)?)
354 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
355 if let Some(retry_data) = failed_paths_retry {
356 // Some paths were sent, even if we failed to send the full MPP value our
357 // recipient may misbehave and claim the funds, at which point we have to
358 // consider the payment sent, so return `Ok()` here, ignoring any retry
360 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
363 // This may happen if we send a payment and some paths fail, but
364 // only due to a temporary monitor failure or the like, implying
365 // they're really in-flight, but we haven't sent the initial
366 // HTLC-Add messages yet.
371 }.map_err(|e| PaymentError::Sending(e))
375 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
376 ) -> Result<(), ()> {
377 let max_payment_attempts = self.retry_attempts.0 + 1;
378 let attempts = *self.payment_cache.lock().unwrap()
380 .and_modify(|attempts| *attempts += 1)
383 if attempts >= max_payment_attempts {
384 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
388 if has_expired(params) {
389 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
393 let payer = self.payer.node_id();
394 let first_hops = self.payer.first_hops();
395 let route = self.router.find_route(&payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &self.scorer.lock());
397 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
401 match self.payer.retry_payment(&route.unwrap(), payment_id) {
403 Err(PaymentSendFailure::ParameterError(_)) |
404 Err(PaymentSendFailure::PathParameterError(_)) => {
405 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
408 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
409 self.retry_payment(payment_id, payment_hash, params)
411 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
412 if let Some(retry) = failed_paths_retry {
413 // Always return Ok for the same reason as noted in pay_internal.
414 let _ = self.retry_payment(payment_id, payment_hash, &retry);
421 /// Removes the payment cached by the given payment hash.
423 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
424 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
425 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
426 self.payment_cache.lock().unwrap().remove(payment_hash);
430 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
431 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
434 fn has_expired(params: &RouteParameters) -> bool {
435 if let Some(expiry_time) = params.payee.expiry_time {
436 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
440 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
443 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
444 S::Target: for <'a> routing::LockableScore<'a>,
448 fn handle_event(&self, event: &Event) {
450 Event::PaymentPathFailed {
451 all_paths_failed, payment_id, payment_hash, rejected_by_dest, path,
452 short_channel_id, retry, ..
454 if let Some(short_channel_id) = short_channel_id {
455 let path = path.iter().collect::<Vec<_>>();
456 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
459 if *rejected_by_dest {
460 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
461 } else if payment_id.is_none() {
462 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
463 } else if retry.is_none() {
464 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
465 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
466 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
470 if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); }
472 Event::PaymentSent { payment_hash, .. } => {
473 let mut payment_cache = self.payment_cache.lock().unwrap();
474 let attempts = payment_cache
475 .remove(payment_hash)
476 .map_or(1, |attempts| attempts + 1);
477 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
482 // Delegate to the decorated event handler unless the payment is retried.
483 self.event_handler.handle_event(event)
490 use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
491 use utils::create_invoice_from_channelmanager;
492 use bitcoin_hashes::sha256::Hash as Sha256;
493 use lightning::ln::PaymentPreimage;
494 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
495 use lightning::ln::functional_test_utils::*;
496 use lightning::ln::msgs::{ErrorAction, LightningError};
497 use lightning::routing::network_graph::NodeId;
498 use lightning::routing::router::{Payee, Route, RouteHop};
499 use lightning::util::test_utils::TestLogger;
500 use lightning::util::errors::APIError;
501 use lightning::util::events::{Event, MessageSendEventsProvider};
502 use secp256k1::{SecretKey, PublicKey, Secp256k1};
503 use std::cell::RefCell;
504 use std::collections::VecDeque;
505 use std::time::{SystemTime, Duration};
507 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
508 let payment_hash = Sha256::hash(&payment_preimage.0);
509 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
510 InvoiceBuilder::new(Currency::Bitcoin)
511 .description("test".into())
512 .payment_hash(payment_hash)
513 .payment_secret(PaymentSecret([0; 32]))
515 .min_final_cltv_expiry(144)
516 .amount_milli_satoshis(128)
517 .build_signed(|hash| {
518 Secp256k1::new().sign_recoverable(hash, &private_key)
523 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
524 let payment_hash = Sha256::hash(&payment_preimage.0);
525 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
526 InvoiceBuilder::new(Currency::Bitcoin)
527 .description("test".into())
528 .payment_hash(payment_hash)
529 .payment_secret(PaymentSecret([0; 32]))
531 .min_final_cltv_expiry(144)
532 .build_signed(|hash| {
533 Secp256k1::new().sign_recoverable(hash, &private_key)
538 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
539 let payment_hash = Sha256::hash(&payment_preimage.0);
540 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
541 let timestamp = SystemTime::now()
542 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
544 InvoiceBuilder::new(Currency::Bitcoin)
545 .description("test".into())
546 .payment_hash(payment_hash)
547 .payment_secret(PaymentSecret([0; 32]))
548 .timestamp(timestamp)
549 .min_final_cltv_expiry(144)
550 .amount_milli_satoshis(128)
551 .build_signed(|hash| {
552 Secp256k1::new().sign_recoverable(hash, &private_key)
557 fn pubkey() -> PublicKey {
558 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
562 fn pays_invoice_on_first_attempt() {
563 let event_handled = core::cell::RefCell::new(false);
564 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
566 let payment_preimage = PaymentPreimage([1; 32]);
567 let invoice = invoice(payment_preimage);
568 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
569 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
571 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
572 let router = TestRouter {};
573 let scorer = RefCell::new(TestScorer::new());
574 let logger = TestLogger::new();
576 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
578 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
579 assert_eq!(*payer.attempts.borrow(), 1);
581 invoice_payer.handle_event(&Event::PaymentSent {
582 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
584 assert_eq!(*event_handled.borrow(), true);
585 assert_eq!(*payer.attempts.borrow(), 1);
589 fn pays_invoice_on_retry() {
590 let event_handled = core::cell::RefCell::new(false);
591 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
593 let payment_preimage = PaymentPreimage([1; 32]);
594 let invoice = invoice(payment_preimage);
595 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
596 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
598 let payer = TestPayer::new()
599 .expect_send(Amount::ForInvoice(final_value_msat))
600 .expect_send(Amount::OnRetry(final_value_msat / 2));
601 let router = TestRouter {};
602 let scorer = RefCell::new(TestScorer::new());
603 let logger = TestLogger::new();
605 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
607 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
608 assert_eq!(*payer.attempts.borrow(), 1);
610 let event = Event::PaymentPathFailed {
613 network_update: None,
614 rejected_by_dest: false,
615 all_paths_failed: false,
616 path: TestRouter::path_for_value(final_value_msat),
617 short_channel_id: None,
618 retry: Some(TestRouter::retry_for_invoice(&invoice)),
620 invoice_payer.handle_event(&event);
621 assert_eq!(*event_handled.borrow(), false);
622 assert_eq!(*payer.attempts.borrow(), 2);
624 invoice_payer.handle_event(&Event::PaymentSent {
625 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
627 assert_eq!(*event_handled.borrow(), true);
628 assert_eq!(*payer.attempts.borrow(), 2);
632 fn retries_payment_path_for_unknown_payment() {
633 let event_handled = core::cell::RefCell::new(false);
634 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
636 let payment_preimage = PaymentPreimage([1; 32]);
637 let invoice = invoice(payment_preimage);
638 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
639 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
641 let payer = TestPayer::new()
642 .expect_send(Amount::OnRetry(final_value_msat / 2))
643 .expect_send(Amount::OnRetry(final_value_msat / 2));
644 let router = TestRouter {};
645 let scorer = RefCell::new(TestScorer::new());
646 let logger = TestLogger::new();
648 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
650 let payment_id = Some(PaymentId([1; 32]));
651 let event = Event::PaymentPathFailed {
654 network_update: None,
655 rejected_by_dest: false,
656 all_paths_failed: false,
657 path: TestRouter::path_for_value(final_value_msat),
658 short_channel_id: None,
659 retry: Some(TestRouter::retry_for_invoice(&invoice)),
661 invoice_payer.handle_event(&event);
662 assert_eq!(*event_handled.borrow(), false);
663 assert_eq!(*payer.attempts.borrow(), 1);
665 invoice_payer.handle_event(&event);
666 assert_eq!(*event_handled.borrow(), false);
667 assert_eq!(*payer.attempts.borrow(), 2);
669 invoice_payer.handle_event(&Event::PaymentSent {
670 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
672 assert_eq!(*event_handled.borrow(), true);
673 assert_eq!(*payer.attempts.borrow(), 2);
677 fn fails_paying_invoice_after_max_retries() {
678 let event_handled = core::cell::RefCell::new(false);
679 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
681 let payment_preimage = PaymentPreimage([1; 32]);
682 let invoice = invoice(payment_preimage);
683 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
685 let payer = TestPayer::new()
686 .expect_send(Amount::ForInvoice(final_value_msat))
687 .expect_send(Amount::OnRetry(final_value_msat / 2))
688 .expect_send(Amount::OnRetry(final_value_msat / 2));
689 let router = TestRouter {};
690 let scorer = RefCell::new(TestScorer::new());
691 let logger = TestLogger::new();
693 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
695 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
696 assert_eq!(*payer.attempts.borrow(), 1);
698 let event = Event::PaymentPathFailed {
700 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
701 network_update: None,
702 rejected_by_dest: false,
703 all_paths_failed: true,
704 path: TestRouter::path_for_value(final_value_msat),
705 short_channel_id: None,
706 retry: Some(TestRouter::retry_for_invoice(&invoice)),
708 invoice_payer.handle_event(&event);
709 assert_eq!(*event_handled.borrow(), false);
710 assert_eq!(*payer.attempts.borrow(), 2);
712 let event = Event::PaymentPathFailed {
714 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
715 network_update: None,
716 rejected_by_dest: false,
717 all_paths_failed: false,
718 path: TestRouter::path_for_value(final_value_msat / 2),
719 short_channel_id: None,
720 retry: Some(RouteParameters {
721 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
724 invoice_payer.handle_event(&event);
725 assert_eq!(*event_handled.borrow(), false);
726 assert_eq!(*payer.attempts.borrow(), 3);
728 invoice_payer.handle_event(&event);
729 assert_eq!(*event_handled.borrow(), true);
730 assert_eq!(*payer.attempts.borrow(), 3);
734 fn fails_paying_invoice_with_missing_retry_params() {
735 let event_handled = core::cell::RefCell::new(false);
736 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
738 let payment_preimage = PaymentPreimage([1; 32]);
739 let invoice = invoice(payment_preimage);
740 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
742 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
743 let router = TestRouter {};
744 let scorer = RefCell::new(TestScorer::new());
745 let logger = TestLogger::new();
747 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
749 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
750 assert_eq!(*payer.attempts.borrow(), 1);
752 let event = Event::PaymentPathFailed {
754 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
755 network_update: None,
756 rejected_by_dest: false,
757 all_paths_failed: false,
759 short_channel_id: None,
762 invoice_payer.handle_event(&event);
763 assert_eq!(*event_handled.borrow(), true);
764 assert_eq!(*payer.attempts.borrow(), 1);
768 fn fails_paying_invoice_after_expiration() {
769 let event_handled = core::cell::RefCell::new(false);
770 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
772 let payer = TestPayer::new();
773 let router = TestRouter {};
774 let scorer = RefCell::new(TestScorer::new());
775 let logger = TestLogger::new();
777 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
779 let payment_preimage = PaymentPreimage([1; 32]);
780 let invoice = expired_invoice(payment_preimage);
781 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
782 assert_eq!(msg, "Invoice expired prior to send");
783 } else { panic!("Expected Invoice Error"); }
787 fn fails_retrying_invoice_after_expiration() {
788 let event_handled = core::cell::RefCell::new(false);
789 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
791 let payment_preimage = PaymentPreimage([1; 32]);
792 let invoice = invoice(payment_preimage);
793 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
795 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
796 let router = TestRouter {};
797 let scorer = RefCell::new(TestScorer::new());
798 let logger = TestLogger::new();
800 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
802 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
803 assert_eq!(*payer.attempts.borrow(), 1);
805 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
806 retry_data.payee.expiry_time = Some(SystemTime::now()
807 .checked_sub(Duration::from_secs(2)).unwrap()
808 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
809 let event = Event::PaymentPathFailed {
811 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
812 network_update: None,
813 rejected_by_dest: false,
814 all_paths_failed: false,
816 short_channel_id: None,
817 retry: Some(retry_data),
819 invoice_payer.handle_event(&event);
820 assert_eq!(*event_handled.borrow(), true);
821 assert_eq!(*payer.attempts.borrow(), 1);
825 fn fails_paying_invoice_after_retry_error() {
826 let event_handled = core::cell::RefCell::new(false);
827 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
829 let payment_preimage = PaymentPreimage([1; 32]);
830 let invoice = invoice(payment_preimage);
831 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
833 let payer = TestPayer::new()
835 .expect_send(Amount::ForInvoice(final_value_msat))
836 .expect_send(Amount::OnRetry(final_value_msat / 2));
837 let router = TestRouter {};
838 let scorer = RefCell::new(TestScorer::new());
839 let logger = TestLogger::new();
841 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
843 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
844 assert_eq!(*payer.attempts.borrow(), 1);
846 let event = Event::PaymentPathFailed {
848 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
849 network_update: None,
850 rejected_by_dest: false,
851 all_paths_failed: false,
852 path: TestRouter::path_for_value(final_value_msat / 2),
853 short_channel_id: None,
854 retry: Some(TestRouter::retry_for_invoice(&invoice)),
856 invoice_payer.handle_event(&event);
857 assert_eq!(*event_handled.borrow(), true);
858 assert_eq!(*payer.attempts.borrow(), 2);
862 fn fails_paying_invoice_after_rejected_by_payee() {
863 let event_handled = core::cell::RefCell::new(false);
864 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
866 let payment_preimage = PaymentPreimage([1; 32]);
867 let invoice = invoice(payment_preimage);
868 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
870 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
871 let router = TestRouter {};
872 let scorer = RefCell::new(TestScorer::new());
873 let logger = TestLogger::new();
875 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
877 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
878 assert_eq!(*payer.attempts.borrow(), 1);
880 let event = Event::PaymentPathFailed {
882 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
883 network_update: None,
884 rejected_by_dest: true,
885 all_paths_failed: false,
887 short_channel_id: None,
888 retry: Some(TestRouter::retry_for_invoice(&invoice)),
890 invoice_payer.handle_event(&event);
891 assert_eq!(*event_handled.borrow(), true);
892 assert_eq!(*payer.attempts.borrow(), 1);
896 fn fails_repaying_invoice_with_pending_payment() {
897 let event_handled = core::cell::RefCell::new(false);
898 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
900 let payment_preimage = PaymentPreimage([1; 32]);
901 let invoice = invoice(payment_preimage);
902 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
904 let payer = TestPayer::new()
905 .expect_send(Amount::ForInvoice(final_value_msat))
906 .expect_send(Amount::ForInvoice(final_value_msat));
907 let router = TestRouter {};
908 let scorer = RefCell::new(TestScorer::new());
909 let logger = TestLogger::new();
911 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
913 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
915 // Cannot repay an invoice pending payment.
916 match invoice_payer.pay_invoice(&invoice) {
917 Err(PaymentError::Invoice("payment pending")) => {},
918 Err(_) => panic!("unexpected error"),
919 Ok(_) => panic!("expected invoice error"),
922 // Can repay an invoice once cleared from cache.
923 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
924 invoice_payer.remove_cached_payment(&payment_hash);
925 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
927 // Cannot retry paying an invoice if cleared from cache.
928 invoice_payer.remove_cached_payment(&payment_hash);
929 let event = Event::PaymentPathFailed {
932 network_update: None,
933 rejected_by_dest: false,
934 all_paths_failed: false,
936 short_channel_id: None,
937 retry: Some(TestRouter::retry_for_invoice(&invoice)),
939 invoice_payer.handle_event(&event);
940 assert_eq!(*event_handled.borrow(), true);
944 fn fails_paying_invoice_with_routing_errors() {
945 let payer = TestPayer::new();
946 let router = FailingRouter {};
947 let scorer = RefCell::new(TestScorer::new());
948 let logger = TestLogger::new();
950 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
952 let payment_preimage = PaymentPreimage([1; 32]);
953 let invoice = invoice(payment_preimage);
954 match invoice_payer.pay_invoice(&invoice) {
955 Err(PaymentError::Routing(_)) => {},
956 Err(_) => panic!("unexpected error"),
957 Ok(_) => panic!("expected routing error"),
962 fn fails_paying_invoice_with_sending_errors() {
963 let payment_preimage = PaymentPreimage([1; 32]);
964 let invoice = invoice(payment_preimage);
965 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
967 let payer = TestPayer::new()
969 .expect_send(Amount::ForInvoice(final_value_msat));
970 let router = TestRouter {};
971 let scorer = RefCell::new(TestScorer::new());
972 let logger = TestLogger::new();
974 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
976 match invoice_payer.pay_invoice(&invoice) {
977 Err(PaymentError::Sending(_)) => {},
978 Err(_) => panic!("unexpected error"),
979 Ok(_) => panic!("expected sending error"),
984 fn pays_zero_value_invoice_using_amount() {
985 let event_handled = core::cell::RefCell::new(false);
986 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
988 let payment_preimage = PaymentPreimage([1; 32]);
989 let invoice = zero_value_invoice(payment_preimage);
990 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
991 let final_value_msat = 100;
993 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
994 let router = TestRouter {};
995 let scorer = RefCell::new(TestScorer::new());
996 let logger = TestLogger::new();
998 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1001 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1002 assert_eq!(*payer.attempts.borrow(), 1);
1004 invoice_payer.handle_event(&Event::PaymentSent {
1005 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1007 assert_eq!(*event_handled.borrow(), true);
1008 assert_eq!(*payer.attempts.borrow(), 1);
1012 fn fails_paying_zero_value_invoice_with_amount() {
1013 let event_handled = core::cell::RefCell::new(false);
1014 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1016 let payer = TestPayer::new();
1017 let router = TestRouter {};
1018 let scorer = RefCell::new(TestScorer::new());
1019 let logger = TestLogger::new();
1021 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1023 let payment_preimage = PaymentPreimage([1; 32]);
1024 let invoice = invoice(payment_preimage);
1026 // Cannot repay an invoice pending payment.
1027 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1028 Err(PaymentError::Invoice("amount unexpected")) => {},
1029 Err(_) => panic!("unexpected error"),
1030 Ok(_) => panic!("expected invoice error"),
1035 fn pays_pubkey_with_amount() {
1036 let event_handled = core::cell::RefCell::new(false);
1037 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1039 let pubkey = pubkey();
1040 let payment_preimage = PaymentPreimage([1; 32]);
1041 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1042 let final_value_msat = 100;
1043 let final_cltv_expiry_delta = 42;
1045 let payer = TestPayer::new()
1046 .expect_send(Amount::Spontaneous(final_value_msat))
1047 .expect_send(Amount::OnRetry(final_value_msat));
1048 let router = TestRouter {};
1049 let scorer = RefCell::new(TestScorer::new());
1050 let logger = TestLogger::new();
1052 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1054 let payment_id = Some(invoice_payer.pay_pubkey(
1055 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1057 assert_eq!(*payer.attempts.borrow(), 1);
1059 let retry = RouteParameters {
1060 payee: Payee::for_keysend(pubkey),
1062 final_cltv_expiry_delta,
1064 let event = Event::PaymentPathFailed {
1067 network_update: None,
1068 rejected_by_dest: false,
1069 all_paths_failed: false,
1071 short_channel_id: None,
1074 invoice_payer.handle_event(&event);
1075 assert_eq!(*event_handled.borrow(), false);
1076 assert_eq!(*payer.attempts.borrow(), 2);
1078 invoice_payer.handle_event(&Event::PaymentSent {
1079 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1081 assert_eq!(*event_handled.borrow(), true);
1082 assert_eq!(*payer.attempts.borrow(), 2);
1086 fn scores_failed_channel() {
1087 let event_handled = core::cell::RefCell::new(false);
1088 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1090 let payment_preimage = PaymentPreimage([1; 32]);
1091 let invoice = invoice(payment_preimage);
1092 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1093 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1094 let path = TestRouter::path_for_value(final_value_msat);
1095 let short_channel_id = Some(path[0].short_channel_id);
1097 // Expect that scorer is given short_channel_id upon handling the event.
1098 let payer = TestPayer::new()
1099 .expect_send(Amount::ForInvoice(final_value_msat))
1100 .expect_send(Amount::OnRetry(final_value_msat / 2));
1101 let router = TestRouter {};
1102 let scorer = RefCell::new(TestScorer::new().expect_channel_failure(short_channel_id.unwrap()));
1103 let logger = TestLogger::new();
1105 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1107 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1108 let event = Event::PaymentPathFailed {
1111 network_update: None,
1112 rejected_by_dest: false,
1113 all_paths_failed: false,
1116 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1118 invoice_payer.handle_event(&event);
1124 fn route_for_value(final_value_msat: u64) -> Route {
1128 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1129 channel_features: ChannelFeatures::empty(),
1130 node_features: NodeFeatures::empty(),
1131 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1134 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1135 channel_features: ChannelFeatures::empty(),
1136 node_features: NodeFeatures::empty(),
1137 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1144 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1145 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1148 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1149 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1150 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1151 .with_route_hints(invoice.route_hints());
1152 if let Some(features) = invoice.features() {
1153 payee = payee.with_features(features.clone());
1155 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1159 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1164 impl<S: routing::Score> Router<S> for TestRouter {
1168 params: &RouteParameters,
1169 _first_hops: Option<&[&ChannelDetails]>,
1171 ) -> Result<Route, LightningError> {
1173 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1178 struct FailingRouter;
1180 impl<S: routing::Score> Router<S> for FailingRouter {
1184 _params: &RouteParameters,
1185 _first_hops: Option<&[&ChannelDetails]>,
1187 ) -> Result<Route, LightningError> {
1188 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1193 expectations: VecDeque<u64>,
1199 expectations: VecDeque::new(),
1203 fn expect_channel_failure(mut self, short_channel_id: u64) -> Self {
1204 self.expectations.push_back(short_channel_id);
1209 impl routing::Score for TestScorer {
1210 fn channel_penalty_msat(
1211 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId
1214 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
1215 if let Some(expected_short_channel_id) = self.expectations.pop_front() {
1216 assert_eq!(short_channel_id, expected_short_channel_id);
1221 impl Drop for TestScorer {
1222 fn drop(&mut self) {
1223 if std::thread::panicking() {
1227 if !self.expectations.is_empty() {
1228 panic!("Unsatisfied channel failure expectations: {:?}", self.expectations);
1234 expectations: core::cell::RefCell<VecDeque<Amount>>,
1235 attempts: core::cell::RefCell<usize>,
1236 failing_on_attempt: Option<usize>,
1239 #[derive(Clone, Debug, PartialEq, Eq)]
1249 expectations: core::cell::RefCell::new(VecDeque::new()),
1250 attempts: core::cell::RefCell::new(0),
1251 failing_on_attempt: None,
1255 fn expect_send(self, value_msat: Amount) -> Self {
1256 self.expectations.borrow_mut().push_back(value_msat);
1260 fn fails_on_attempt(self, attempt: usize) -> Self {
1262 expectations: core::cell::RefCell::new(self.expectations.borrow().clone()),
1263 attempts: core::cell::RefCell::new(0),
1264 failing_on_attempt: Some(attempt),
1268 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1269 let mut attempts = self.attempts.borrow_mut();
1271 match self.failing_on_attempt {
1272 None => Ok(PaymentId([1; 32])),
1273 Some(attempt) if attempt != *attempts => Ok(PaymentId([1; 32])),
1274 Some(_) => Err(PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed)),
1278 fn check_value_msats(&self, actual_value_msats: Amount) {
1279 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1280 if let Some(expected_value_msats) = expected_value_msats {
1281 assert_eq!(actual_value_msats, expected_value_msats);
1286 impl Drop for TestPayer {
1287 fn drop(&mut self) {
1288 if std::thread::panicking() {
1292 if !self.expectations.borrow().is_empty() {
1293 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1298 impl Payer for TestPayer {
1299 fn node_id(&self) -> PublicKey {
1300 let secp_ctx = Secp256k1::new();
1301 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1304 fn first_hops(&self) -> Vec<ChannelDetails> {
1309 &self, route: &Route, _payment_hash: PaymentHash,
1310 _payment_secret: &Option<PaymentSecret>
1311 ) -> Result<PaymentId, PaymentSendFailure> {
1312 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1313 self.check_attempts()
1316 fn send_spontaneous_payment(
1317 &self, route: &Route, _payment_preimage: PaymentPreimage,
1318 ) -> Result<PaymentId, PaymentSendFailure> {
1319 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1320 self.check_attempts()
1324 &self, route: &Route, _payment_id: PaymentId
1325 ) -> Result<(), PaymentSendFailure> {
1326 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1327 self.check_attempts().map(|_| ())
1331 // *** Full Featured Functional Tests with a Real ChannelManager ***
1332 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1334 impl<S: routing::Score> Router<S> for ManualRouter {
1335 fn find_route(&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, _scorer: &S)
1336 -> Result<Route, LightningError> {
1337 self.0.borrow_mut().pop_front().unwrap()
1341 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1342 self.0.borrow_mut().push_back(result);
1345 impl Drop for ManualRouter {
1346 fn drop(&mut self) {
1347 if std::thread::panicking() {
1350 assert!(self.0.borrow_mut().is_empty());
1355 fn retry_multi_path_single_failed_payment() {
1356 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1357 let chanmon_cfgs = create_chanmon_cfgs(2);
1358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1360 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1362 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1363 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1364 let chans = nodes[0].node.list_usable_channels();
1365 let mut route = Route {
1368 pubkey: nodes[1].node.get_our_node_id(),
1369 node_features: NodeFeatures::known(),
1370 short_channel_id: chans[0].short_channel_id.unwrap(),
1371 channel_features: ChannelFeatures::known(),
1373 cltv_expiry_delta: 100,
1376 pubkey: nodes[1].node.get_our_node_id(),
1377 node_features: NodeFeatures::known(),
1378 short_channel_id: chans[1].short_channel_id.unwrap(),
1379 channel_features: ChannelFeatures::known(),
1380 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1381 cltv_expiry_delta: 100,
1384 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1386 let router = ManualRouter(RefCell::new(VecDeque::new()));
1387 router.expect_find_route(Ok(route.clone()));
1388 // On retry, split the payment across both channels.
1389 route.paths[0][0].fee_msat = 50_000_001;
1390 route.paths[1][0].fee_msat = 50_000_000;
1391 router.expect_find_route(Ok(route.clone()));
1393 let event_handler = |_: &_| { panic!(); };
1394 let scorer = RefCell::new(TestScorer::new());
1395 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1397 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1398 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1400 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1401 assert_eq!(htlc_msgs.len(), 2);
1402 check_added_monitors!(nodes[0], 2);
1406 fn immediate_retry_on_failure() {
1407 // Tests that we can/will retry immediately after a failure
1408 let chanmon_cfgs = create_chanmon_cfgs(2);
1409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1411 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1413 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1414 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1415 let chans = nodes[0].node.list_usable_channels();
1416 let mut route = Route {
1419 pubkey: nodes[1].node.get_our_node_id(),
1420 node_features: NodeFeatures::known(),
1421 short_channel_id: chans[0].short_channel_id.unwrap(),
1422 channel_features: ChannelFeatures::known(),
1423 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1424 cltv_expiry_delta: 100,
1427 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1429 let router = ManualRouter(RefCell::new(VecDeque::new()));
1430 router.expect_find_route(Ok(route.clone()));
1431 // On retry, split the payment across both channels.
1432 route.paths.push(route.paths[0].clone());
1433 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1434 route.paths[0][0].fee_msat = 50_000_000;
1435 route.paths[1][0].fee_msat = 50_000_001;
1436 router.expect_find_route(Ok(route.clone()));
1438 let event_handler = |_: &_| { panic!(); };
1439 let scorer = RefCell::new(TestScorer::new());
1440 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1442 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1443 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1445 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1446 assert_eq!(htlc_msgs.len(), 2);
1447 check_added_monitors!(nodes[0], 2);