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: EventHandler>
156 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
157 S::Target: for <'a> LockableScore<'a>,
165 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
166 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
167 retry_attempts: RetryAttempts,
170 /// A trait defining behavior of an [`Invoice`] payer.
172 /// Returns the payer's node id.
173 fn node_id(&self) -> PublicKey;
175 /// Returns the payer's channels.
176 fn first_hops(&self) -> Vec<ChannelDetails>;
178 /// Sends a payment over the Lightning Network using the given [`Route`].
180 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
181 ) -> Result<PaymentId, PaymentSendFailure>;
183 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
184 fn send_spontaneous_payment(
185 &self, route: &Route, payment_preimage: PaymentPreimage
186 ) -> Result<PaymentId, PaymentSendFailure>;
188 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
189 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
191 /// Signals that no further retries for the given payment will occur.
192 fn abandon_payment(&self, payment_id: PaymentId);
195 /// A trait defining behavior for routing an [`Invoice`] payment.
196 pub trait Router<S: Score> {
197 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
199 &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
200 first_hops: Option<&[&ChannelDetails]>, scorer: &S
201 ) -> Result<Route, LightningError>;
204 /// Number of attempts to retry payment path failures for an [`Invoice`].
206 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
207 /// payments, if this is less than the total number of paths, we will never even retry all of the
209 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
210 pub struct RetryAttempts(pub usize);
212 /// An error that may occur when making a payment.
213 #[derive(Clone, Debug)]
214 pub enum PaymentError {
215 /// An error resulting from the provided [`Invoice`] or payment hash.
216 Invoice(&'static str),
217 /// An error occurring when finding a route.
218 Routing(LightningError),
219 /// An error occurring when sending a payment.
220 Sending(PaymentSendFailure),
223 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> InvoicePayer<P, R, S, L, E>
226 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
227 S::Target: for <'a> LockableScore<'a>,
230 /// Creates an invoice payer that retries failed payment paths.
232 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
233 /// `retry_attempts` has been exceeded for a given [`Invoice`].
235 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
243 payment_cache: Mutex::new(HashMap::new()),
248 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
250 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
251 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
253 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
254 if invoice.amount_milli_satoshis().is_none() {
255 Err(PaymentError::Invoice("amount missing"))
257 self.pay_invoice_using_amount(invoice, None)
261 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
262 /// case a retry is needed.
264 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
265 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
267 pub fn pay_zero_value_invoice(
268 &self, invoice: &Invoice, amount_msats: u64
269 ) -> Result<PaymentId, PaymentError> {
270 if invoice.amount_milli_satoshis().is_some() {
271 Err(PaymentError::Invoice("amount unexpected"))
273 self.pay_invoice_using_amount(invoice, Some(amount_msats))
277 fn pay_invoice_using_amount(
278 &self, invoice: &Invoice, amount_msats: Option<u64>
279 ) -> Result<PaymentId, PaymentError> {
280 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
282 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
283 match self.payment_cache.lock().unwrap().entry(payment_hash) {
284 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
285 hash_map::Entry::Vacant(entry) => entry.insert(0),
288 let payment_secret = Some(invoice.payment_secret().clone());
289 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
290 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
291 .with_route_hints(invoice.route_hints());
292 if let Some(features) = invoice.features() {
293 payee = payee.with_features(features.clone());
295 let params = RouteParameters {
297 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
298 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
301 let send_payment = |route: &Route| {
302 self.payer.send_payment(route, payment_hash, &payment_secret)
304 self.pay_internal(¶ms, payment_hash, send_payment)
305 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
308 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
309 /// case a retry is needed.
311 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
312 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
314 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
315 final_cltv_expiry_delta: u32
316 ) -> Result<PaymentId, PaymentError> {
317 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
318 match self.payment_cache.lock().unwrap().entry(payment_hash) {
319 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
320 hash_map::Entry::Vacant(entry) => entry.insert(0),
323 let params = RouteParameters {
324 payee: Payee::for_keysend(pubkey),
325 final_value_msat: amount_msats,
326 final_cltv_expiry_delta,
329 let send_payment = |route: &Route| {
330 self.payer.send_spontaneous_payment(route, payment_preimage)
332 self.pay_internal(¶ms, payment_hash, send_payment)
333 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
336 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
337 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
338 ) -> Result<PaymentId, PaymentError> {
339 if has_expired(params) {
340 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
341 return Err(PaymentError::Invoice("Invoice expired prior to send"));
344 let payer = self.payer.node_id();
345 let first_hops = self.payer.first_hops();
346 let route = self.router.find_route(
347 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
349 ).map_err(|e| PaymentError::Routing(e))?;
351 match send_payment(&route) {
352 Ok(payment_id) => Ok(payment_id),
354 PaymentSendFailure::ParameterError(_) => Err(e),
355 PaymentSendFailure::PathParameterError(_) => Err(e),
356 PaymentSendFailure::AllFailedRetrySafe(_) => {
357 let mut payment_cache = self.payment_cache.lock().unwrap();
358 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
359 if *retry_count >= self.retry_attempts.0 {
363 std::mem::drop(payment_cache);
364 Ok(self.pay_internal(params, payment_hash, send_payment)?)
367 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
368 if let Some(retry_data) = failed_paths_retry {
369 // Some paths were sent, even if we failed to send the full MPP value our
370 // recipient may misbehave and claim the funds, at which point we have to
371 // consider the payment sent, so return `Ok()` here, ignoring any retry
373 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
376 // This may happen if we send a payment and some paths fail, but
377 // only due to a temporary monitor failure or the like, implying
378 // they're really in-flight, but we haven't sent the initial
379 // HTLC-Add messages yet.
384 }.map_err(|e| PaymentError::Sending(e))
388 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
389 ) -> Result<(), ()> {
390 let max_payment_attempts = self.retry_attempts.0 + 1;
391 let attempts = *self.payment_cache.lock().unwrap()
393 .and_modify(|attempts| *attempts += 1)
396 if attempts >= max_payment_attempts {
397 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
401 if has_expired(params) {
402 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
406 let payer = self.payer.node_id();
407 let first_hops = self.payer.first_hops();
408 let route = self.router.find_route(
409 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
413 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
417 match self.payer.retry_payment(&route.unwrap(), payment_id) {
419 Err(PaymentSendFailure::ParameterError(_)) |
420 Err(PaymentSendFailure::PathParameterError(_)) => {
421 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
424 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
425 self.retry_payment(payment_id, payment_hash, params)
427 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
428 if let Some(retry) = failed_paths_retry {
429 // Always return Ok for the same reason as noted in pay_internal.
430 let _ = self.retry_payment(payment_id, payment_hash, &retry);
437 /// Removes the payment cached by the given payment hash.
439 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
440 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
441 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
442 self.payment_cache.lock().unwrap().remove(payment_hash);
446 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
447 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
450 fn has_expired(params: &RouteParameters) -> bool {
451 if let Some(expiry_time) = params.payee.expiry_time {
452 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
456 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> EventHandler for InvoicePayer<P, R, S, L, E>
459 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
460 S::Target: for <'a> LockableScore<'a>,
463 fn handle_event(&self, event: &Event) {
465 Event::PaymentPathFailed {
466 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
468 if let Some(short_channel_id) = short_channel_id {
469 let path = path.iter().collect::<Vec<_>>();
470 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
473 if payment_id.is_none() {
474 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
475 } else if *rejected_by_dest {
476 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
477 self.payer.abandon_payment(payment_id.unwrap());
478 } else if retry.is_none() {
479 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
480 self.payer.abandon_payment(payment_id.unwrap());
481 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
482 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
485 self.payer.abandon_payment(payment_id.unwrap());
488 Event::PaymentFailed { payment_hash, .. } => {
489 self.remove_cached_payment(&payment_hash);
491 Event::PaymentPathSuccessful { path, .. } => {
492 let path = path.iter().collect::<Vec<_>>();
493 self.scorer.lock().payment_path_successful(&path);
495 Event::PaymentSent { payment_hash, .. } => {
496 let mut payment_cache = self.payment_cache.lock().unwrap();
497 let attempts = payment_cache
498 .remove(payment_hash)
499 .map_or(1, |attempts| attempts + 1);
500 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
505 // Delegate to the decorated event handler unless the payment is retried.
506 self.event_handler.handle_event(event)
513 use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
514 use utils::create_invoice_from_channelmanager;
515 use bitcoin_hashes::sha256::Hash as Sha256;
516 use lightning::ln::PaymentPreimage;
517 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
518 use lightning::ln::functional_test_utils::*;
519 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
520 use lightning::routing::network_graph::NodeId;
521 use lightning::routing::router::{Payee, Route, RouteHop};
522 use lightning::util::test_utils::TestLogger;
523 use lightning::util::errors::APIError;
524 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
525 use secp256k1::{SecretKey, PublicKey, Secp256k1};
526 use std::cell::RefCell;
527 use std::collections::VecDeque;
528 use std::time::{SystemTime, Duration};
530 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
531 let payment_hash = Sha256::hash(&payment_preimage.0);
532 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
533 InvoiceBuilder::new(Currency::Bitcoin)
534 .description("test".into())
535 .payment_hash(payment_hash)
536 .payment_secret(PaymentSecret([0; 32]))
538 .min_final_cltv_expiry(144)
539 .amount_milli_satoshis(128)
540 .build_signed(|hash| {
541 Secp256k1::new().sign_recoverable(hash, &private_key)
546 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
547 let payment_hash = Sha256::hash(&payment_preimage.0);
548 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
549 InvoiceBuilder::new(Currency::Bitcoin)
550 .description("test".into())
551 .payment_hash(payment_hash)
552 .payment_secret(PaymentSecret([0; 32]))
554 .min_final_cltv_expiry(144)
555 .build_signed(|hash| {
556 Secp256k1::new().sign_recoverable(hash, &private_key)
561 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
562 let payment_hash = Sha256::hash(&payment_preimage.0);
563 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
564 let timestamp = SystemTime::now()
565 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
567 InvoiceBuilder::new(Currency::Bitcoin)
568 .description("test".into())
569 .payment_hash(payment_hash)
570 .payment_secret(PaymentSecret([0; 32]))
571 .timestamp(timestamp)
572 .min_final_cltv_expiry(144)
573 .amount_milli_satoshis(128)
574 .build_signed(|hash| {
575 Secp256k1::new().sign_recoverable(hash, &private_key)
580 fn pubkey() -> PublicKey {
581 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
585 fn pays_invoice_on_first_attempt() {
586 let event_handled = core::cell::RefCell::new(false);
587 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
589 let payment_preimage = PaymentPreimage([1; 32]);
590 let invoice = invoice(payment_preimage);
591 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
592 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
594 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
595 let router = TestRouter {};
596 let scorer = RefCell::new(TestScorer::new());
597 let logger = TestLogger::new();
599 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
601 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
602 assert_eq!(*payer.attempts.borrow(), 1);
604 invoice_payer.handle_event(&Event::PaymentSent {
605 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
607 assert_eq!(*event_handled.borrow(), true);
608 assert_eq!(*payer.attempts.borrow(), 1);
612 fn pays_invoice_on_retry() {
613 let event_handled = core::cell::RefCell::new(false);
614 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
616 let payment_preimage = PaymentPreimage([1; 32]);
617 let invoice = invoice(payment_preimage);
618 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
619 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
621 let payer = TestPayer::new()
622 .expect_send(Amount::ForInvoice(final_value_msat))
623 .expect_send(Amount::OnRetry(final_value_msat / 2));
624 let router = TestRouter {};
625 let scorer = RefCell::new(TestScorer::new());
626 let logger = TestLogger::new();
628 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
630 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
631 assert_eq!(*payer.attempts.borrow(), 1);
633 let event = Event::PaymentPathFailed {
636 network_update: None,
637 rejected_by_dest: false,
638 all_paths_failed: false,
639 path: TestRouter::path_for_value(final_value_msat),
640 short_channel_id: None,
641 retry: Some(TestRouter::retry_for_invoice(&invoice)),
643 invoice_payer.handle_event(&event);
644 assert_eq!(*event_handled.borrow(), false);
645 assert_eq!(*payer.attempts.borrow(), 2);
647 invoice_payer.handle_event(&Event::PaymentSent {
648 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
650 assert_eq!(*event_handled.borrow(), true);
651 assert_eq!(*payer.attempts.borrow(), 2);
655 fn pays_invoice_on_partial_failure() {
656 let event_handler = |_: &_| { panic!() };
658 let payment_preimage = PaymentPreimage([1; 32]);
659 let invoice = invoice(payment_preimage);
660 let retry = TestRouter::retry_for_invoice(&invoice);
661 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
663 let payer = TestPayer::new()
664 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
665 .fails_with_partial_failure(retry, OnAttempt(2))
666 .expect_send(Amount::ForInvoice(final_value_msat))
667 .expect_send(Amount::OnRetry(final_value_msat / 2))
668 .expect_send(Amount::OnRetry(final_value_msat / 2));
669 let router = TestRouter {};
670 let scorer = RefCell::new(TestScorer::new());
671 let logger = TestLogger::new();
673 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
675 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
679 fn retries_payment_path_for_unknown_payment() {
680 let event_handled = core::cell::RefCell::new(false);
681 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
683 let payment_preimage = PaymentPreimage([1; 32]);
684 let invoice = invoice(payment_preimage);
685 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
686 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
688 let payer = TestPayer::new()
689 .expect_send(Amount::OnRetry(final_value_msat / 2))
690 .expect_send(Amount::OnRetry(final_value_msat / 2));
691 let router = TestRouter {};
692 let scorer = RefCell::new(TestScorer::new());
693 let logger = TestLogger::new();
695 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
697 let payment_id = Some(PaymentId([1; 32]));
698 let event = Event::PaymentPathFailed {
701 network_update: None,
702 rejected_by_dest: false,
703 all_paths_failed: false,
704 path: TestRouter::path_for_value(final_value_msat),
705 short_channel_id: None,
706 retry: Some(TestRouter::retry_for_invoice(&invoice)),
708 invoice_payer.handle_event(&event);
709 assert_eq!(*event_handled.borrow(), false);
710 assert_eq!(*payer.attempts.borrow(), 1);
712 invoice_payer.handle_event(&event);
713 assert_eq!(*event_handled.borrow(), false);
714 assert_eq!(*payer.attempts.borrow(), 2);
716 invoice_payer.handle_event(&Event::PaymentSent {
717 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
719 assert_eq!(*event_handled.borrow(), true);
720 assert_eq!(*payer.attempts.borrow(), 2);
724 fn fails_paying_invoice_after_max_retries() {
725 let event_handled = core::cell::RefCell::new(false);
726 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
728 let payment_preimage = PaymentPreimage([1; 32]);
729 let invoice = invoice(payment_preimage);
730 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
732 let payer = TestPayer::new()
733 .expect_send(Amount::ForInvoice(final_value_msat))
734 .expect_send(Amount::OnRetry(final_value_msat / 2))
735 .expect_send(Amount::OnRetry(final_value_msat / 2));
736 let router = TestRouter {};
737 let scorer = RefCell::new(TestScorer::new());
738 let logger = TestLogger::new();
740 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
742 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
743 assert_eq!(*payer.attempts.borrow(), 1);
745 let event = Event::PaymentPathFailed {
747 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
748 network_update: None,
749 rejected_by_dest: false,
750 all_paths_failed: true,
751 path: TestRouter::path_for_value(final_value_msat),
752 short_channel_id: None,
753 retry: Some(TestRouter::retry_for_invoice(&invoice)),
755 invoice_payer.handle_event(&event);
756 assert_eq!(*event_handled.borrow(), false);
757 assert_eq!(*payer.attempts.borrow(), 2);
759 let event = Event::PaymentPathFailed {
761 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
762 network_update: None,
763 rejected_by_dest: false,
764 all_paths_failed: false,
765 path: TestRouter::path_for_value(final_value_msat / 2),
766 short_channel_id: None,
767 retry: Some(RouteParameters {
768 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
771 invoice_payer.handle_event(&event);
772 assert_eq!(*event_handled.borrow(), false);
773 assert_eq!(*payer.attempts.borrow(), 3);
775 invoice_payer.handle_event(&event);
776 assert_eq!(*event_handled.borrow(), true);
777 assert_eq!(*payer.attempts.borrow(), 3);
781 fn fails_paying_invoice_with_missing_retry_params() {
782 let event_handled = core::cell::RefCell::new(false);
783 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
785 let payment_preimage = PaymentPreimage([1; 32]);
786 let invoice = invoice(payment_preimage);
787 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
789 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
790 let router = TestRouter {};
791 let scorer = RefCell::new(TestScorer::new());
792 let logger = TestLogger::new();
794 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
796 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
797 assert_eq!(*payer.attempts.borrow(), 1);
799 let event = Event::PaymentPathFailed {
801 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
802 network_update: None,
803 rejected_by_dest: false,
804 all_paths_failed: false,
806 short_channel_id: None,
809 invoice_payer.handle_event(&event);
810 assert_eq!(*event_handled.borrow(), true);
811 assert_eq!(*payer.attempts.borrow(), 1);
815 fn fails_paying_invoice_after_expiration() {
816 let event_handled = core::cell::RefCell::new(false);
817 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
819 let payer = TestPayer::new();
820 let router = TestRouter {};
821 let scorer = RefCell::new(TestScorer::new());
822 let logger = TestLogger::new();
824 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
826 let payment_preimage = PaymentPreimage([1; 32]);
827 let invoice = expired_invoice(payment_preimage);
828 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
829 assert_eq!(msg, "Invoice expired prior to send");
830 } else { panic!("Expected Invoice Error"); }
834 fn fails_retrying_invoice_after_expiration() {
835 let event_handled = core::cell::RefCell::new(false);
836 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
838 let payment_preimage = PaymentPreimage([1; 32]);
839 let invoice = invoice(payment_preimage);
840 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
842 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
843 let router = TestRouter {};
844 let scorer = RefCell::new(TestScorer::new());
845 let logger = TestLogger::new();
847 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
849 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
850 assert_eq!(*payer.attempts.borrow(), 1);
852 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
853 retry_data.payee.expiry_time = Some(SystemTime::now()
854 .checked_sub(Duration::from_secs(2)).unwrap()
855 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
856 let event = Event::PaymentPathFailed {
858 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
859 network_update: None,
860 rejected_by_dest: false,
861 all_paths_failed: false,
863 short_channel_id: None,
864 retry: Some(retry_data),
866 invoice_payer.handle_event(&event);
867 assert_eq!(*event_handled.borrow(), true);
868 assert_eq!(*payer.attempts.borrow(), 1);
872 fn fails_paying_invoice_after_retry_error() {
873 let event_handled = core::cell::RefCell::new(false);
874 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
876 let payment_preimage = PaymentPreimage([1; 32]);
877 let invoice = invoice(payment_preimage);
878 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
880 let payer = TestPayer::new()
882 .expect_send(Amount::ForInvoice(final_value_msat))
883 .expect_send(Amount::OnRetry(final_value_msat / 2));
884 let router = TestRouter {};
885 let scorer = RefCell::new(TestScorer::new());
886 let logger = TestLogger::new();
888 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
890 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
891 assert_eq!(*payer.attempts.borrow(), 1);
893 let event = Event::PaymentPathFailed {
895 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
896 network_update: None,
897 rejected_by_dest: false,
898 all_paths_failed: false,
899 path: TestRouter::path_for_value(final_value_msat / 2),
900 short_channel_id: None,
901 retry: Some(TestRouter::retry_for_invoice(&invoice)),
903 invoice_payer.handle_event(&event);
904 assert_eq!(*event_handled.borrow(), true);
905 assert_eq!(*payer.attempts.borrow(), 2);
909 fn fails_paying_invoice_after_rejected_by_payee() {
910 let event_handled = core::cell::RefCell::new(false);
911 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
913 let payment_preimage = PaymentPreimage([1; 32]);
914 let invoice = invoice(payment_preimage);
915 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
917 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
918 let router = TestRouter {};
919 let scorer = RefCell::new(TestScorer::new());
920 let logger = TestLogger::new();
922 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
924 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
925 assert_eq!(*payer.attempts.borrow(), 1);
927 let event = Event::PaymentPathFailed {
929 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
930 network_update: None,
931 rejected_by_dest: true,
932 all_paths_failed: false,
934 short_channel_id: None,
935 retry: Some(TestRouter::retry_for_invoice(&invoice)),
937 invoice_payer.handle_event(&event);
938 assert_eq!(*event_handled.borrow(), true);
939 assert_eq!(*payer.attempts.borrow(), 1);
943 fn fails_repaying_invoice_with_pending_payment() {
944 let event_handled = core::cell::RefCell::new(false);
945 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
947 let payment_preimage = PaymentPreimage([1; 32]);
948 let invoice = invoice(payment_preimage);
949 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
951 let payer = TestPayer::new()
952 .expect_send(Amount::ForInvoice(final_value_msat))
953 .expect_send(Amount::ForInvoice(final_value_msat));
954 let router = TestRouter {};
955 let scorer = RefCell::new(TestScorer::new());
956 let logger = TestLogger::new();
958 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
960 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
962 // Cannot repay an invoice pending payment.
963 match invoice_payer.pay_invoice(&invoice) {
964 Err(PaymentError::Invoice("payment pending")) => {},
965 Err(_) => panic!("unexpected error"),
966 Ok(_) => panic!("expected invoice error"),
969 // Can repay an invoice once cleared from cache.
970 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
971 invoice_payer.remove_cached_payment(&payment_hash);
972 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
974 // Cannot retry paying an invoice if cleared from cache.
975 invoice_payer.remove_cached_payment(&payment_hash);
976 let event = Event::PaymentPathFailed {
979 network_update: None,
980 rejected_by_dest: false,
981 all_paths_failed: false,
983 short_channel_id: None,
984 retry: Some(TestRouter::retry_for_invoice(&invoice)),
986 invoice_payer.handle_event(&event);
987 assert_eq!(*event_handled.borrow(), true);
991 fn fails_paying_invoice_with_routing_errors() {
992 let payer = TestPayer::new();
993 let router = FailingRouter {};
994 let scorer = RefCell::new(TestScorer::new());
995 let logger = TestLogger::new();
997 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
999 let payment_preimage = PaymentPreimage([1; 32]);
1000 let invoice = invoice(payment_preimage);
1001 match invoice_payer.pay_invoice(&invoice) {
1002 Err(PaymentError::Routing(_)) => {},
1003 Err(_) => panic!("unexpected error"),
1004 Ok(_) => panic!("expected routing error"),
1009 fn fails_paying_invoice_with_sending_errors() {
1010 let payment_preimage = PaymentPreimage([1; 32]);
1011 let invoice = invoice(payment_preimage);
1012 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1014 let payer = TestPayer::new()
1015 .fails_on_attempt(1)
1016 .expect_send(Amount::ForInvoice(final_value_msat));
1017 let router = TestRouter {};
1018 let scorer = RefCell::new(TestScorer::new());
1019 let logger = TestLogger::new();
1021 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1023 match invoice_payer.pay_invoice(&invoice) {
1024 Err(PaymentError::Sending(_)) => {},
1025 Err(_) => panic!("unexpected error"),
1026 Ok(_) => panic!("expected sending error"),
1031 fn pays_zero_value_invoice_using_amount() {
1032 let event_handled = core::cell::RefCell::new(false);
1033 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1035 let payment_preimage = PaymentPreimage([1; 32]);
1036 let invoice = zero_value_invoice(payment_preimage);
1037 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1038 let final_value_msat = 100;
1040 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1041 let router = TestRouter {};
1042 let scorer = RefCell::new(TestScorer::new());
1043 let logger = TestLogger::new();
1045 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1048 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1049 assert_eq!(*payer.attempts.borrow(), 1);
1051 invoice_payer.handle_event(&Event::PaymentSent {
1052 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1054 assert_eq!(*event_handled.borrow(), true);
1055 assert_eq!(*payer.attempts.borrow(), 1);
1059 fn fails_paying_zero_value_invoice_with_amount() {
1060 let event_handled = core::cell::RefCell::new(false);
1061 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1063 let payer = TestPayer::new();
1064 let router = TestRouter {};
1065 let scorer = RefCell::new(TestScorer::new());
1066 let logger = TestLogger::new();
1068 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1070 let payment_preimage = PaymentPreimage([1; 32]);
1071 let invoice = invoice(payment_preimage);
1073 // Cannot repay an invoice pending payment.
1074 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1075 Err(PaymentError::Invoice("amount unexpected")) => {},
1076 Err(_) => panic!("unexpected error"),
1077 Ok(_) => panic!("expected invoice error"),
1082 fn pays_pubkey_with_amount() {
1083 let event_handled = core::cell::RefCell::new(false);
1084 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1086 let pubkey = pubkey();
1087 let payment_preimage = PaymentPreimage([1; 32]);
1088 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1089 let final_value_msat = 100;
1090 let final_cltv_expiry_delta = 42;
1092 let payer = TestPayer::new()
1093 .expect_send(Amount::Spontaneous(final_value_msat))
1094 .expect_send(Amount::OnRetry(final_value_msat));
1095 let router = TestRouter {};
1096 let scorer = RefCell::new(TestScorer::new());
1097 let logger = TestLogger::new();
1099 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1101 let payment_id = Some(invoice_payer.pay_pubkey(
1102 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1104 assert_eq!(*payer.attempts.borrow(), 1);
1106 let retry = RouteParameters {
1107 payee: Payee::for_keysend(pubkey),
1109 final_cltv_expiry_delta,
1111 let event = Event::PaymentPathFailed {
1114 network_update: None,
1115 rejected_by_dest: false,
1116 all_paths_failed: false,
1118 short_channel_id: None,
1121 invoice_payer.handle_event(&event);
1122 assert_eq!(*event_handled.borrow(), false);
1123 assert_eq!(*payer.attempts.borrow(), 2);
1125 invoice_payer.handle_event(&Event::PaymentSent {
1126 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1128 assert_eq!(*event_handled.borrow(), true);
1129 assert_eq!(*payer.attempts.borrow(), 2);
1133 fn scores_failed_channel() {
1134 let event_handled = core::cell::RefCell::new(false);
1135 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1137 let payment_preimage = PaymentPreimage([1; 32]);
1138 let invoice = invoice(payment_preimage);
1139 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1140 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1141 let path = TestRouter::path_for_value(final_value_msat);
1142 let short_channel_id = Some(path[0].short_channel_id);
1144 // Expect that scorer is given short_channel_id upon handling the event.
1145 let payer = TestPayer::new()
1146 .expect_send(Amount::ForInvoice(final_value_msat))
1147 .expect_send(Amount::OnRetry(final_value_msat / 2));
1148 let router = TestRouter {};
1149 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1150 path: path.clone(), short_channel_id: path[0].short_channel_id,
1152 let logger = TestLogger::new();
1154 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1156 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1157 let event = Event::PaymentPathFailed {
1160 network_update: None,
1161 rejected_by_dest: false,
1162 all_paths_failed: false,
1165 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1167 invoice_payer.handle_event(&event);
1171 fn scores_successful_channels() {
1172 let event_handled = core::cell::RefCell::new(false);
1173 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1175 let payment_preimage = PaymentPreimage([1; 32]);
1176 let invoice = invoice(payment_preimage);
1177 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1178 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1179 let route = TestRouter::route_for_value(final_value_msat);
1181 // Expect that scorer is given short_channel_id upon handling the event.
1182 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1183 let router = TestRouter {};
1184 let scorer = RefCell::new(TestScorer::new()
1185 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1186 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1188 let logger = TestLogger::new();
1190 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1192 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1193 let event = Event::PaymentPathSuccessful {
1194 payment_id, payment_hash, path: route.paths[0].clone()
1196 invoice_payer.handle_event(&event);
1197 let event = Event::PaymentPathSuccessful {
1198 payment_id, payment_hash, path: route.paths[1].clone()
1200 invoice_payer.handle_event(&event);
1206 fn route_for_value(final_value_msat: u64) -> Route {
1210 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1211 channel_features: ChannelFeatures::empty(),
1212 node_features: NodeFeatures::empty(),
1213 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1216 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1217 channel_features: ChannelFeatures::empty(),
1218 node_features: NodeFeatures::empty(),
1219 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1226 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1227 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1230 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1231 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1232 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1233 .with_route_hints(invoice.route_hints());
1234 if let Some(features) = invoice.features() {
1235 payee = payee.with_features(features.clone());
1237 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1241 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1246 impl<S: Score> Router<S> for TestRouter {
1248 &self, _payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
1249 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1250 ) -> Result<Route, LightningError> {
1252 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1257 struct FailingRouter;
1259 impl<S: Score> Router<S> for FailingRouter {
1261 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1262 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1263 ) -> Result<Route, LightningError> {
1264 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1269 expectations: Option<VecDeque<PaymentPath>>,
1274 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1275 Success { path: Vec<RouteHop> },
1285 fn expect(mut self, expectation: PaymentPath) -> Self {
1286 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1292 impl lightning::util::ser::Writeable for TestScorer {
1293 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1296 impl Score for TestScorer {
1297 fn channel_penalty_msat(
1298 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: Option<u64>, _source: &NodeId, _target: &NodeId
1301 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1302 if let Some(expectations) = &mut self.expectations {
1303 match expectations.pop_front() {
1304 Some(PaymentPath::Failure { path, short_channel_id }) => {
1305 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1306 assert_eq!(actual_short_channel_id, short_channel_id);
1308 Some(PaymentPath::Success { path }) => {
1309 panic!("Unexpected successful payment path: {:?}", path)
1311 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1316 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1317 if let Some(expectations) = &mut self.expectations {
1318 match expectations.pop_front() {
1319 Some(PaymentPath::Failure { path, .. }) => {
1320 panic!("Unexpected payment path failure: {:?}", path)
1322 Some(PaymentPath::Success { path }) => {
1323 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1325 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1331 impl Drop for TestScorer {
1332 fn drop(&mut self) {
1333 if std::thread::panicking() {
1337 if let Some(expectations) = &self.expectations {
1338 if !expectations.is_empty() {
1339 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1346 expectations: core::cell::RefCell<VecDeque<Amount>>,
1347 attempts: core::cell::RefCell<usize>,
1348 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1351 #[derive(Clone, Debug, PartialEq, Eq)]
1358 struct OnAttempt(usize);
1363 expectations: core::cell::RefCell::new(VecDeque::new()),
1364 attempts: core::cell::RefCell::new(0),
1365 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1369 fn expect_send(self, value_msat: Amount) -> Self {
1370 self.expectations.borrow_mut().push_back(value_msat);
1374 fn fails_on_attempt(self, attempt: usize) -> Self {
1375 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1376 self.fails_with(failure, OnAttempt(attempt))
1379 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1380 self.fails_with(PaymentSendFailure::PartialFailure {
1382 failed_paths_retry: Some(retry),
1383 payment_id: PaymentId([1; 32]),
1387 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1388 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1392 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1393 let mut attempts = self.attempts.borrow_mut();
1396 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1397 Some(failure) => Err(failure),
1398 None => Ok(PaymentId([1; 32])),
1402 fn check_value_msats(&self, actual_value_msats: Amount) {
1403 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1404 if let Some(expected_value_msats) = expected_value_msats {
1405 assert_eq!(actual_value_msats, expected_value_msats);
1407 panic!("Unexpected amount: {:?}", actual_value_msats);
1412 impl Drop for TestPayer {
1413 fn drop(&mut self) {
1414 if std::thread::panicking() {
1418 if !self.expectations.borrow().is_empty() {
1419 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1424 impl Payer for TestPayer {
1425 fn node_id(&self) -> PublicKey {
1426 let secp_ctx = Secp256k1::new();
1427 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1430 fn first_hops(&self) -> Vec<ChannelDetails> {
1435 &self, route: &Route, _payment_hash: PaymentHash,
1436 _payment_secret: &Option<PaymentSecret>
1437 ) -> Result<PaymentId, PaymentSendFailure> {
1438 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1439 self.check_attempts()
1442 fn send_spontaneous_payment(
1443 &self, route: &Route, _payment_preimage: PaymentPreimage,
1444 ) -> Result<PaymentId, PaymentSendFailure> {
1445 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1446 self.check_attempts()
1450 &self, route: &Route, _payment_id: PaymentId
1451 ) -> Result<(), PaymentSendFailure> {
1452 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1453 self.check_attempts().map(|_| ())
1456 fn abandon_payment(&self, _payment_id: PaymentId) { }
1459 // *** Full Featured Functional Tests with a Real ChannelManager ***
1460 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1462 impl<S: Score> Router<S> for ManualRouter {
1464 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1465 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1466 ) -> Result<Route, LightningError> {
1467 self.0.borrow_mut().pop_front().unwrap()
1471 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1472 self.0.borrow_mut().push_back(result);
1475 impl Drop for ManualRouter {
1476 fn drop(&mut self) {
1477 if std::thread::panicking() {
1480 assert!(self.0.borrow_mut().is_empty());
1485 fn retry_multi_path_single_failed_payment() {
1486 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1487 let chanmon_cfgs = create_chanmon_cfgs(2);
1488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1490 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1493 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1494 let chans = nodes[0].node.list_usable_channels();
1495 let mut route = Route {
1498 pubkey: nodes[1].node.get_our_node_id(),
1499 node_features: NodeFeatures::known(),
1500 short_channel_id: chans[0].short_channel_id.unwrap(),
1501 channel_features: ChannelFeatures::known(),
1503 cltv_expiry_delta: 100,
1506 pubkey: nodes[1].node.get_our_node_id(),
1507 node_features: NodeFeatures::known(),
1508 short_channel_id: chans[1].short_channel_id.unwrap(),
1509 channel_features: ChannelFeatures::known(),
1510 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1511 cltv_expiry_delta: 100,
1514 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1516 let router = ManualRouter(RefCell::new(VecDeque::new()));
1517 router.expect_find_route(Ok(route.clone()));
1518 // On retry, split the payment across both channels.
1519 route.paths[0][0].fee_msat = 50_000_001;
1520 route.paths[1][0].fee_msat = 50_000_000;
1521 router.expect_find_route(Ok(route.clone()));
1523 let event_handler = |_: &_| { panic!(); };
1524 let scorer = RefCell::new(TestScorer::new());
1525 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1527 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1528 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1530 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1531 assert_eq!(htlc_msgs.len(), 2);
1532 check_added_monitors!(nodes[0], 2);
1536 fn immediate_retry_on_failure() {
1537 // Tests that we can/will retry immediately after a failure
1538 let chanmon_cfgs = create_chanmon_cfgs(2);
1539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1543 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1544 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1545 let chans = nodes[0].node.list_usable_channels();
1546 let mut route = Route {
1549 pubkey: nodes[1].node.get_our_node_id(),
1550 node_features: NodeFeatures::known(),
1551 short_channel_id: chans[0].short_channel_id.unwrap(),
1552 channel_features: ChannelFeatures::known(),
1553 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1554 cltv_expiry_delta: 100,
1557 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1559 let router = ManualRouter(RefCell::new(VecDeque::new()));
1560 router.expect_find_route(Ok(route.clone()));
1561 // On retry, split the payment across both channels.
1562 route.paths.push(route.paths[0].clone());
1563 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1564 route.paths[0][0].fee_msat = 50_000_000;
1565 route.paths[1][0].fee_msat = 50_000_001;
1566 router.expect_find_route(Ok(route.clone()));
1568 let event_handler = |_: &_| { panic!(); };
1569 let scorer = RefCell::new(TestScorer::new());
1570 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1572 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1573 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1575 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1576 assert_eq!(htlc_msgs.len(), 2);
1577 check_added_monitors!(nodes[0], 2);
1581 fn no_extra_retries_on_back_to_back_fail() {
1582 // In a previous release, we had a race where we may exceed the payment retry count if we
1583 // get two failures in a row with the second having `all_paths_failed` set.
1584 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1585 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1586 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1587 // pending which we will see later. Thus, when we previously removed the retry tracking map
1588 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1589 // retry entry even though more events for the same payment were still pending. This led to
1590 // us retrying a payment again even though we'd already given up on it.
1592 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1593 // is used to remove the payment retry counter entries instead. This tests for the specific
1594 // excess-retry case while also testing `PaymentFailed` generation.
1596 let chanmon_cfgs = create_chanmon_cfgs(3);
1597 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1598 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1599 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1601 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;
1602 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;
1604 let mut route = Route {
1607 pubkey: nodes[1].node.get_our_node_id(),
1608 node_features: NodeFeatures::known(),
1609 short_channel_id: chan_1_scid,
1610 channel_features: ChannelFeatures::known(),
1612 cltv_expiry_delta: 100,
1614 pubkey: nodes[2].node.get_our_node_id(),
1615 node_features: NodeFeatures::known(),
1616 short_channel_id: chan_2_scid,
1617 channel_features: ChannelFeatures::known(),
1618 fee_msat: 100_000_000,
1619 cltv_expiry_delta: 100,
1622 pubkey: nodes[1].node.get_our_node_id(),
1623 node_features: NodeFeatures::known(),
1624 short_channel_id: chan_1_scid,
1625 channel_features: ChannelFeatures::known(),
1627 cltv_expiry_delta: 100,
1629 pubkey: nodes[2].node.get_our_node_id(),
1630 node_features: NodeFeatures::known(),
1631 short_channel_id: chan_2_scid,
1632 channel_features: ChannelFeatures::known(),
1633 fee_msat: 100_000_000,
1634 cltv_expiry_delta: 100,
1637 payee: Some(Payee::from_node_id(nodes[2].node.get_our_node_id())),
1639 let router = ManualRouter(RefCell::new(VecDeque::new()));
1640 router.expect_find_route(Ok(route.clone()));
1641 // On retry, we'll only be asked for one path
1642 route.paths.remove(1);
1643 router.expect_find_route(Ok(route.clone()));
1645 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1646 let event_handler = |event: &Event| {
1647 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1648 event_checker(event);
1650 let scorer = RefCell::new(TestScorer::new());
1651 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1653 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1654 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1656 let htlc_updates = SendEvent::from_node(&nodes[0]);
1657 check_added_monitors!(nodes[0], 1);
1658 assert_eq!(htlc_updates.msgs.len(), 1);
1660 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1661 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1662 check_added_monitors!(nodes[1], 1);
1663 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1665 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1666 check_added_monitors!(nodes[0], 1);
1667 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1669 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1670 check_added_monitors!(nodes[0], 1);
1671 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1673 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1674 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1675 check_added_monitors!(nodes[1], 1);
1676 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1678 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1679 check_added_monitors!(nodes[1], 1);
1680 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1682 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1683 check_added_monitors!(nodes[0], 1);
1685 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1686 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1687 check_added_monitors!(nodes[0], 1);
1688 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1690 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1691 check_added_monitors!(nodes[1], 1);
1692 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1694 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1695 check_added_monitors!(nodes[1], 1);
1696 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1698 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1699 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1700 check_added_monitors!(nodes[0], 1);
1702 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1703 check_added_monitors!(nodes[0], 1);
1704 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1706 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1707 check_added_monitors!(nodes[1], 1);
1708 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1709 check_added_monitors!(nodes[1], 1);
1710 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1712 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1713 check_added_monitors!(nodes[0], 1);
1715 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1716 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1717 // with it set. The first event will use up the only retry we are allowed, with the second
1718 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1719 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1720 // if the final HTLC failed.
1721 expected_events.borrow_mut().push_back(&|ev: &Event| {
1722 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1723 assert!(!rejected_by_dest);
1724 assert!(all_paths_failed);
1725 } else { panic!("Unexpected event"); }
1727 nodes[0].node.process_pending_events(&invoice_payer);
1728 assert!(expected_events.borrow().is_empty());
1730 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1731 check_added_monitors!(nodes[0], 1);
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1734 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1735 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1736 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1737 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1739 expected_events.borrow_mut().push_back(&|ev: &Event| {
1740 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1741 assert!(!rejected_by_dest);
1742 assert!(all_paths_failed);
1743 } else { panic!("Unexpected event"); }
1745 expected_events.borrow_mut().push_back(&|ev: &Event| {
1746 if let Event::PaymentFailed { .. } = ev {
1747 } else { panic!("Unexpected event"); }
1749 nodes[0].node.process_pending_events(&invoice_payer);
1750 assert!(expected_events.borrow().is_empty());