1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
19 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
20 //! [`Event::PaymentPathSuccessful`] events, respectively.
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
35 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
36 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
37 //! # use lightning::ln::msgs::LightningError;
38 //! # use lightning::routing::scoring::Score;
39 //! # use lightning::routing::network_graph::NodeId;
40 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
41 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
42 //! # use lightning::util::logger::{Logger, Record};
43 //! # use lightning::util::ser::{Writeable, Writer};
44 //! # use lightning_invoice::Invoice;
45 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
46 //! # use secp256k1::key::PublicKey;
47 //! # use std::cell::RefCell;
48 //! # use std::ops::Deref;
50 //! # struct FakeEventProvider {}
51 //! # impl EventsProvider for FakeEventProvider {
52 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
55 //! # struct FakePayer {}
56 //! # impl Payer for FakePayer {
57 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
58 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
59 //! # fn send_payment(
60 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
61 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
62 //! # fn send_spontaneous_payment(
63 //! # &self, route: &Route, payment_preimage: PaymentPreimage
64 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
65 //! # fn retry_payment(
66 //! # &self, route: &Route, payment_id: PaymentId
67 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
68 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
71 //! # struct FakeRouter {}
72 //! # impl<S: Score> Router<S> for FakeRouter {
74 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
75 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
76 //! # ) -> Result<Route, LightningError> { unimplemented!() }
79 //! # struct FakeScorer {}
80 //! # impl Writeable for FakeScorer {
81 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), std::io::Error> { unimplemented!(); }
83 //! # impl Score for FakeScorer {
84 //! # fn channel_penalty_msat(
85 //! # &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
87 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
88 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
91 //! # struct FakeLogger {}
92 //! # impl Logger for FakeLogger {
93 //! # fn log(&self, record: &Record) { unimplemented!() }
97 //! let event_handler = |event: &Event| {
99 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
100 //! Event::PaymentSent { .. } => println!("payment successful"),
104 //! # let payer = FakePayer {};
105 //! # let router = FakeRouter {};
106 //! # let scorer = RefCell::new(FakeScorer {});
107 //! # let logger = FakeLogger {};
108 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
110 //! let invoice = "...";
111 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
112 //! invoice_payer.pay_invoice(&invoice).unwrap();
114 //! # let event_provider = FakeEventProvider {};
116 //! event_provider.process_pending_events(&invoice_payer);
124 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
125 //! as updates to the network graph or changes to channel scores should be applied prior to
126 //! retries, typically by way of composing [`EventHandler`]s accordingly.
130 use bitcoin_hashes::Hash;
131 use bitcoin_hashes::sha256::Hash as Sha256;
133 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
134 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
135 use lightning::ln::msgs::LightningError;
136 use lightning::routing::scoring::{LockableScore, Score};
137 use lightning::routing::router::{Payee, Route, RouteParameters};
138 use lightning::util::events::{Event, EventHandler};
139 use lightning::util::logger::Logger;
141 use secp256k1::key::PublicKey;
143 use std::collections::hash_map::{self, HashMap};
145 use std::sync::Mutex;
146 use std::time::{Duration, SystemTime};
148 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
150 /// See [module-level documentation] for details.
152 /// [module-level documentation]: crate::payment
153 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
156 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
157 S::Target: for <'a> LockableScore<'a>,
166 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
167 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
168 retry_attempts: RetryAttempts,
171 /// A trait defining behavior of an [`Invoice`] payer.
173 /// Returns the payer's node id.
174 fn node_id(&self) -> PublicKey;
176 /// Returns the payer's channels.
177 fn first_hops(&self) -> Vec<ChannelDetails>;
179 /// Sends a payment over the Lightning Network using the given [`Route`].
181 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
182 ) -> Result<PaymentId, PaymentSendFailure>;
184 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
185 fn send_spontaneous_payment(
186 &self, route: &Route, payment_preimage: PaymentPreimage
187 ) -> Result<PaymentId, PaymentSendFailure>;
189 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
190 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
192 /// Signals that no further retries for the given payment will occur.
193 fn abandon_payment(&self, payment_id: PaymentId);
196 /// A trait defining behavior for routing an [`Invoice`] payment.
197 pub trait Router<S: Score> {
198 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
200 &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
201 first_hops: Option<&[&ChannelDetails]>, scorer: &S
202 ) -> Result<Route, LightningError>;
205 /// Number of attempts to retry payment path failures for an [`Invoice`].
207 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
208 /// payments, if this is less than the total number of paths, we will never even retry all of the
210 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
211 pub struct RetryAttempts(pub usize);
213 /// An error that may occur when making a payment.
214 #[derive(Clone, Debug)]
215 pub enum PaymentError {
216 /// An error resulting from the provided [`Invoice`] or payment hash.
217 Invoice(&'static str),
218 /// An error occurring when finding a route.
219 Routing(LightningError),
220 /// An error occurring when sending a payment.
221 Sending(PaymentSendFailure),
224 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
227 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
228 S::Target: for <'a> LockableScore<'a>,
232 /// Creates an invoice payer that retries failed payment paths.
234 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
235 /// `retry_attempts` has been exceeded for a given [`Invoice`].
237 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
245 payment_cache: Mutex::new(HashMap::new()),
250 /// Pays the given [`Invoice`], caching it for later use in 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_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
256 if invoice.amount_milli_satoshis().is_none() {
257 Err(PaymentError::Invoice("amount missing"))
259 self.pay_invoice_using_amount(invoice, None)
263 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
264 /// case a retry is needed.
266 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
267 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
269 pub fn pay_zero_value_invoice(
270 &self, invoice: &Invoice, amount_msats: u64
271 ) -> Result<PaymentId, PaymentError> {
272 if invoice.amount_milli_satoshis().is_some() {
273 Err(PaymentError::Invoice("amount unexpected"))
275 self.pay_invoice_using_amount(invoice, Some(amount_msats))
279 fn pay_invoice_using_amount(
280 &self, invoice: &Invoice, amount_msats: Option<u64>
281 ) -> Result<PaymentId, PaymentError> {
282 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
284 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
285 match self.payment_cache.lock().unwrap().entry(payment_hash) {
286 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
287 hash_map::Entry::Vacant(entry) => entry.insert(0),
290 let payment_secret = Some(invoice.payment_secret().clone());
291 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
292 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
293 .with_route_hints(invoice.route_hints());
294 if let Some(features) = invoice.features() {
295 payee = payee.with_features(features.clone());
297 let params = RouteParameters {
299 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
300 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
303 let send_payment = |route: &Route| {
304 self.payer.send_payment(route, payment_hash, &payment_secret)
306 self.pay_internal(¶ms, payment_hash, send_payment)
307 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
310 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
311 /// case a retry is needed.
313 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
314 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
316 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
317 final_cltv_expiry_delta: u32
318 ) -> Result<PaymentId, PaymentError> {
319 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
320 match self.payment_cache.lock().unwrap().entry(payment_hash) {
321 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
322 hash_map::Entry::Vacant(entry) => entry.insert(0),
325 let params = RouteParameters {
326 payee: Payee::for_keysend(pubkey),
327 final_value_msat: amount_msats,
328 final_cltv_expiry_delta,
331 let send_payment = |route: &Route| {
332 self.payer.send_spontaneous_payment(route, payment_preimage)
334 self.pay_internal(¶ms, payment_hash, send_payment)
335 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
338 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
339 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
340 ) -> Result<PaymentId, PaymentError> {
341 if has_expired(params) {
342 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
343 return Err(PaymentError::Invoice("Invoice expired prior to send"));
346 let payer = self.payer.node_id();
347 let first_hops = self.payer.first_hops();
348 let route = self.router.find_route(
349 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
351 ).map_err(|e| PaymentError::Routing(e))?;
353 match send_payment(&route) {
354 Ok(payment_id) => Ok(payment_id),
356 PaymentSendFailure::ParameterError(_) => Err(e),
357 PaymentSendFailure::PathParameterError(_) => Err(e),
358 PaymentSendFailure::AllFailedRetrySafe(_) => {
359 let mut payment_cache = self.payment_cache.lock().unwrap();
360 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
361 if *retry_count >= self.retry_attempts.0 {
365 std::mem::drop(payment_cache);
366 Ok(self.pay_internal(params, payment_hash, send_payment)?)
369 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
370 if let Some(retry_data) = failed_paths_retry {
371 // Some paths were sent, even if we failed to send the full MPP value our
372 // recipient may misbehave and claim the funds, at which point we have to
373 // consider the payment sent, so return `Ok()` here, ignoring any retry
375 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
378 // This may happen if we send a payment and some paths fail, but
379 // only due to a temporary monitor failure or the like, implying
380 // they're really in-flight, but we haven't sent the initial
381 // HTLC-Add messages yet.
386 }.map_err(|e| PaymentError::Sending(e))
390 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
391 ) -> Result<(), ()> {
392 let max_payment_attempts = self.retry_attempts.0 + 1;
393 let attempts = *self.payment_cache.lock().unwrap()
395 .and_modify(|attempts| *attempts += 1)
398 if attempts >= max_payment_attempts {
399 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
403 if has_expired(params) {
404 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
408 let payer = self.payer.node_id();
409 let first_hops = self.payer.first_hops();
410 let route = self.router.find_route(
411 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
415 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
419 match self.payer.retry_payment(&route.unwrap(), payment_id) {
421 Err(PaymentSendFailure::ParameterError(_)) |
422 Err(PaymentSendFailure::PathParameterError(_)) => {
423 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
426 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
427 self.retry_payment(payment_id, payment_hash, params)
429 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
430 if let Some(retry) = failed_paths_retry {
431 // Always return Ok for the same reason as noted in pay_internal.
432 let _ = self.retry_payment(payment_id, payment_hash, &retry);
439 /// Removes the payment cached by the given payment hash.
441 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
442 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
443 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
444 self.payment_cache.lock().unwrap().remove(payment_hash);
448 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
449 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
452 fn has_expired(params: &RouteParameters) -> bool {
453 if let Some(expiry_time) = params.payee.expiry_time {
454 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
458 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
461 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
462 S::Target: for <'a> LockableScore<'a>,
466 fn handle_event(&self, event: &Event) {
468 Event::PaymentPathFailed {
469 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
471 if let Some(short_channel_id) = short_channel_id {
472 let path = path.iter().collect::<Vec<_>>();
473 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
476 if payment_id.is_none() {
477 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
478 } else if *rejected_by_dest {
479 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
480 self.payer.abandon_payment(payment_id.unwrap());
481 } else if retry.is_none() {
482 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
483 self.payer.abandon_payment(payment_id.unwrap());
484 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
485 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
488 self.payer.abandon_payment(payment_id.unwrap());
491 Event::PaymentFailed { payment_hash, .. } => {
492 self.remove_cached_payment(&payment_hash);
494 Event::PaymentPathSuccessful { path, .. } => {
495 let path = path.iter().collect::<Vec<_>>();
496 self.scorer.lock().payment_path_successful(&path);
498 Event::PaymentSent { payment_hash, .. } => {
499 let mut payment_cache = self.payment_cache.lock().unwrap();
500 let attempts = payment_cache
501 .remove(payment_hash)
502 .map_or(1, |attempts| attempts + 1);
503 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
508 // Delegate to the decorated event handler unless the payment is retried.
509 self.event_handler.handle_event(event)
516 use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
517 use utils::create_invoice_from_channelmanager;
518 use bitcoin_hashes::sha256::Hash as Sha256;
519 use lightning::ln::PaymentPreimage;
520 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
521 use lightning::ln::functional_test_utils::*;
522 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
523 use lightning::routing::network_graph::NodeId;
524 use lightning::routing::router::{Payee, Route, RouteHop};
525 use lightning::util::test_utils::TestLogger;
526 use lightning::util::errors::APIError;
527 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
528 use secp256k1::{SecretKey, PublicKey, Secp256k1};
529 use std::cell::RefCell;
530 use std::collections::VecDeque;
531 use std::time::{SystemTime, Duration};
533 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
534 let payment_hash = Sha256::hash(&payment_preimage.0);
535 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
536 InvoiceBuilder::new(Currency::Bitcoin)
537 .description("test".into())
538 .payment_hash(payment_hash)
539 .payment_secret(PaymentSecret([0; 32]))
541 .min_final_cltv_expiry(144)
542 .amount_milli_satoshis(128)
543 .build_signed(|hash| {
544 Secp256k1::new().sign_recoverable(hash, &private_key)
549 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
550 let payment_hash = Sha256::hash(&payment_preimage.0);
551 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
552 InvoiceBuilder::new(Currency::Bitcoin)
553 .description("test".into())
554 .payment_hash(payment_hash)
555 .payment_secret(PaymentSecret([0; 32]))
557 .min_final_cltv_expiry(144)
558 .build_signed(|hash| {
559 Secp256k1::new().sign_recoverable(hash, &private_key)
564 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
565 let payment_hash = Sha256::hash(&payment_preimage.0);
566 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
567 let timestamp = SystemTime::now()
568 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
570 InvoiceBuilder::new(Currency::Bitcoin)
571 .description("test".into())
572 .payment_hash(payment_hash)
573 .payment_secret(PaymentSecret([0; 32]))
574 .timestamp(timestamp)
575 .min_final_cltv_expiry(144)
576 .amount_milli_satoshis(128)
577 .build_signed(|hash| {
578 Secp256k1::new().sign_recoverable(hash, &private_key)
583 fn pubkey() -> PublicKey {
584 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
588 fn pays_invoice_on_first_attempt() {
589 let event_handled = core::cell::RefCell::new(false);
590 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
592 let payment_preimage = PaymentPreimage([1; 32]);
593 let invoice = invoice(payment_preimage);
594 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
595 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
597 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
598 let router = TestRouter {};
599 let scorer = RefCell::new(TestScorer::new());
600 let logger = TestLogger::new();
602 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
604 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
605 assert_eq!(*payer.attempts.borrow(), 1);
607 invoice_payer.handle_event(&Event::PaymentSent {
608 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
610 assert_eq!(*event_handled.borrow(), true);
611 assert_eq!(*payer.attempts.borrow(), 1);
615 fn pays_invoice_on_retry() {
616 let event_handled = core::cell::RefCell::new(false);
617 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
619 let payment_preimage = PaymentPreimage([1; 32]);
620 let invoice = invoice(payment_preimage);
621 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
622 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
624 let payer = TestPayer::new()
625 .expect_send(Amount::ForInvoice(final_value_msat))
626 .expect_send(Amount::OnRetry(final_value_msat / 2));
627 let router = TestRouter {};
628 let scorer = RefCell::new(TestScorer::new());
629 let logger = TestLogger::new();
631 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
633 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
634 assert_eq!(*payer.attempts.borrow(), 1);
636 let event = Event::PaymentPathFailed {
639 network_update: None,
640 rejected_by_dest: false,
641 all_paths_failed: false,
642 path: TestRouter::path_for_value(final_value_msat),
643 short_channel_id: None,
644 retry: Some(TestRouter::retry_for_invoice(&invoice)),
646 invoice_payer.handle_event(&event);
647 assert_eq!(*event_handled.borrow(), false);
648 assert_eq!(*payer.attempts.borrow(), 2);
650 invoice_payer.handle_event(&Event::PaymentSent {
651 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
653 assert_eq!(*event_handled.borrow(), true);
654 assert_eq!(*payer.attempts.borrow(), 2);
658 fn pays_invoice_on_partial_failure() {
659 let event_handler = |_: &_| { panic!() };
661 let payment_preimage = PaymentPreimage([1; 32]);
662 let invoice = invoice(payment_preimage);
663 let retry = TestRouter::retry_for_invoice(&invoice);
664 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
666 let payer = TestPayer::new()
667 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
668 .fails_with_partial_failure(retry, OnAttempt(2))
669 .expect_send(Amount::ForInvoice(final_value_msat))
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 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
682 fn retries_payment_path_for_unknown_payment() {
683 let event_handled = core::cell::RefCell::new(false);
684 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
686 let payment_preimage = PaymentPreimage([1; 32]);
687 let invoice = invoice(payment_preimage);
688 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
689 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
691 let payer = TestPayer::new()
692 .expect_send(Amount::OnRetry(final_value_msat / 2))
693 .expect_send(Amount::OnRetry(final_value_msat / 2));
694 let router = TestRouter {};
695 let scorer = RefCell::new(TestScorer::new());
696 let logger = TestLogger::new();
698 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
700 let payment_id = Some(PaymentId([1; 32]));
701 let event = Event::PaymentPathFailed {
704 network_update: None,
705 rejected_by_dest: false,
706 all_paths_failed: false,
707 path: TestRouter::path_for_value(final_value_msat),
708 short_channel_id: None,
709 retry: Some(TestRouter::retry_for_invoice(&invoice)),
711 invoice_payer.handle_event(&event);
712 assert_eq!(*event_handled.borrow(), false);
713 assert_eq!(*payer.attempts.borrow(), 1);
715 invoice_payer.handle_event(&event);
716 assert_eq!(*event_handled.borrow(), false);
717 assert_eq!(*payer.attempts.borrow(), 2);
719 invoice_payer.handle_event(&Event::PaymentSent {
720 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
722 assert_eq!(*event_handled.borrow(), true);
723 assert_eq!(*payer.attempts.borrow(), 2);
727 fn fails_paying_invoice_after_max_retries() {
728 let event_handled = core::cell::RefCell::new(false);
729 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
731 let payment_preimage = PaymentPreimage([1; 32]);
732 let invoice = invoice(payment_preimage);
733 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
735 let payer = TestPayer::new()
736 .expect_send(Amount::ForInvoice(final_value_msat))
737 .expect_send(Amount::OnRetry(final_value_msat / 2))
738 .expect_send(Amount::OnRetry(final_value_msat / 2));
739 let router = TestRouter {};
740 let scorer = RefCell::new(TestScorer::new());
741 let logger = TestLogger::new();
743 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
745 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
746 assert_eq!(*payer.attempts.borrow(), 1);
748 let event = Event::PaymentPathFailed {
750 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
751 network_update: None,
752 rejected_by_dest: false,
753 all_paths_failed: true,
754 path: TestRouter::path_for_value(final_value_msat),
755 short_channel_id: None,
756 retry: Some(TestRouter::retry_for_invoice(&invoice)),
758 invoice_payer.handle_event(&event);
759 assert_eq!(*event_handled.borrow(), false);
760 assert_eq!(*payer.attempts.borrow(), 2);
762 let event = Event::PaymentPathFailed {
764 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
765 network_update: None,
766 rejected_by_dest: false,
767 all_paths_failed: false,
768 path: TestRouter::path_for_value(final_value_msat / 2),
769 short_channel_id: None,
770 retry: Some(RouteParameters {
771 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
774 invoice_payer.handle_event(&event);
775 assert_eq!(*event_handled.borrow(), false);
776 assert_eq!(*payer.attempts.borrow(), 3);
778 invoice_payer.handle_event(&event);
779 assert_eq!(*event_handled.borrow(), true);
780 assert_eq!(*payer.attempts.borrow(), 3);
784 fn fails_paying_invoice_with_missing_retry_params() {
785 let event_handled = core::cell::RefCell::new(false);
786 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
788 let payment_preimage = PaymentPreimage([1; 32]);
789 let invoice = invoice(payment_preimage);
790 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
792 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
793 let router = TestRouter {};
794 let scorer = RefCell::new(TestScorer::new());
795 let logger = TestLogger::new();
797 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
799 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
800 assert_eq!(*payer.attempts.borrow(), 1);
802 let event = Event::PaymentPathFailed {
804 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
805 network_update: None,
806 rejected_by_dest: false,
807 all_paths_failed: false,
809 short_channel_id: None,
812 invoice_payer.handle_event(&event);
813 assert_eq!(*event_handled.borrow(), true);
814 assert_eq!(*payer.attempts.borrow(), 1);
818 fn fails_paying_invoice_after_expiration() {
819 let event_handled = core::cell::RefCell::new(false);
820 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
822 let payer = TestPayer::new();
823 let router = TestRouter {};
824 let scorer = RefCell::new(TestScorer::new());
825 let logger = TestLogger::new();
827 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
829 let payment_preimage = PaymentPreimage([1; 32]);
830 let invoice = expired_invoice(payment_preimage);
831 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
832 assert_eq!(msg, "Invoice expired prior to send");
833 } else { panic!("Expected Invoice Error"); }
837 fn fails_retrying_invoice_after_expiration() {
838 let event_handled = core::cell::RefCell::new(false);
839 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
841 let payment_preimage = PaymentPreimage([1; 32]);
842 let invoice = invoice(payment_preimage);
843 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
845 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
846 let router = TestRouter {};
847 let scorer = RefCell::new(TestScorer::new());
848 let logger = TestLogger::new();
850 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
852 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
853 assert_eq!(*payer.attempts.borrow(), 1);
855 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
856 retry_data.payee.expiry_time = Some(SystemTime::now()
857 .checked_sub(Duration::from_secs(2)).unwrap()
858 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
859 let event = Event::PaymentPathFailed {
861 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
862 network_update: None,
863 rejected_by_dest: false,
864 all_paths_failed: false,
866 short_channel_id: None,
867 retry: Some(retry_data),
869 invoice_payer.handle_event(&event);
870 assert_eq!(*event_handled.borrow(), true);
871 assert_eq!(*payer.attempts.borrow(), 1);
875 fn fails_paying_invoice_after_retry_error() {
876 let event_handled = core::cell::RefCell::new(false);
877 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
879 let payment_preimage = PaymentPreimage([1; 32]);
880 let invoice = invoice(payment_preimage);
881 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
883 let payer = TestPayer::new()
885 .expect_send(Amount::ForInvoice(final_value_msat))
886 .expect_send(Amount::OnRetry(final_value_msat / 2));
887 let router = TestRouter {};
888 let scorer = RefCell::new(TestScorer::new());
889 let logger = TestLogger::new();
891 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
893 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
894 assert_eq!(*payer.attempts.borrow(), 1);
896 let event = Event::PaymentPathFailed {
898 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
899 network_update: None,
900 rejected_by_dest: false,
901 all_paths_failed: false,
902 path: TestRouter::path_for_value(final_value_msat / 2),
903 short_channel_id: None,
904 retry: Some(TestRouter::retry_for_invoice(&invoice)),
906 invoice_payer.handle_event(&event);
907 assert_eq!(*event_handled.borrow(), true);
908 assert_eq!(*payer.attempts.borrow(), 2);
912 fn fails_paying_invoice_after_rejected_by_payee() {
913 let event_handled = core::cell::RefCell::new(false);
914 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
916 let payment_preimage = PaymentPreimage([1; 32]);
917 let invoice = invoice(payment_preimage);
918 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
920 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
921 let router = TestRouter {};
922 let scorer = RefCell::new(TestScorer::new());
923 let logger = TestLogger::new();
925 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
927 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
928 assert_eq!(*payer.attempts.borrow(), 1);
930 let event = Event::PaymentPathFailed {
932 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
933 network_update: None,
934 rejected_by_dest: true,
935 all_paths_failed: false,
937 short_channel_id: None,
938 retry: Some(TestRouter::retry_for_invoice(&invoice)),
940 invoice_payer.handle_event(&event);
941 assert_eq!(*event_handled.borrow(), true);
942 assert_eq!(*payer.attempts.borrow(), 1);
946 fn fails_repaying_invoice_with_pending_payment() {
947 let event_handled = core::cell::RefCell::new(false);
948 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
950 let payment_preimage = PaymentPreimage([1; 32]);
951 let invoice = invoice(payment_preimage);
952 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
954 let payer = TestPayer::new()
955 .expect_send(Amount::ForInvoice(final_value_msat))
956 .expect_send(Amount::ForInvoice(final_value_msat));
957 let router = TestRouter {};
958 let scorer = RefCell::new(TestScorer::new());
959 let logger = TestLogger::new();
961 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
963 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
965 // Cannot repay an invoice pending payment.
966 match invoice_payer.pay_invoice(&invoice) {
967 Err(PaymentError::Invoice("payment pending")) => {},
968 Err(_) => panic!("unexpected error"),
969 Ok(_) => panic!("expected invoice error"),
972 // Can repay an invoice once cleared from cache.
973 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
974 invoice_payer.remove_cached_payment(&payment_hash);
975 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
977 // Cannot retry paying an invoice if cleared from cache.
978 invoice_payer.remove_cached_payment(&payment_hash);
979 let event = Event::PaymentPathFailed {
982 network_update: None,
983 rejected_by_dest: false,
984 all_paths_failed: false,
986 short_channel_id: None,
987 retry: Some(TestRouter::retry_for_invoice(&invoice)),
989 invoice_payer.handle_event(&event);
990 assert_eq!(*event_handled.borrow(), true);
994 fn fails_paying_invoice_with_routing_errors() {
995 let payer = TestPayer::new();
996 let router = FailingRouter {};
997 let scorer = RefCell::new(TestScorer::new());
998 let logger = TestLogger::new();
1000 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1002 let payment_preimage = PaymentPreimage([1; 32]);
1003 let invoice = invoice(payment_preimage);
1004 match invoice_payer.pay_invoice(&invoice) {
1005 Err(PaymentError::Routing(_)) => {},
1006 Err(_) => panic!("unexpected error"),
1007 Ok(_) => panic!("expected routing error"),
1012 fn fails_paying_invoice_with_sending_errors() {
1013 let payment_preimage = PaymentPreimage([1; 32]);
1014 let invoice = invoice(payment_preimage);
1015 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1017 let payer = TestPayer::new()
1018 .fails_on_attempt(1)
1019 .expect_send(Amount::ForInvoice(final_value_msat));
1020 let router = TestRouter {};
1021 let scorer = RefCell::new(TestScorer::new());
1022 let logger = TestLogger::new();
1024 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1026 match invoice_payer.pay_invoice(&invoice) {
1027 Err(PaymentError::Sending(_)) => {},
1028 Err(_) => panic!("unexpected error"),
1029 Ok(_) => panic!("expected sending error"),
1034 fn pays_zero_value_invoice_using_amount() {
1035 let event_handled = core::cell::RefCell::new(false);
1036 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1038 let payment_preimage = PaymentPreimage([1; 32]);
1039 let invoice = zero_value_invoice(payment_preimage);
1040 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1041 let final_value_msat = 100;
1043 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1044 let router = TestRouter {};
1045 let scorer = RefCell::new(TestScorer::new());
1046 let logger = TestLogger::new();
1048 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1051 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1052 assert_eq!(*payer.attempts.borrow(), 1);
1054 invoice_payer.handle_event(&Event::PaymentSent {
1055 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1057 assert_eq!(*event_handled.borrow(), true);
1058 assert_eq!(*payer.attempts.borrow(), 1);
1062 fn fails_paying_zero_value_invoice_with_amount() {
1063 let event_handled = core::cell::RefCell::new(false);
1064 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1066 let payer = TestPayer::new();
1067 let router = TestRouter {};
1068 let scorer = RefCell::new(TestScorer::new());
1069 let logger = TestLogger::new();
1071 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1073 let payment_preimage = PaymentPreimage([1; 32]);
1074 let invoice = invoice(payment_preimage);
1076 // Cannot repay an invoice pending payment.
1077 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1078 Err(PaymentError::Invoice("amount unexpected")) => {},
1079 Err(_) => panic!("unexpected error"),
1080 Ok(_) => panic!("expected invoice error"),
1085 fn pays_pubkey_with_amount() {
1086 let event_handled = core::cell::RefCell::new(false);
1087 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1089 let pubkey = pubkey();
1090 let payment_preimage = PaymentPreimage([1; 32]);
1091 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1092 let final_value_msat = 100;
1093 let final_cltv_expiry_delta = 42;
1095 let payer = TestPayer::new()
1096 .expect_send(Amount::Spontaneous(final_value_msat))
1097 .expect_send(Amount::OnRetry(final_value_msat));
1098 let router = TestRouter {};
1099 let scorer = RefCell::new(TestScorer::new());
1100 let logger = TestLogger::new();
1102 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1104 let payment_id = Some(invoice_payer.pay_pubkey(
1105 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1107 assert_eq!(*payer.attempts.borrow(), 1);
1109 let retry = RouteParameters {
1110 payee: Payee::for_keysend(pubkey),
1112 final_cltv_expiry_delta,
1114 let event = Event::PaymentPathFailed {
1117 network_update: None,
1118 rejected_by_dest: false,
1119 all_paths_failed: false,
1121 short_channel_id: None,
1124 invoice_payer.handle_event(&event);
1125 assert_eq!(*event_handled.borrow(), false);
1126 assert_eq!(*payer.attempts.borrow(), 2);
1128 invoice_payer.handle_event(&Event::PaymentSent {
1129 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1131 assert_eq!(*event_handled.borrow(), true);
1132 assert_eq!(*payer.attempts.borrow(), 2);
1136 fn scores_failed_channel() {
1137 let event_handled = core::cell::RefCell::new(false);
1138 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1140 let payment_preimage = PaymentPreimage([1; 32]);
1141 let invoice = invoice(payment_preimage);
1142 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1143 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1144 let path = TestRouter::path_for_value(final_value_msat);
1145 let short_channel_id = Some(path[0].short_channel_id);
1147 // Expect that scorer is given short_channel_id upon handling the event.
1148 let payer = TestPayer::new()
1149 .expect_send(Amount::ForInvoice(final_value_msat))
1150 .expect_send(Amount::OnRetry(final_value_msat / 2));
1151 let router = TestRouter {};
1152 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1153 path: path.clone(), short_channel_id: path[0].short_channel_id,
1155 let logger = TestLogger::new();
1157 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1159 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1160 let event = Event::PaymentPathFailed {
1163 network_update: None,
1164 rejected_by_dest: false,
1165 all_paths_failed: false,
1168 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1170 invoice_payer.handle_event(&event);
1174 fn scores_successful_channels() {
1175 let event_handled = core::cell::RefCell::new(false);
1176 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1178 let payment_preimage = PaymentPreimage([1; 32]);
1179 let invoice = invoice(payment_preimage);
1180 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1181 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1182 let route = TestRouter::route_for_value(final_value_msat);
1184 // Expect that scorer is given short_channel_id upon handling the event.
1185 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1186 let router = TestRouter {};
1187 let scorer = RefCell::new(TestScorer::new()
1188 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1189 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1191 let logger = TestLogger::new();
1193 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1195 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1196 let event = Event::PaymentPathSuccessful {
1197 payment_id, payment_hash, path: route.paths[0].clone()
1199 invoice_payer.handle_event(&event);
1200 let event = Event::PaymentPathSuccessful {
1201 payment_id, payment_hash, path: route.paths[1].clone()
1203 invoice_payer.handle_event(&event);
1209 fn route_for_value(final_value_msat: u64) -> Route {
1213 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1214 channel_features: ChannelFeatures::empty(),
1215 node_features: NodeFeatures::empty(),
1216 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1219 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1220 channel_features: ChannelFeatures::empty(),
1221 node_features: NodeFeatures::empty(),
1222 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1229 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1230 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1233 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1234 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1235 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1236 .with_route_hints(invoice.route_hints());
1237 if let Some(features) = invoice.features() {
1238 payee = payee.with_features(features.clone());
1240 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1244 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1249 impl<S: Score> Router<S> for TestRouter {
1251 &self, _payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
1252 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1253 ) -> Result<Route, LightningError> {
1255 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1260 struct FailingRouter;
1262 impl<S: Score> Router<S> for FailingRouter {
1264 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1265 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1266 ) -> Result<Route, LightningError> {
1267 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1272 expectations: Option<VecDeque<PaymentPath>>,
1277 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1278 Success { path: Vec<RouteHop> },
1288 fn expect(mut self, expectation: PaymentPath) -> Self {
1289 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1295 impl lightning::util::ser::Writeable for TestScorer {
1296 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1299 impl Score for TestScorer {
1300 fn channel_penalty_msat(
1301 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
1304 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1305 if let Some(expectations) = &mut self.expectations {
1306 match expectations.pop_front() {
1307 Some(PaymentPath::Failure { path, short_channel_id }) => {
1308 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1309 assert_eq!(actual_short_channel_id, short_channel_id);
1311 Some(PaymentPath::Success { path }) => {
1312 panic!("Unexpected successful payment path: {:?}", path)
1314 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1319 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1320 if let Some(expectations) = &mut self.expectations {
1321 match expectations.pop_front() {
1322 Some(PaymentPath::Failure { path, .. }) => {
1323 panic!("Unexpected payment path failure: {:?}", path)
1325 Some(PaymentPath::Success { path }) => {
1326 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1328 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1334 impl Drop for TestScorer {
1335 fn drop(&mut self) {
1336 if std::thread::panicking() {
1340 if let Some(expectations) = &self.expectations {
1341 if !expectations.is_empty() {
1342 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1349 expectations: core::cell::RefCell<VecDeque<Amount>>,
1350 attempts: core::cell::RefCell<usize>,
1351 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1354 #[derive(Clone, Debug, PartialEq, Eq)]
1361 struct OnAttempt(usize);
1366 expectations: core::cell::RefCell::new(VecDeque::new()),
1367 attempts: core::cell::RefCell::new(0),
1368 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1372 fn expect_send(self, value_msat: Amount) -> Self {
1373 self.expectations.borrow_mut().push_back(value_msat);
1377 fn fails_on_attempt(self, attempt: usize) -> Self {
1378 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1379 self.fails_with(failure, OnAttempt(attempt))
1382 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1383 self.fails_with(PaymentSendFailure::PartialFailure {
1385 failed_paths_retry: Some(retry),
1386 payment_id: PaymentId([1; 32]),
1390 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1391 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1395 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1396 let mut attempts = self.attempts.borrow_mut();
1399 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1400 Some(failure) => Err(failure),
1401 None => Ok(PaymentId([1; 32])),
1405 fn check_value_msats(&self, actual_value_msats: Amount) {
1406 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1407 if let Some(expected_value_msats) = expected_value_msats {
1408 assert_eq!(actual_value_msats, expected_value_msats);
1410 panic!("Unexpected amount: {:?}", actual_value_msats);
1415 impl Drop for TestPayer {
1416 fn drop(&mut self) {
1417 if std::thread::panicking() {
1421 if !self.expectations.borrow().is_empty() {
1422 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1427 impl Payer for TestPayer {
1428 fn node_id(&self) -> PublicKey {
1429 let secp_ctx = Secp256k1::new();
1430 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1433 fn first_hops(&self) -> Vec<ChannelDetails> {
1438 &self, route: &Route, _payment_hash: PaymentHash,
1439 _payment_secret: &Option<PaymentSecret>
1440 ) -> Result<PaymentId, PaymentSendFailure> {
1441 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1442 self.check_attempts()
1445 fn send_spontaneous_payment(
1446 &self, route: &Route, _payment_preimage: PaymentPreimage,
1447 ) -> Result<PaymentId, PaymentSendFailure> {
1448 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1449 self.check_attempts()
1453 &self, route: &Route, _payment_id: PaymentId
1454 ) -> Result<(), PaymentSendFailure> {
1455 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1456 self.check_attempts().map(|_| ())
1459 fn abandon_payment(&self, _payment_id: PaymentId) { }
1462 // *** Full Featured Functional Tests with a Real ChannelManager ***
1463 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1465 impl<S: Score> Router<S> for ManualRouter {
1467 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1468 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1469 ) -> Result<Route, LightningError> {
1470 self.0.borrow_mut().pop_front().unwrap()
1474 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1475 self.0.borrow_mut().push_back(result);
1478 impl Drop for ManualRouter {
1479 fn drop(&mut self) {
1480 if std::thread::panicking() {
1483 assert!(self.0.borrow_mut().is_empty());
1488 fn retry_multi_path_single_failed_payment() {
1489 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1490 let chanmon_cfgs = create_chanmon_cfgs(2);
1491 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1492 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1493 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1495 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1496 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1497 let chans = nodes[0].node.list_usable_channels();
1498 let mut route = Route {
1501 pubkey: nodes[1].node.get_our_node_id(),
1502 node_features: NodeFeatures::known(),
1503 short_channel_id: chans[0].short_channel_id.unwrap(),
1504 channel_features: ChannelFeatures::known(),
1506 cltv_expiry_delta: 100,
1509 pubkey: nodes[1].node.get_our_node_id(),
1510 node_features: NodeFeatures::known(),
1511 short_channel_id: chans[1].short_channel_id.unwrap(),
1512 channel_features: ChannelFeatures::known(),
1513 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1514 cltv_expiry_delta: 100,
1517 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1519 let router = ManualRouter(RefCell::new(VecDeque::new()));
1520 router.expect_find_route(Ok(route.clone()));
1521 // On retry, split the payment across both channels.
1522 route.paths[0][0].fee_msat = 50_000_001;
1523 route.paths[1][0].fee_msat = 50_000_000;
1524 router.expect_find_route(Ok(route.clone()));
1526 let event_handler = |_: &_| { panic!(); };
1527 let scorer = RefCell::new(TestScorer::new());
1528 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1530 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1531 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1533 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1534 assert_eq!(htlc_msgs.len(), 2);
1535 check_added_monitors!(nodes[0], 2);
1539 fn immediate_retry_on_failure() {
1540 // Tests that we can/will retry immediately after a failure
1541 let chanmon_cfgs = create_chanmon_cfgs(2);
1542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1544 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1547 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1548 let chans = nodes[0].node.list_usable_channels();
1549 let mut route = Route {
1552 pubkey: nodes[1].node.get_our_node_id(),
1553 node_features: NodeFeatures::known(),
1554 short_channel_id: chans[0].short_channel_id.unwrap(),
1555 channel_features: ChannelFeatures::known(),
1556 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1557 cltv_expiry_delta: 100,
1560 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1562 let router = ManualRouter(RefCell::new(VecDeque::new()));
1563 router.expect_find_route(Ok(route.clone()));
1564 // On retry, split the payment across both channels.
1565 route.paths.push(route.paths[0].clone());
1566 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1567 route.paths[0][0].fee_msat = 50_000_000;
1568 route.paths[1][0].fee_msat = 50_000_001;
1569 router.expect_find_route(Ok(route.clone()));
1571 let event_handler = |_: &_| { panic!(); };
1572 let scorer = RefCell::new(TestScorer::new());
1573 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1575 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1576 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1578 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1579 assert_eq!(htlc_msgs.len(), 2);
1580 check_added_monitors!(nodes[0], 2);
1584 fn no_extra_retries_on_back_to_back_fail() {
1585 // In a previous release, we had a race where we may exceed the payment retry count if we
1586 // get two failures in a row with the second having `all_paths_failed` set.
1587 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1588 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1589 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1590 // pending which we will see later. Thus, when we previously removed the retry tracking map
1591 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1592 // retry entry even though more events for the same payment were still pending. This led to
1593 // us retrying a payment again even though we'd already given up on it.
1595 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1596 // is used to remove the payment retry counter entries instead. This tests for the specific
1597 // excess-retry case while also testing `PaymentFailed` generation.
1599 let chanmon_cfgs = create_chanmon_cfgs(3);
1600 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1601 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1602 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1604 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1605 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1607 let mut route = Route {
1610 pubkey: nodes[1].node.get_our_node_id(),
1611 node_features: NodeFeatures::known(),
1612 short_channel_id: chan_1_scid,
1613 channel_features: ChannelFeatures::known(),
1615 cltv_expiry_delta: 100,
1617 pubkey: nodes[2].node.get_our_node_id(),
1618 node_features: NodeFeatures::known(),
1619 short_channel_id: chan_2_scid,
1620 channel_features: ChannelFeatures::known(),
1621 fee_msat: 100_000_000,
1622 cltv_expiry_delta: 100,
1625 pubkey: nodes[1].node.get_our_node_id(),
1626 node_features: NodeFeatures::known(),
1627 short_channel_id: chan_1_scid,
1628 channel_features: ChannelFeatures::known(),
1630 cltv_expiry_delta: 100,
1632 pubkey: nodes[2].node.get_our_node_id(),
1633 node_features: NodeFeatures::known(),
1634 short_channel_id: chan_2_scid,
1635 channel_features: ChannelFeatures::known(),
1636 fee_msat: 100_000_000,
1637 cltv_expiry_delta: 100,
1640 payee: Some(Payee::from_node_id(nodes[2].node.get_our_node_id())),
1642 let router = ManualRouter(RefCell::new(VecDeque::new()));
1643 router.expect_find_route(Ok(route.clone()));
1644 // On retry, we'll only be asked for one path
1645 route.paths.remove(1);
1646 router.expect_find_route(Ok(route.clone()));
1648 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1649 let event_handler = |event: &Event| {
1650 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1651 event_checker(event);
1653 let scorer = RefCell::new(TestScorer::new());
1654 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1656 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1657 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1659 let htlc_updates = SendEvent::from_node(&nodes[0]);
1660 check_added_monitors!(nodes[0], 1);
1661 assert_eq!(htlc_updates.msgs.len(), 1);
1663 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1664 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1665 check_added_monitors!(nodes[1], 1);
1666 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1668 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1669 check_added_monitors!(nodes[0], 1);
1670 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1673 check_added_monitors!(nodes[0], 1);
1674 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1677 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1678 check_added_monitors!(nodes[1], 1);
1679 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1681 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1682 check_added_monitors!(nodes[1], 1);
1683 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1685 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1686 check_added_monitors!(nodes[0], 1);
1688 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1689 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1690 check_added_monitors!(nodes[0], 1);
1691 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1693 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1694 check_added_monitors!(nodes[1], 1);
1695 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1697 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1698 check_added_monitors!(nodes[1], 1);
1699 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1701 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1702 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1703 check_added_monitors!(nodes[0], 1);
1705 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1706 check_added_monitors!(nodes[0], 1);
1707 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1709 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1710 check_added_monitors!(nodes[1], 1);
1711 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1712 check_added_monitors!(nodes[1], 1);
1713 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1715 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1716 check_added_monitors!(nodes[0], 1);
1718 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1719 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1720 // with it set. The first event will use up the only retry we are allowed, with the second
1721 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1722 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1723 // if the final HTLC failed.
1724 expected_events.borrow_mut().push_back(&|ev: &Event| {
1725 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1726 assert!(!rejected_by_dest);
1727 assert!(all_paths_failed);
1728 } else { panic!("Unexpected event"); }
1730 nodes[0].node.process_pending_events(&invoice_payer);
1731 assert!(expected_events.borrow().is_empty());
1733 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1734 check_added_monitors!(nodes[0], 1);
1736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1737 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1738 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1739 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1740 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1742 expected_events.borrow_mut().push_back(&|ev: &Event| {
1743 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1744 assert!(!rejected_by_dest);
1745 assert!(all_paths_failed);
1746 } else { panic!("Unexpected event"); }
1748 expected_events.borrow_mut().push_back(&|ev: &Event| {
1749 if let Event::PaymentFailed { .. } = ev {
1750 } else { panic!("Unexpected event"); }
1752 nodes[0].node.process_pending_events(&invoice_payer);
1753 assert!(expected_events.borrow().is_empty());