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::scoring::Score;
35 //! # use lightning::routing::network_graph::NodeId;
36 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
37 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
38 //! # use lightning::util::logger::{Logger, Record};
39 //! # use lightning::util::ser::{Writeable, Writer};
40 //! # use lightning_invoice::Invoice;
41 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
42 //! # use secp256k1::key::PublicKey;
43 //! # use std::cell::RefCell;
44 //! # use std::ops::Deref;
46 //! # struct FakeEventProvider {}
47 //! # impl EventsProvider for FakeEventProvider {
48 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
51 //! # struct FakePayer {}
52 //! # impl Payer for FakePayer {
53 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
54 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
55 //! # fn send_payment(
56 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
57 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
58 //! # fn send_spontaneous_payment(
59 //! # &self, route: &Route, payment_preimage: PaymentPreimage
60 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
61 //! # fn retry_payment(
62 //! # &self, route: &Route, payment_id: PaymentId
63 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
66 //! # struct FakeRouter {};
67 //! # impl<S: Score> Router<S> for FakeRouter {
69 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
70 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
71 //! # ) -> Result<Route, LightningError> { unimplemented!() }
74 //! # struct FakeScorer {};
75 //! # impl Writeable for FakeScorer {
76 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); }
78 //! # impl Score for FakeScorer {
79 //! # fn channel_penalty_msat(
80 //! # &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
82 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
85 //! # struct FakeLogger {};
86 //! # impl Logger for FakeLogger {
87 //! # fn log(&self, record: &Record) { unimplemented!() }
91 //! let event_handler = |event: &Event| {
93 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
94 //! Event::PaymentSent { .. } => println!("payment successful"),
98 //! # let payer = FakePayer {};
99 //! # let router = FakeRouter {};
100 //! # let scorer = RefCell::new(FakeScorer {});
101 //! # let logger = FakeLogger {};
102 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
104 //! let invoice = "...";
105 //! let invoice = invoice.parse::<Invoice>().unwrap();
106 //! invoice_payer.pay_invoice(&invoice).unwrap();
108 //! # let event_provider = FakeEventProvider {};
110 //! event_provider.process_pending_events(&invoice_payer);
117 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
118 //! as updates to the network graph or changes to channel scores should be applied prior to
119 //! retries, typically by way of composing [`EventHandler`]s accordingly.
123 use bitcoin_hashes::Hash;
124 use bitcoin_hashes::sha256::Hash as Sha256;
126 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
127 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
128 use lightning::ln::msgs::LightningError;
129 use lightning::routing::scoring::{LockableScore, Score};
130 use lightning::routing::router::{Payee, Route, RouteParameters};
131 use lightning::util::events::{Event, EventHandler};
132 use lightning::util::logger::Logger;
134 use secp256k1::key::PublicKey;
136 use std::collections::hash_map::{self, HashMap};
138 use std::sync::Mutex;
139 use std::time::{Duration, SystemTime};
141 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
142 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
145 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
146 S::Target: for <'a> LockableScore<'a>,
155 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
156 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
157 retry_attempts: RetryAttempts,
160 /// A trait defining behavior of an [`Invoice`] payer.
162 /// Returns the payer's node id.
163 fn node_id(&self) -> PublicKey;
165 /// Returns the payer's channels.
166 fn first_hops(&self) -> Vec<ChannelDetails>;
168 /// Sends a payment over the Lightning Network using the given [`Route`].
170 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
171 ) -> Result<PaymentId, PaymentSendFailure>;
173 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
174 fn send_spontaneous_payment(
175 &self, route: &Route, payment_preimage: PaymentPreimage
176 ) -> Result<PaymentId, PaymentSendFailure>;
178 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
179 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
182 /// A trait defining behavior for routing an [`Invoice`] payment.
183 pub trait Router<S: Score> {
184 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
186 &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
187 first_hops: Option<&[&ChannelDetails]>, scorer: &S
188 ) -> Result<Route, LightningError>;
191 /// Number of attempts to retry payment path failures for an [`Invoice`].
193 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
194 /// payments, if this is less than the total number of paths, we will never even retry all of the
196 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
197 pub struct RetryAttempts(pub usize);
199 /// An error that may occur when making a payment.
200 #[derive(Clone, Debug)]
201 pub enum PaymentError {
202 /// An error resulting from the provided [`Invoice`] or payment hash.
203 Invoice(&'static str),
204 /// An error occurring when finding a route.
205 Routing(LightningError),
206 /// An error occurring when sending a payment.
207 Sending(PaymentSendFailure),
210 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
213 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
214 S::Target: for <'a> LockableScore<'a>,
218 /// Creates an invoice payer that retries failed payment paths.
220 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
221 /// `retry_attempts` has been exceeded for a given [`Invoice`].
223 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
231 payment_cache: Mutex::new(HashMap::new()),
236 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
238 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
239 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
241 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
242 if invoice.amount_milli_satoshis().is_none() {
243 Err(PaymentError::Invoice("amount missing"))
245 self.pay_invoice_using_amount(invoice, None)
249 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
250 /// case a retry is needed.
252 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
253 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
255 pub fn pay_zero_value_invoice(
256 &self, invoice: &Invoice, amount_msats: u64
257 ) -> Result<PaymentId, PaymentError> {
258 if invoice.amount_milli_satoshis().is_some() {
259 Err(PaymentError::Invoice("amount unexpected"))
261 self.pay_invoice_using_amount(invoice, Some(amount_msats))
265 fn pay_invoice_using_amount(
266 &self, invoice: &Invoice, amount_msats: Option<u64>
267 ) -> Result<PaymentId, PaymentError> {
268 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
270 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
271 match self.payment_cache.lock().unwrap().entry(payment_hash) {
272 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
273 hash_map::Entry::Vacant(entry) => entry.insert(0),
276 let payment_secret = Some(invoice.payment_secret().clone());
277 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
278 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
279 .with_route_hints(invoice.route_hints());
280 if let Some(features) = invoice.features() {
281 payee = payee.with_features(features.clone());
283 let params = RouteParameters {
285 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
286 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
289 let send_payment = |route: &Route| {
290 self.payer.send_payment(route, payment_hash, &payment_secret)
292 self.pay_internal(¶ms, payment_hash, send_payment)
293 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
296 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
297 /// case a retry is needed.
299 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
300 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
302 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
303 final_cltv_expiry_delta: u32
304 ) -> Result<PaymentId, PaymentError> {
305 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
306 match self.payment_cache.lock().unwrap().entry(payment_hash) {
307 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
308 hash_map::Entry::Vacant(entry) => entry.insert(0),
311 let params = RouteParameters {
312 payee: Payee::for_keysend(pubkey),
313 final_value_msat: amount_msats,
314 final_cltv_expiry_delta,
317 let send_payment = |route: &Route| {
318 self.payer.send_spontaneous_payment(route, payment_preimage)
320 self.pay_internal(¶ms, payment_hash, send_payment)
321 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
324 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
325 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
326 ) -> Result<PaymentId, PaymentError> {
327 if has_expired(params) {
328 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
329 return Err(PaymentError::Invoice("Invoice expired prior to send"));
332 let payer = self.payer.node_id();
333 let first_hops = self.payer.first_hops();
334 let route = self.router.find_route(
335 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
337 ).map_err(|e| PaymentError::Routing(e))?;
339 match send_payment(&route) {
340 Ok(payment_id) => Ok(payment_id),
342 PaymentSendFailure::ParameterError(_) => Err(e),
343 PaymentSendFailure::PathParameterError(_) => Err(e),
344 PaymentSendFailure::AllFailedRetrySafe(_) => {
345 let mut payment_cache = self.payment_cache.lock().unwrap();
346 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
347 if *retry_count >= self.retry_attempts.0 {
351 std::mem::drop(payment_cache);
352 Ok(self.pay_internal(params, payment_hash, send_payment)?)
355 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
356 if let Some(retry_data) = failed_paths_retry {
357 // Some paths were sent, even if we failed to send the full MPP value our
358 // recipient may misbehave and claim the funds, at which point we have to
359 // consider the payment sent, so return `Ok()` here, ignoring any retry
361 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
364 // This may happen if we send a payment and some paths fail, but
365 // only due to a temporary monitor failure or the like, implying
366 // they're really in-flight, but we haven't sent the initial
367 // HTLC-Add messages yet.
372 }.map_err(|e| PaymentError::Sending(e))
376 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
377 ) -> Result<(), ()> {
378 let max_payment_attempts = self.retry_attempts.0 + 1;
379 let attempts = *self.payment_cache.lock().unwrap()
381 .and_modify(|attempts| *attempts += 1)
384 if attempts >= max_payment_attempts {
385 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
389 if has_expired(params) {
390 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
394 let payer = self.payer.node_id();
395 let first_hops = self.payer.first_hops();
396 let route = self.router.find_route(
397 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
401 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
405 match self.payer.retry_payment(&route.unwrap(), payment_id) {
407 Err(PaymentSendFailure::ParameterError(_)) |
408 Err(PaymentSendFailure::PathParameterError(_)) => {
409 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
412 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
413 self.retry_payment(payment_id, payment_hash, params)
415 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
416 if let Some(retry) = failed_paths_retry {
417 // Always return Ok for the same reason as noted in pay_internal.
418 let _ = self.retry_payment(payment_id, payment_hash, &retry);
425 /// Removes the payment cached by the given payment hash.
427 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
428 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
429 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
430 self.payment_cache.lock().unwrap().remove(payment_hash);
434 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
435 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
438 fn has_expired(params: &RouteParameters) -> bool {
439 if let Some(expiry_time) = params.payee.expiry_time {
440 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
444 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
447 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
448 S::Target: for <'a> LockableScore<'a>,
452 fn handle_event(&self, event: &Event) {
454 Event::PaymentPathFailed {
455 all_paths_failed, payment_id, payment_hash, rejected_by_dest, path,
456 short_channel_id, retry, ..
458 if let Some(short_channel_id) = short_channel_id {
459 let path = path.iter().collect::<Vec<_>>();
460 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
463 if *rejected_by_dest {
464 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
465 } else if payment_id.is_none() {
466 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
467 } else if retry.is_none() {
468 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
469 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
470 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
474 if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); }
476 Event::PaymentSent { payment_hash, .. } => {
477 let mut payment_cache = self.payment_cache.lock().unwrap();
478 let attempts = payment_cache
479 .remove(payment_hash)
480 .map_or(1, |attempts| attempts + 1);
481 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
486 // Delegate to the decorated event handler unless the payment is retried.
487 self.event_handler.handle_event(event)
494 use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
495 use utils::create_invoice_from_channelmanager;
496 use bitcoin_hashes::sha256::Hash as Sha256;
497 use lightning::ln::PaymentPreimage;
498 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
499 use lightning::ln::functional_test_utils::*;
500 use lightning::ln::msgs::{ErrorAction, LightningError};
501 use lightning::routing::network_graph::NodeId;
502 use lightning::routing::router::{Payee, Route, RouteHop};
503 use lightning::util::test_utils::TestLogger;
504 use lightning::util::errors::APIError;
505 use lightning::util::events::{Event, MessageSendEventsProvider};
506 use secp256k1::{SecretKey, PublicKey, Secp256k1};
507 use std::cell::RefCell;
508 use std::collections::VecDeque;
509 use std::time::{SystemTime, Duration};
511 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
512 let payment_hash = Sha256::hash(&payment_preimage.0);
513 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
514 InvoiceBuilder::new(Currency::Bitcoin)
515 .description("test".into())
516 .payment_hash(payment_hash)
517 .payment_secret(PaymentSecret([0; 32]))
519 .min_final_cltv_expiry(144)
520 .amount_milli_satoshis(128)
521 .build_signed(|hash| {
522 Secp256k1::new().sign_recoverable(hash, &private_key)
527 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
528 let payment_hash = Sha256::hash(&payment_preimage.0);
529 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
530 InvoiceBuilder::new(Currency::Bitcoin)
531 .description("test".into())
532 .payment_hash(payment_hash)
533 .payment_secret(PaymentSecret([0; 32]))
535 .min_final_cltv_expiry(144)
536 .build_signed(|hash| {
537 Secp256k1::new().sign_recoverable(hash, &private_key)
542 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
543 let payment_hash = Sha256::hash(&payment_preimage.0);
544 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
545 let timestamp = SystemTime::now()
546 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
548 InvoiceBuilder::new(Currency::Bitcoin)
549 .description("test".into())
550 .payment_hash(payment_hash)
551 .payment_secret(PaymentSecret([0; 32]))
552 .timestamp(timestamp)
553 .min_final_cltv_expiry(144)
554 .amount_milli_satoshis(128)
555 .build_signed(|hash| {
556 Secp256k1::new().sign_recoverable(hash, &private_key)
561 fn pubkey() -> PublicKey {
562 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
566 fn pays_invoice_on_first_attempt() {
567 let event_handled = core::cell::RefCell::new(false);
568 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
570 let payment_preimage = PaymentPreimage([1; 32]);
571 let invoice = invoice(payment_preimage);
572 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
573 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
575 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
576 let router = TestRouter {};
577 let scorer = RefCell::new(TestScorer::new());
578 let logger = TestLogger::new();
580 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
582 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
583 assert_eq!(*payer.attempts.borrow(), 1);
585 invoice_payer.handle_event(&Event::PaymentSent {
586 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
588 assert_eq!(*event_handled.borrow(), true);
589 assert_eq!(*payer.attempts.borrow(), 1);
593 fn pays_invoice_on_retry() {
594 let event_handled = core::cell::RefCell::new(false);
595 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
597 let payment_preimage = PaymentPreimage([1; 32]);
598 let invoice = invoice(payment_preimage);
599 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
600 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
602 let payer = TestPayer::new()
603 .expect_send(Amount::ForInvoice(final_value_msat))
604 .expect_send(Amount::OnRetry(final_value_msat / 2));
605 let router = TestRouter {};
606 let scorer = RefCell::new(TestScorer::new());
607 let logger = TestLogger::new();
609 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
611 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
612 assert_eq!(*payer.attempts.borrow(), 1);
614 let event = Event::PaymentPathFailed {
617 network_update: None,
618 rejected_by_dest: false,
619 all_paths_failed: false,
620 path: TestRouter::path_for_value(final_value_msat),
621 short_channel_id: None,
622 retry: Some(TestRouter::retry_for_invoice(&invoice)),
624 invoice_payer.handle_event(&event);
625 assert_eq!(*event_handled.borrow(), false);
626 assert_eq!(*payer.attempts.borrow(), 2);
628 invoice_payer.handle_event(&Event::PaymentSent {
629 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
631 assert_eq!(*event_handled.borrow(), true);
632 assert_eq!(*payer.attempts.borrow(), 2);
636 fn pays_invoice_on_partial_failure() {
637 let event_handler = |_: &_| { panic!() };
639 let payment_preimage = PaymentPreimage([1; 32]);
640 let invoice = invoice(payment_preimage);
641 let retry = TestRouter::retry_for_invoice(&invoice);
642 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
644 let payer = TestPayer::new()
645 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
646 .fails_with_partial_failure(retry, OnAttempt(2))
647 .expect_send(Amount::ForInvoice(final_value_msat))
648 .expect_send(Amount::OnRetry(final_value_msat / 2))
649 .expect_send(Amount::OnRetry(final_value_msat / 2));
650 let router = TestRouter {};
651 let scorer = RefCell::new(TestScorer::new());
652 let logger = TestLogger::new();
654 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
656 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
660 fn retries_payment_path_for_unknown_payment() {
661 let event_handled = core::cell::RefCell::new(false);
662 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
664 let payment_preimage = PaymentPreimage([1; 32]);
665 let invoice = invoice(payment_preimage);
666 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
667 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
669 let payer = TestPayer::new()
670 .expect_send(Amount::OnRetry(final_value_msat / 2))
671 .expect_send(Amount::OnRetry(final_value_msat / 2));
672 let router = TestRouter {};
673 let scorer = RefCell::new(TestScorer::new());
674 let logger = TestLogger::new();
676 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
678 let payment_id = Some(PaymentId([1; 32]));
679 let event = Event::PaymentPathFailed {
682 network_update: None,
683 rejected_by_dest: false,
684 all_paths_failed: false,
685 path: TestRouter::path_for_value(final_value_msat),
686 short_channel_id: None,
687 retry: Some(TestRouter::retry_for_invoice(&invoice)),
689 invoice_payer.handle_event(&event);
690 assert_eq!(*event_handled.borrow(), false);
691 assert_eq!(*payer.attempts.borrow(), 1);
693 invoice_payer.handle_event(&event);
694 assert_eq!(*event_handled.borrow(), false);
695 assert_eq!(*payer.attempts.borrow(), 2);
697 invoice_payer.handle_event(&Event::PaymentSent {
698 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
700 assert_eq!(*event_handled.borrow(), true);
701 assert_eq!(*payer.attempts.borrow(), 2);
705 fn fails_paying_invoice_after_max_retries() {
706 let event_handled = core::cell::RefCell::new(false);
707 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
709 let payment_preimage = PaymentPreimage([1; 32]);
710 let invoice = invoice(payment_preimage);
711 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
713 let payer = TestPayer::new()
714 .expect_send(Amount::ForInvoice(final_value_msat))
715 .expect_send(Amount::OnRetry(final_value_msat / 2))
716 .expect_send(Amount::OnRetry(final_value_msat / 2));
717 let router = TestRouter {};
718 let scorer = RefCell::new(TestScorer::new());
719 let logger = TestLogger::new();
721 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
723 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
724 assert_eq!(*payer.attempts.borrow(), 1);
726 let event = Event::PaymentPathFailed {
728 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
729 network_update: None,
730 rejected_by_dest: false,
731 all_paths_failed: true,
732 path: TestRouter::path_for_value(final_value_msat),
733 short_channel_id: None,
734 retry: Some(TestRouter::retry_for_invoice(&invoice)),
736 invoice_payer.handle_event(&event);
737 assert_eq!(*event_handled.borrow(), false);
738 assert_eq!(*payer.attempts.borrow(), 2);
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: false,
746 path: TestRouter::path_for_value(final_value_msat / 2),
747 short_channel_id: None,
748 retry: Some(RouteParameters {
749 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
752 invoice_payer.handle_event(&event);
753 assert_eq!(*event_handled.borrow(), false);
754 assert_eq!(*payer.attempts.borrow(), 3);
756 invoice_payer.handle_event(&event);
757 assert_eq!(*event_handled.borrow(), true);
758 assert_eq!(*payer.attempts.borrow(), 3);
762 fn fails_paying_invoice_with_missing_retry_params() {
763 let event_handled = core::cell::RefCell::new(false);
764 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
766 let payment_preimage = PaymentPreimage([1; 32]);
767 let invoice = invoice(payment_preimage);
768 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
770 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
771 let router = TestRouter {};
772 let scorer = RefCell::new(TestScorer::new());
773 let logger = TestLogger::new();
775 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
777 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
778 assert_eq!(*payer.attempts.borrow(), 1);
780 let event = Event::PaymentPathFailed {
782 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
783 network_update: None,
784 rejected_by_dest: false,
785 all_paths_failed: false,
787 short_channel_id: None,
790 invoice_payer.handle_event(&event);
791 assert_eq!(*event_handled.borrow(), true);
792 assert_eq!(*payer.attempts.borrow(), 1);
796 fn fails_paying_invoice_after_expiration() {
797 let event_handled = core::cell::RefCell::new(false);
798 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
800 let payer = TestPayer::new();
801 let router = TestRouter {};
802 let scorer = RefCell::new(TestScorer::new());
803 let logger = TestLogger::new();
805 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
807 let payment_preimage = PaymentPreimage([1; 32]);
808 let invoice = expired_invoice(payment_preimage);
809 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
810 assert_eq!(msg, "Invoice expired prior to send");
811 } else { panic!("Expected Invoice Error"); }
815 fn fails_retrying_invoice_after_expiration() {
816 let event_handled = core::cell::RefCell::new(false);
817 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
819 let payment_preimage = PaymentPreimage([1; 32]);
820 let invoice = invoice(payment_preimage);
821 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
823 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
824 let router = TestRouter {};
825 let scorer = RefCell::new(TestScorer::new());
826 let logger = TestLogger::new();
828 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
830 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
831 assert_eq!(*payer.attempts.borrow(), 1);
833 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
834 retry_data.payee.expiry_time = Some(SystemTime::now()
835 .checked_sub(Duration::from_secs(2)).unwrap()
836 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
837 let event = Event::PaymentPathFailed {
839 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
840 network_update: None,
841 rejected_by_dest: false,
842 all_paths_failed: false,
844 short_channel_id: None,
845 retry: Some(retry_data),
847 invoice_payer.handle_event(&event);
848 assert_eq!(*event_handled.borrow(), true);
849 assert_eq!(*payer.attempts.borrow(), 1);
853 fn fails_paying_invoice_after_retry_error() {
854 let event_handled = core::cell::RefCell::new(false);
855 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
857 let payment_preimage = PaymentPreimage([1; 32]);
858 let invoice = invoice(payment_preimage);
859 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
861 let payer = TestPayer::new()
863 .expect_send(Amount::ForInvoice(final_value_msat))
864 .expect_send(Amount::OnRetry(final_value_msat / 2));
865 let router = TestRouter {};
866 let scorer = RefCell::new(TestScorer::new());
867 let logger = TestLogger::new();
869 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
871 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
872 assert_eq!(*payer.attempts.borrow(), 1);
874 let event = Event::PaymentPathFailed {
876 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
877 network_update: None,
878 rejected_by_dest: false,
879 all_paths_failed: false,
880 path: TestRouter::path_for_value(final_value_msat / 2),
881 short_channel_id: None,
882 retry: Some(TestRouter::retry_for_invoice(&invoice)),
884 invoice_payer.handle_event(&event);
885 assert_eq!(*event_handled.borrow(), true);
886 assert_eq!(*payer.attempts.borrow(), 2);
890 fn fails_paying_invoice_after_rejected_by_payee() {
891 let event_handled = core::cell::RefCell::new(false);
892 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
894 let payment_preimage = PaymentPreimage([1; 32]);
895 let invoice = invoice(payment_preimage);
896 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
898 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
899 let router = TestRouter {};
900 let scorer = RefCell::new(TestScorer::new());
901 let logger = TestLogger::new();
903 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
905 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
906 assert_eq!(*payer.attempts.borrow(), 1);
908 let event = Event::PaymentPathFailed {
910 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
911 network_update: None,
912 rejected_by_dest: true,
913 all_paths_failed: false,
915 short_channel_id: None,
916 retry: Some(TestRouter::retry_for_invoice(&invoice)),
918 invoice_payer.handle_event(&event);
919 assert_eq!(*event_handled.borrow(), true);
920 assert_eq!(*payer.attempts.borrow(), 1);
924 fn fails_repaying_invoice_with_pending_payment() {
925 let event_handled = core::cell::RefCell::new(false);
926 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
928 let payment_preimage = PaymentPreimage([1; 32]);
929 let invoice = invoice(payment_preimage);
930 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
932 let payer = TestPayer::new()
933 .expect_send(Amount::ForInvoice(final_value_msat))
934 .expect_send(Amount::ForInvoice(final_value_msat));
935 let router = TestRouter {};
936 let scorer = RefCell::new(TestScorer::new());
937 let logger = TestLogger::new();
939 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
941 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
943 // Cannot repay an invoice pending payment.
944 match invoice_payer.pay_invoice(&invoice) {
945 Err(PaymentError::Invoice("payment pending")) => {},
946 Err(_) => panic!("unexpected error"),
947 Ok(_) => panic!("expected invoice error"),
950 // Can repay an invoice once cleared from cache.
951 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
952 invoice_payer.remove_cached_payment(&payment_hash);
953 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
955 // Cannot retry paying an invoice if cleared from cache.
956 invoice_payer.remove_cached_payment(&payment_hash);
957 let event = Event::PaymentPathFailed {
960 network_update: None,
961 rejected_by_dest: false,
962 all_paths_failed: false,
964 short_channel_id: None,
965 retry: Some(TestRouter::retry_for_invoice(&invoice)),
967 invoice_payer.handle_event(&event);
968 assert_eq!(*event_handled.borrow(), true);
972 fn fails_paying_invoice_with_routing_errors() {
973 let payer = TestPayer::new();
974 let router = FailingRouter {};
975 let scorer = RefCell::new(TestScorer::new());
976 let logger = TestLogger::new();
978 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
980 let payment_preimage = PaymentPreimage([1; 32]);
981 let invoice = invoice(payment_preimage);
982 match invoice_payer.pay_invoice(&invoice) {
983 Err(PaymentError::Routing(_)) => {},
984 Err(_) => panic!("unexpected error"),
985 Ok(_) => panic!("expected routing error"),
990 fn fails_paying_invoice_with_sending_errors() {
991 let payment_preimage = PaymentPreimage([1; 32]);
992 let invoice = invoice(payment_preimage);
993 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
995 let payer = TestPayer::new()
997 .expect_send(Amount::ForInvoice(final_value_msat));
998 let router = TestRouter {};
999 let scorer = RefCell::new(TestScorer::new());
1000 let logger = TestLogger::new();
1002 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1004 match invoice_payer.pay_invoice(&invoice) {
1005 Err(PaymentError::Sending(_)) => {},
1006 Err(_) => panic!("unexpected error"),
1007 Ok(_) => panic!("expected sending error"),
1012 fn pays_zero_value_invoice_using_amount() {
1013 let event_handled = core::cell::RefCell::new(false);
1014 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1016 let payment_preimage = PaymentPreimage([1; 32]);
1017 let invoice = zero_value_invoice(payment_preimage);
1018 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1019 let final_value_msat = 100;
1021 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1022 let router = TestRouter {};
1023 let scorer = RefCell::new(TestScorer::new());
1024 let logger = TestLogger::new();
1026 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1029 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1030 assert_eq!(*payer.attempts.borrow(), 1);
1032 invoice_payer.handle_event(&Event::PaymentSent {
1033 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1035 assert_eq!(*event_handled.borrow(), true);
1036 assert_eq!(*payer.attempts.borrow(), 1);
1040 fn fails_paying_zero_value_invoice_with_amount() {
1041 let event_handled = core::cell::RefCell::new(false);
1042 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1044 let payer = TestPayer::new();
1045 let router = TestRouter {};
1046 let scorer = RefCell::new(TestScorer::new());
1047 let logger = TestLogger::new();
1049 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1051 let payment_preimage = PaymentPreimage([1; 32]);
1052 let invoice = invoice(payment_preimage);
1054 // Cannot repay an invoice pending payment.
1055 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1056 Err(PaymentError::Invoice("amount unexpected")) => {},
1057 Err(_) => panic!("unexpected error"),
1058 Ok(_) => panic!("expected invoice error"),
1063 fn pays_pubkey_with_amount() {
1064 let event_handled = core::cell::RefCell::new(false);
1065 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1067 let pubkey = pubkey();
1068 let payment_preimage = PaymentPreimage([1; 32]);
1069 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1070 let final_value_msat = 100;
1071 let final_cltv_expiry_delta = 42;
1073 let payer = TestPayer::new()
1074 .expect_send(Amount::Spontaneous(final_value_msat))
1075 .expect_send(Amount::OnRetry(final_value_msat));
1076 let router = TestRouter {};
1077 let scorer = RefCell::new(TestScorer::new());
1078 let logger = TestLogger::new();
1080 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1082 let payment_id = Some(invoice_payer.pay_pubkey(
1083 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1085 assert_eq!(*payer.attempts.borrow(), 1);
1087 let retry = RouteParameters {
1088 payee: Payee::for_keysend(pubkey),
1090 final_cltv_expiry_delta,
1092 let event = Event::PaymentPathFailed {
1095 network_update: None,
1096 rejected_by_dest: false,
1097 all_paths_failed: false,
1099 short_channel_id: None,
1102 invoice_payer.handle_event(&event);
1103 assert_eq!(*event_handled.borrow(), false);
1104 assert_eq!(*payer.attempts.borrow(), 2);
1106 invoice_payer.handle_event(&Event::PaymentSent {
1107 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1109 assert_eq!(*event_handled.borrow(), true);
1110 assert_eq!(*payer.attempts.borrow(), 2);
1114 fn scores_failed_channel() {
1115 let event_handled = core::cell::RefCell::new(false);
1116 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1118 let payment_preimage = PaymentPreimage([1; 32]);
1119 let invoice = invoice(payment_preimage);
1120 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1121 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1122 let path = TestRouter::path_for_value(final_value_msat);
1123 let short_channel_id = Some(path[0].short_channel_id);
1125 // Expect that scorer is given short_channel_id upon handling the event.
1126 let payer = TestPayer::new()
1127 .expect_send(Amount::ForInvoice(final_value_msat))
1128 .expect_send(Amount::OnRetry(final_value_msat / 2));
1129 let router = TestRouter {};
1130 let scorer = RefCell::new(TestScorer::new().expect_channel_failure(short_channel_id.unwrap()));
1131 let logger = TestLogger::new();
1133 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1135 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1136 let event = Event::PaymentPathFailed {
1139 network_update: None,
1140 rejected_by_dest: false,
1141 all_paths_failed: false,
1144 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1146 invoice_payer.handle_event(&event);
1152 fn route_for_value(final_value_msat: u64) -> Route {
1156 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1157 channel_features: ChannelFeatures::empty(),
1158 node_features: NodeFeatures::empty(),
1159 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1162 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1163 channel_features: ChannelFeatures::empty(),
1164 node_features: NodeFeatures::empty(),
1165 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1172 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1173 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1176 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1177 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1178 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1179 .with_route_hints(invoice.route_hints());
1180 if let Some(features) = invoice.features() {
1181 payee = payee.with_features(features.clone());
1183 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1187 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1192 impl<S: Score> Router<S> for TestRouter {
1194 &self, _payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
1195 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1196 ) -> Result<Route, LightningError> {
1198 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1203 struct FailingRouter;
1205 impl<S: Score> Router<S> for FailingRouter {
1207 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1208 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1209 ) -> Result<Route, LightningError> {
1210 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1215 expectations: VecDeque<u64>,
1221 expectations: VecDeque::new(),
1225 fn expect_channel_failure(mut self, short_channel_id: u64) -> Self {
1226 self.expectations.push_back(short_channel_id);
1232 impl lightning::util::ser::Writeable for TestScorer {
1233 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1235 impl Score for TestScorer {
1236 fn channel_penalty_msat(
1237 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
1240 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
1241 if let Some(expected_short_channel_id) = self.expectations.pop_front() {
1242 assert_eq!(short_channel_id, expected_short_channel_id);
1247 impl Drop for TestScorer {
1248 fn drop(&mut self) {
1249 if std::thread::panicking() {
1253 if !self.expectations.is_empty() {
1254 panic!("Unsatisfied channel failure expectations: {:?}", self.expectations);
1260 expectations: core::cell::RefCell<VecDeque<Amount>>,
1261 attempts: core::cell::RefCell<usize>,
1262 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1265 #[derive(Clone, Debug, PartialEq, Eq)]
1272 struct OnAttempt(usize);
1277 expectations: core::cell::RefCell::new(VecDeque::new()),
1278 attempts: core::cell::RefCell::new(0),
1279 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1283 fn expect_send(self, value_msat: Amount) -> Self {
1284 self.expectations.borrow_mut().push_back(value_msat);
1288 fn fails_on_attempt(self, attempt: usize) -> Self {
1289 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1290 self.fails_with(failure, OnAttempt(attempt))
1293 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1294 self.fails_with(PaymentSendFailure::PartialFailure {
1296 failed_paths_retry: Some(retry),
1297 payment_id: PaymentId([1; 32]),
1301 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1302 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1306 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1307 let mut attempts = self.attempts.borrow_mut();
1310 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1311 Some(failure) => Err(failure),
1312 None => Ok(PaymentId([1; 32])),
1316 fn check_value_msats(&self, actual_value_msats: Amount) {
1317 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1318 if let Some(expected_value_msats) = expected_value_msats {
1319 assert_eq!(actual_value_msats, expected_value_msats);
1321 panic!("Unexpected amount: {:?}", actual_value_msats);
1326 impl Drop for TestPayer {
1327 fn drop(&mut self) {
1328 if std::thread::panicking() {
1332 if !self.expectations.borrow().is_empty() {
1333 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1338 impl Payer for TestPayer {
1339 fn node_id(&self) -> PublicKey {
1340 let secp_ctx = Secp256k1::new();
1341 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1344 fn first_hops(&self) -> Vec<ChannelDetails> {
1349 &self, route: &Route, _payment_hash: PaymentHash,
1350 _payment_secret: &Option<PaymentSecret>
1351 ) -> Result<PaymentId, PaymentSendFailure> {
1352 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1353 self.check_attempts()
1356 fn send_spontaneous_payment(
1357 &self, route: &Route, _payment_preimage: PaymentPreimage,
1358 ) -> Result<PaymentId, PaymentSendFailure> {
1359 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1360 self.check_attempts()
1364 &self, route: &Route, _payment_id: PaymentId
1365 ) -> Result<(), PaymentSendFailure> {
1366 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1367 self.check_attempts().map(|_| ())
1371 // *** Full Featured Functional Tests with a Real ChannelManager ***
1372 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1374 impl<S: Score> Router<S> for ManualRouter {
1376 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1377 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1378 ) -> Result<Route, LightningError> {
1379 self.0.borrow_mut().pop_front().unwrap()
1383 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1384 self.0.borrow_mut().push_back(result);
1387 impl Drop for ManualRouter {
1388 fn drop(&mut self) {
1389 if std::thread::panicking() {
1392 assert!(self.0.borrow_mut().is_empty());
1397 fn retry_multi_path_single_failed_payment() {
1398 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1399 let chanmon_cfgs = create_chanmon_cfgs(2);
1400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1404 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1405 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1406 let chans = nodes[0].node.list_usable_channels();
1407 let mut route = Route {
1410 pubkey: nodes[1].node.get_our_node_id(),
1411 node_features: NodeFeatures::known(),
1412 short_channel_id: chans[0].short_channel_id.unwrap(),
1413 channel_features: ChannelFeatures::known(),
1415 cltv_expiry_delta: 100,
1418 pubkey: nodes[1].node.get_our_node_id(),
1419 node_features: NodeFeatures::known(),
1420 short_channel_id: chans[1].short_channel_id.unwrap(),
1421 channel_features: ChannelFeatures::known(),
1422 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1423 cltv_expiry_delta: 100,
1426 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1428 let router = ManualRouter(RefCell::new(VecDeque::new()));
1429 router.expect_find_route(Ok(route.clone()));
1430 // On retry, split the payment across both channels.
1431 route.paths[0][0].fee_msat = 50_000_001;
1432 route.paths[1][0].fee_msat = 50_000_000;
1433 router.expect_find_route(Ok(route.clone()));
1435 let event_handler = |_: &_| { panic!(); };
1436 let scorer = RefCell::new(TestScorer::new());
1437 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1439 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1440 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1442 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1443 assert_eq!(htlc_msgs.len(), 2);
1444 check_added_monitors!(nodes[0], 2);
1448 fn immediate_retry_on_failure() {
1449 // Tests that we can/will retry immediately after a failure
1450 let chanmon_cfgs = create_chanmon_cfgs(2);
1451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1453 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1455 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1456 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1457 let chans = nodes[0].node.list_usable_channels();
1458 let mut route = Route {
1461 pubkey: nodes[1].node.get_our_node_id(),
1462 node_features: NodeFeatures::known(),
1463 short_channel_id: chans[0].short_channel_id.unwrap(),
1464 channel_features: ChannelFeatures::known(),
1465 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1466 cltv_expiry_delta: 100,
1469 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1471 let router = ManualRouter(RefCell::new(VecDeque::new()));
1472 router.expect_find_route(Ok(route.clone()));
1473 // On retry, split the payment across both channels.
1474 route.paths.push(route.paths[0].clone());
1475 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1476 route.paths[0][0].fee_msat = 50_000_000;
1477 route.paths[1][0].fee_msat = 50_000_001;
1478 router.expect_find_route(Ok(route.clone()));
1480 let event_handler = |_: &_| { panic!(); };
1481 let scorer = RefCell::new(TestScorer::new());
1482 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1484 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1485 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1487 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1488 assert_eq!(htlc_msgs.len(), 2);
1489 check_added_monitors!(nodes[0], 2);