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 //! # #[cfg(feature = "no-std")]
36 //! # extern crate core2;
38 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
39 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
40 //! # use lightning::ln::msgs::LightningError;
41 //! # use lightning::routing::gossip::NodeId;
42 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
43 //! # use lightning::routing::scoring::{ChannelUsage, Score};
44 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # use lightning::util::ser::{Writeable, Writer};
47 //! # use lightning_invoice::Invoice;
48 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, Router};
49 //! # use secp256k1::PublicKey;
50 //! # use std::cell::RefCell;
51 //! # use std::ops::Deref;
53 //! # #[cfg(not(feature = "std"))]
55 //! # #[cfg(feature = "std")]
58 //! # struct FakeEventProvider {}
59 //! # impl EventsProvider for FakeEventProvider {
60 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
63 //! # struct FakePayer {}
64 //! # impl Payer for FakePayer {
65 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
66 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
67 //! # fn send_payment(
68 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
69 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
70 //! # fn send_spontaneous_payment(
71 //! # &self, route: &Route, payment_preimage: PaymentPreimage
72 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
73 //! # fn retry_payment(
74 //! # &self, route: &Route, payment_id: PaymentId
75 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
76 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
79 //! # struct FakeRouter {}
80 //! # impl<S: Score> Router<S> for FakeRouter {
82 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
83 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
84 //! # ) -> Result<Route, LightningError> { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
101 //! # struct FakeLogger {}
102 //! # impl Logger for FakeLogger {
103 //! # fn log(&self, record: &Record) { unimplemented!() }
107 //! let event_handler = |event: &Event| {
109 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
110 //! Event::PaymentSent { .. } => println!("payment successful"),
114 //! # let payer = FakePayer {};
115 //! # let router = FakeRouter {};
116 //! # let scorer = RefCell::new(FakeScorer {});
117 //! # let logger = FakeLogger {};
118 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
120 //! let invoice = "...";
121 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
122 //! invoice_payer.pay_invoice(&invoice).unwrap();
124 //! # let event_provider = FakeEventProvider {};
126 //! event_provider.process_pending_events(&invoice_payer);
134 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
135 //! as updates to the network graph or changes to channel scores should be applied prior to
136 //! retries, typically by way of composing [`EventHandler`]s accordingly.
140 use bitcoin_hashes::Hash;
141 use bitcoin_hashes::sha256::Hash as Sha256;
143 use crate::prelude::*;
144 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
145 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
146 use lightning::ln::msgs::LightningError;
147 use lightning::routing::scoring::{LockableScore, Score};
148 use lightning::routing::router::{PaymentParameters, Route, RouteParameters};
149 use lightning::util::events::{Event, EventHandler};
150 use lightning::util::logger::Logger;
151 use time_utils::Time;
152 use crate::sync::Mutex;
154 use secp256k1::PublicKey;
157 use core::fmt::{Debug, Display, Formatter};
158 use core::ops::Deref;
159 use core::time::Duration;
160 #[cfg(feature = "std")]
161 use std::time::SystemTime;
163 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
165 /// See [module-level documentation] for details.
167 /// [module-level documentation]: crate::payment
168 pub type InvoicePayer<P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, ConfiguredTime>;
170 #[cfg(not(feature = "no-std"))]
171 type ConfiguredTime = std::time::Instant;
172 #[cfg(feature = "no-std")]
174 #[cfg(feature = "no-std")]
175 type ConfiguredTime = time_utils::Eternity;
177 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
178 pub struct InvoicePayerUsingTime<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time>
181 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
182 S::Target: for <'a> LockableScore<'a>,
190 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
191 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
195 /// Storing minimal payment attempts information required for determining if a outbound payment can
197 #[derive(Clone, Copy)]
198 struct PaymentAttempts<T: Time> {
199 /// This count will be incremented only after the result of the attempt is known. When it's 0,
200 /// it means the result of the first attempt is now known yet.
202 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
203 first_attempted_at: T
206 impl<T: Time> PaymentAttempts<T> {
210 first_attempted_at: T::now()
215 impl<T: Time> Display for PaymentAttempts<T> {
216 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
217 #[cfg(feature = "no-std")]
218 return write!( f, "attempts: {}", self.count);
219 #[cfg(not(feature = "no-std"))]
222 "attempts: {}, duration: {}s",
224 T::now().duration_since(self.first_attempted_at).as_secs()
229 /// A trait defining behavior of an [`Invoice`] payer.
231 /// Returns the payer's node id.
232 fn node_id(&self) -> PublicKey;
234 /// Returns the payer's channels.
235 fn first_hops(&self) -> Vec<ChannelDetails>;
237 /// Sends a payment over the Lightning Network using the given [`Route`].
239 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
240 ) -> Result<PaymentId, PaymentSendFailure>;
242 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
243 fn send_spontaneous_payment(
244 &self, route: &Route, payment_preimage: PaymentPreimage
245 ) -> Result<PaymentId, PaymentSendFailure>;
247 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
248 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
250 /// Signals that no further retries for the given payment will occur.
251 fn abandon_payment(&self, payment_id: PaymentId);
254 /// A trait defining behavior for routing an [`Invoice`] payment.
255 pub trait Router<S: Score> {
256 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
258 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
259 first_hops: Option<&[&ChannelDetails]>, scorer: &S
260 ) -> Result<Route, LightningError>;
263 /// Strategies available to retry payment path failures for an [`Invoice`].
265 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
267 /// Max number of attempts to retry payment.
269 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
270 /// payments, if this is less than the total number of paths, we will never even retry all of the
273 #[cfg(feature = "std")]
274 /// Time elapsed before abandoning retries for a payment.
279 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
280 match (self, attempts) {
281 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
282 max_retry_count >= &count
284 #[cfg(feature = "std")]
285 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
286 *max_duration >= T::now().duration_since(*first_attempted_at),
291 /// An error that may occur when making a payment.
292 #[derive(Clone, Debug)]
293 pub enum PaymentError {
294 /// An error resulting from the provided [`Invoice`] or payment hash.
295 Invoice(&'static str),
296 /// An error occurring when finding a route.
297 Routing(LightningError),
298 /// An error occurring when sending a payment.
299 Sending(PaymentSendFailure),
302 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, S, L, E, T>
305 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
306 S::Target: for <'a> LockableScore<'a>,
309 /// Creates an invoice payer that retries failed payment paths.
311 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
312 /// `retry` has been exceeded for a given [`Invoice`].
314 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry: Retry
322 payment_cache: Mutex::new(HashMap::new()),
327 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
329 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
330 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
332 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
333 if invoice.amount_milli_satoshis().is_none() {
334 Err(PaymentError::Invoice("amount missing"))
336 self.pay_invoice_using_amount(invoice, None)
340 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
341 /// case a retry is needed.
343 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
344 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
346 pub fn pay_zero_value_invoice(
347 &self, invoice: &Invoice, amount_msats: u64
348 ) -> Result<PaymentId, PaymentError> {
349 if invoice.amount_milli_satoshis().is_some() {
350 Err(PaymentError::Invoice("amount unexpected"))
352 self.pay_invoice_using_amount(invoice, Some(amount_msats))
356 fn pay_invoice_using_amount(
357 &self, invoice: &Invoice, amount_msats: Option<u64>
358 ) -> Result<PaymentId, PaymentError> {
359 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
361 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
362 match self.payment_cache.lock().unwrap().entry(payment_hash) {
363 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
364 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
367 let payment_secret = Some(invoice.payment_secret().clone());
368 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
369 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
370 .with_route_hints(invoice.route_hints());
371 if let Some(features) = invoice.features() {
372 payment_params = payment_params.with_features(features.clone());
374 let route_params = RouteParameters {
376 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
377 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
380 let send_payment = |route: &Route| {
381 self.payer.send_payment(route, payment_hash, &payment_secret)
384 self.pay_internal(&route_params, payment_hash, send_payment)
385 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
388 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
389 /// case a retry is needed.
391 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
392 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
394 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
395 final_cltv_expiry_delta: u32
396 ) -> Result<PaymentId, PaymentError> {
397 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
398 match self.payment_cache.lock().unwrap().entry(payment_hash) {
399 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
400 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
403 let route_params = RouteParameters {
404 payment_params: PaymentParameters::for_keysend(pubkey),
405 final_value_msat: amount_msats,
406 final_cltv_expiry_delta,
409 let send_payment = |route: &Route| {
410 self.payer.send_spontaneous_payment(route, payment_preimage)
412 self.pay_internal(&route_params, payment_hash, send_payment)
413 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
416 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
417 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
418 ) -> Result<PaymentId, PaymentError> {
419 #[cfg(feature = "std")] {
420 if has_expired(params) {
421 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
422 return Err(PaymentError::Invoice("Invoice expired prior to send"));
426 let payer = self.payer.node_id();
427 let first_hops = self.payer.first_hops();
428 let route = self.router.find_route(
429 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
431 ).map_err(|e| PaymentError::Routing(e))?;
433 match send_payment(&route) {
434 Ok(payment_id) => Ok(payment_id),
436 PaymentSendFailure::ParameterError(_) => Err(e),
437 PaymentSendFailure::PathParameterError(_) => Err(e),
438 PaymentSendFailure::AllFailedRetrySafe(_) => {
439 let mut payment_cache = self.payment_cache.lock().unwrap();
440 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
441 payment_attempts.count += 1;
442 if self.retry.is_retryable_now(payment_attempts) {
443 core::mem::drop(payment_cache);
444 Ok(self.pay_internal(params, payment_hash, send_payment)?)
449 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
450 if let Some(retry_data) = failed_paths_retry {
451 // Some paths were sent, even if we failed to send the full MPP value our
452 // recipient may misbehave and claim the funds, at which point we have to
453 // consider the payment sent, so return `Ok()` here, ignoring any retry
455 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
458 // This may happen if we send a payment and some paths fail, but
459 // only due to a temporary monitor failure or the like, implying
460 // they're really in-flight, but we haven't sent the initial
461 // HTLC-Add messages yet.
466 }.map_err(|e| PaymentError::Sending(e))
470 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
471 ) -> Result<(), ()> {
473 *self.payment_cache.lock().unwrap().entry(payment_hash)
474 .and_modify(|attempts| attempts.count += 1)
475 .or_insert(PaymentAttempts {
477 first_attempted_at: T::now()
480 if !self.retry.is_retryable_now(&attempts) {
481 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
485 #[cfg(feature = "std")] {
486 if has_expired(params) {
487 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
492 let payer = self.payer.node_id();
493 let first_hops = self.payer.first_hops();
494 let route = self.router.find_route(
495 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
499 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
503 match self.payer.retry_payment(&route.unwrap(), payment_id) {
505 Err(PaymentSendFailure::ParameterError(_)) |
506 Err(PaymentSendFailure::PathParameterError(_)) => {
507 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
510 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
511 self.retry_payment(payment_id, payment_hash, params)
513 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
514 if let Some(retry) = failed_paths_retry {
515 // Always return Ok for the same reason as noted in pay_internal.
516 let _ = self.retry_payment(payment_id, payment_hash, &retry);
523 /// Removes the payment cached by the given payment hash.
525 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
526 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
527 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
528 self.payment_cache.lock().unwrap().remove(payment_hash);
532 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
533 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
536 #[cfg(feature = "std")]
537 fn has_expired(route_params: &RouteParameters) -> bool {
538 if let Some(expiry_time) = route_params.payment_params.expiry_time {
539 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
543 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, S, L, E, T>
546 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
547 S::Target: for <'a> LockableScore<'a>,
550 fn handle_event(&self, event: &Event) {
552 Event::PaymentPathFailed {
553 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
555 if let Some(short_channel_id) = short_channel_id {
556 let path = path.iter().collect::<Vec<_>>();
557 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
560 if payment_id.is_none() {
561 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
562 } else if *rejected_by_dest {
563 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
564 self.payer.abandon_payment(payment_id.unwrap());
565 } else if retry.is_none() {
566 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
567 self.payer.abandon_payment(payment_id.unwrap());
568 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
569 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
572 self.payer.abandon_payment(payment_id.unwrap());
575 Event::PaymentFailed { payment_hash, .. } => {
576 self.remove_cached_payment(&payment_hash);
578 Event::PaymentPathSuccessful { path, .. } => {
579 let path = path.iter().collect::<Vec<_>>();
580 self.scorer.lock().payment_path_successful(&path);
582 Event::PaymentSent { payment_hash, .. } => {
583 let mut payment_cache = self.payment_cache.lock().unwrap();
584 let attempts = payment_cache
585 .remove(payment_hash)
586 .map_or(1, |attempts| attempts.count + 1);
587 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
589 Event::ProbeSuccessful { payment_hash, path, .. } => {
590 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
591 let path = path.iter().collect::<Vec<_>>();
592 self.scorer.lock().probe_successful(&path);
594 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
595 if let Some(short_channel_id) = short_channel_id {
596 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
597 let path = path.iter().collect::<Vec<_>>();
598 self.scorer.lock().probe_failed(&path, *short_channel_id);
604 // Delegate to the decorated event handler unless the payment is retried.
605 self.event_handler.handle_event(event)
612 use crate::{InvoiceBuilder, Currency};
613 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
614 use bitcoin_hashes::sha256::Hash as Sha256;
615 use lightning::ln::PaymentPreimage;
616 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
617 use lightning::ln::functional_test_utils::*;
618 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
619 use lightning::routing::gossip::NodeId;
620 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
621 use lightning::routing::scoring::ChannelUsage;
622 use lightning::util::test_utils::TestLogger;
623 use lightning::util::errors::APIError;
624 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
625 use secp256k1::{SecretKey, PublicKey, Secp256k1};
626 use std::cell::RefCell;
627 use std::collections::VecDeque;
628 use std::time::{SystemTime, Duration};
629 use time_utils::tests::SinceEpoch;
630 use DEFAULT_EXPIRY_TIME;
632 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
633 let payment_hash = Sha256::hash(&payment_preimage.0);
634 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
636 InvoiceBuilder::new(Currency::Bitcoin)
637 .description("test".into())
638 .payment_hash(payment_hash)
639 .payment_secret(PaymentSecret([0; 32]))
640 .duration_since_epoch(duration_since_epoch())
641 .min_final_cltv_expiry(144)
642 .amount_milli_satoshis(128)
643 .build_signed(|hash| {
644 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
649 fn duration_since_epoch() -> Duration {
650 #[cfg(feature = "std")]
651 let duration_since_epoch =
652 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
653 #[cfg(not(feature = "std"))]
654 let duration_since_epoch = Duration::from_secs(1234567);
658 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
659 let payment_hash = Sha256::hash(&payment_preimage.0);
660 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
662 InvoiceBuilder::new(Currency::Bitcoin)
663 .description("test".into())
664 .payment_hash(payment_hash)
665 .payment_secret(PaymentSecret([0; 32]))
666 .duration_since_epoch(duration_since_epoch())
667 .min_final_cltv_expiry(144)
668 .build_signed(|hash| {
669 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
674 #[cfg(feature = "std")]
675 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
676 let payment_hash = Sha256::hash(&payment_preimage.0);
677 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
678 let duration = duration_since_epoch()
679 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
681 InvoiceBuilder::new(Currency::Bitcoin)
682 .description("test".into())
683 .payment_hash(payment_hash)
684 .payment_secret(PaymentSecret([0; 32]))
685 .duration_since_epoch(duration)
686 .min_final_cltv_expiry(144)
687 .amount_milli_satoshis(128)
688 .build_signed(|hash| {
689 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
694 fn pubkey() -> PublicKey {
695 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
699 fn pays_invoice_on_first_attempt() {
700 let event_handled = core::cell::RefCell::new(false);
701 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
703 let payment_preimage = PaymentPreimage([1; 32]);
704 let invoice = invoice(payment_preimage);
705 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
706 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
708 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
709 let router = TestRouter {};
710 let scorer = RefCell::new(TestScorer::new());
711 let logger = TestLogger::new();
713 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
715 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
716 assert_eq!(*payer.attempts.borrow(), 1);
718 invoice_payer.handle_event(&Event::PaymentSent {
719 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
721 assert_eq!(*event_handled.borrow(), true);
722 assert_eq!(*payer.attempts.borrow(), 1);
726 fn pays_invoice_on_retry() {
727 let event_handled = core::cell::RefCell::new(false);
728 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
730 let payment_preimage = PaymentPreimage([1; 32]);
731 let invoice = invoice(payment_preimage);
732 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
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 let router = TestRouter {};
739 let scorer = RefCell::new(TestScorer::new());
740 let logger = TestLogger::new();
742 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
744 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
745 assert_eq!(*payer.attempts.borrow(), 1);
747 let event = Event::PaymentPathFailed {
750 network_update: None,
751 rejected_by_dest: false,
752 all_paths_failed: false,
753 path: TestRouter::path_for_value(final_value_msat),
754 short_channel_id: None,
755 retry: Some(TestRouter::retry_for_invoice(&invoice)),
757 invoice_payer.handle_event(&event);
758 assert_eq!(*event_handled.borrow(), false);
759 assert_eq!(*payer.attempts.borrow(), 2);
761 invoice_payer.handle_event(&Event::PaymentSent {
762 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
764 assert_eq!(*event_handled.borrow(), true);
765 assert_eq!(*payer.attempts.borrow(), 2);
769 fn pays_invoice_on_partial_failure() {
770 let event_handler = |_: &_| { panic!() };
772 let payment_preimage = PaymentPreimage([1; 32]);
773 let invoice = invoice(payment_preimage);
774 let retry = TestRouter::retry_for_invoice(&invoice);
775 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
777 let payer = TestPayer::new()
778 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
779 .fails_with_partial_failure(retry, OnAttempt(2))
780 .expect_send(Amount::ForInvoice(final_value_msat))
781 .expect_send(Amount::OnRetry(final_value_msat / 2))
782 .expect_send(Amount::OnRetry(final_value_msat / 2));
783 let router = TestRouter {};
784 let scorer = RefCell::new(TestScorer::new());
785 let logger = TestLogger::new();
787 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
789 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
793 fn retries_payment_path_for_unknown_payment() {
794 let event_handled = core::cell::RefCell::new(false);
795 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
797 let payment_preimage = PaymentPreimage([1; 32]);
798 let invoice = invoice(payment_preimage);
799 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
800 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
802 let payer = TestPayer::new()
803 .expect_send(Amount::OnRetry(final_value_msat / 2))
804 .expect_send(Amount::OnRetry(final_value_msat / 2));
805 let router = TestRouter {};
806 let scorer = RefCell::new(TestScorer::new());
807 let logger = TestLogger::new();
809 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
811 let payment_id = Some(PaymentId([1; 32]));
812 let event = Event::PaymentPathFailed {
815 network_update: None,
816 rejected_by_dest: false,
817 all_paths_failed: false,
818 path: TestRouter::path_for_value(final_value_msat),
819 short_channel_id: None,
820 retry: Some(TestRouter::retry_for_invoice(&invoice)),
822 invoice_payer.handle_event(&event);
823 assert_eq!(*event_handled.borrow(), false);
824 assert_eq!(*payer.attempts.borrow(), 1);
826 invoice_payer.handle_event(&event);
827 assert_eq!(*event_handled.borrow(), false);
828 assert_eq!(*payer.attempts.borrow(), 2);
830 invoice_payer.handle_event(&Event::PaymentSent {
831 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
833 assert_eq!(*event_handled.borrow(), true);
834 assert_eq!(*payer.attempts.borrow(), 2);
838 fn fails_paying_invoice_after_max_retry_counts() {
839 let event_handled = core::cell::RefCell::new(false);
840 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
842 let payment_preimage = PaymentPreimage([1; 32]);
843 let invoice = invoice(payment_preimage);
844 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
846 let payer = TestPayer::new()
847 .expect_send(Amount::ForInvoice(final_value_msat))
848 .expect_send(Amount::OnRetry(final_value_msat / 2))
849 .expect_send(Amount::OnRetry(final_value_msat / 2));
850 let router = TestRouter {};
851 let scorer = RefCell::new(TestScorer::new());
852 let logger = TestLogger::new();
854 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
856 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
857 assert_eq!(*payer.attempts.borrow(), 1);
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: true,
865 path: TestRouter::path_for_value(final_value_msat),
866 short_channel_id: None,
867 retry: Some(TestRouter::retry_for_invoice(&invoice)),
869 invoice_payer.handle_event(&event);
870 assert_eq!(*event_handled.borrow(), false);
871 assert_eq!(*payer.attempts.borrow(), 2);
873 let event = Event::PaymentPathFailed {
875 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
876 network_update: None,
877 rejected_by_dest: false,
878 all_paths_failed: false,
879 path: TestRouter::path_for_value(final_value_msat / 2),
880 short_channel_id: None,
881 retry: Some(RouteParameters {
882 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
885 invoice_payer.handle_event(&event);
886 assert_eq!(*event_handled.borrow(), false);
887 assert_eq!(*payer.attempts.borrow(), 3);
889 invoice_payer.handle_event(&event);
890 assert_eq!(*event_handled.borrow(), true);
891 assert_eq!(*payer.attempts.borrow(), 3);
894 #[cfg(feature = "std")]
896 fn fails_paying_invoice_after_max_retry_timeout() {
897 let event_handled = core::cell::RefCell::new(false);
898 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
900 let payment_preimage = PaymentPreimage([1; 32]);
901 let invoice = invoice(payment_preimage);
902 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
904 let payer = TestPayer::new()
905 .expect_send(Amount::ForInvoice(final_value_msat))
906 .expect_send(Amount::OnRetry(final_value_msat / 2));
908 let router = TestRouter {};
909 let scorer = RefCell::new(TestScorer::new());
910 let logger = TestLogger::new();
911 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
914 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
916 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
917 assert_eq!(*payer.attempts.borrow(), 1);
919 let event = Event::PaymentPathFailed {
921 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
922 network_update: None,
923 rejected_by_dest: false,
924 all_paths_failed: true,
925 path: TestRouter::path_for_value(final_value_msat),
926 short_channel_id: None,
927 retry: Some(TestRouter::retry_for_invoice(&invoice)),
929 invoice_payer.handle_event(&event);
930 assert_eq!(*event_handled.borrow(), false);
931 assert_eq!(*payer.attempts.borrow(), 2);
933 SinceEpoch::advance(Duration::from_secs(121));
935 invoice_payer.handle_event(&event);
936 assert_eq!(*event_handled.borrow(), true);
937 assert_eq!(*payer.attempts.borrow(), 2);
941 fn fails_paying_invoice_with_missing_retry_params() {
942 let event_handled = core::cell::RefCell::new(false);
943 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
945 let payment_preimage = PaymentPreimage([1; 32]);
946 let invoice = invoice(payment_preimage);
947 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
949 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
950 let router = TestRouter {};
951 let scorer = RefCell::new(TestScorer::new());
952 let logger = TestLogger::new();
954 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
956 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
957 assert_eq!(*payer.attempts.borrow(), 1);
959 let event = Event::PaymentPathFailed {
961 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
962 network_update: None,
963 rejected_by_dest: false,
964 all_paths_failed: false,
966 short_channel_id: None,
969 invoice_payer.handle_event(&event);
970 assert_eq!(*event_handled.borrow(), true);
971 assert_eq!(*payer.attempts.borrow(), 1);
974 // Expiration is checked only in an std environment
975 #[cfg(feature = "std")]
977 fn fails_paying_invoice_after_expiration() {
978 let event_handled = core::cell::RefCell::new(false);
979 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
981 let payer = TestPayer::new();
982 let router = TestRouter {};
983 let scorer = RefCell::new(TestScorer::new());
984 let logger = TestLogger::new();
986 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
988 let payment_preimage = PaymentPreimage([1; 32]);
989 let invoice = expired_invoice(payment_preimage);
990 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
991 assert_eq!(msg, "Invoice expired prior to send");
992 } else { panic!("Expected Invoice Error"); }
995 // Expiration is checked only in an std environment
996 #[cfg(feature = "std")]
998 fn fails_retrying_invoice_after_expiration() {
999 let event_handled = core::cell::RefCell::new(false);
1000 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1002 let payment_preimage = PaymentPreimage([1; 32]);
1003 let invoice = invoice(payment_preimage);
1004 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1006 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1007 let router = TestRouter {};
1008 let scorer = RefCell::new(TestScorer::new());
1009 let logger = TestLogger::new();
1011 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1013 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1014 assert_eq!(*payer.attempts.borrow(), 1);
1016 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1017 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1018 .checked_sub(Duration::from_secs(2)).unwrap()
1019 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1020 let event = Event::PaymentPathFailed {
1022 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1023 network_update: None,
1024 rejected_by_dest: false,
1025 all_paths_failed: false,
1027 short_channel_id: None,
1028 retry: Some(retry_data),
1030 invoice_payer.handle_event(&event);
1031 assert_eq!(*event_handled.borrow(), true);
1032 assert_eq!(*payer.attempts.borrow(), 1);
1036 fn fails_paying_invoice_after_retry_error() {
1037 let event_handled = core::cell::RefCell::new(false);
1038 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1040 let payment_preimage = PaymentPreimage([1; 32]);
1041 let invoice = invoice(payment_preimage);
1042 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1044 let payer = TestPayer::new()
1045 .fails_on_attempt(2)
1046 .expect_send(Amount::ForInvoice(final_value_msat))
1047 .expect_send(Amount::OnRetry(final_value_msat / 2));
1048 let router = TestRouter {};
1049 let scorer = RefCell::new(TestScorer::new());
1050 let logger = TestLogger::new();
1052 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1054 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1055 assert_eq!(*payer.attempts.borrow(), 1);
1057 let event = Event::PaymentPathFailed {
1059 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1060 network_update: None,
1061 rejected_by_dest: false,
1062 all_paths_failed: false,
1063 path: TestRouter::path_for_value(final_value_msat / 2),
1064 short_channel_id: None,
1065 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1067 invoice_payer.handle_event(&event);
1068 assert_eq!(*event_handled.borrow(), true);
1069 assert_eq!(*payer.attempts.borrow(), 2);
1073 fn fails_paying_invoice_after_rejected_by_payee() {
1074 let event_handled = core::cell::RefCell::new(false);
1075 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1077 let payment_preimage = PaymentPreimage([1; 32]);
1078 let invoice = invoice(payment_preimage);
1079 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1081 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1082 let router = TestRouter {};
1083 let scorer = RefCell::new(TestScorer::new());
1084 let logger = TestLogger::new();
1086 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1088 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1089 assert_eq!(*payer.attempts.borrow(), 1);
1091 let event = Event::PaymentPathFailed {
1093 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1094 network_update: None,
1095 rejected_by_dest: true,
1096 all_paths_failed: false,
1098 short_channel_id: None,
1099 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1101 invoice_payer.handle_event(&event);
1102 assert_eq!(*event_handled.borrow(), true);
1103 assert_eq!(*payer.attempts.borrow(), 1);
1107 fn fails_repaying_invoice_with_pending_payment() {
1108 let event_handled = core::cell::RefCell::new(false);
1109 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1111 let payment_preimage = PaymentPreimage([1; 32]);
1112 let invoice = invoice(payment_preimage);
1113 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1115 let payer = TestPayer::new()
1116 .expect_send(Amount::ForInvoice(final_value_msat))
1117 .expect_send(Amount::ForInvoice(final_value_msat));
1118 let router = TestRouter {};
1119 let scorer = RefCell::new(TestScorer::new());
1120 let logger = TestLogger::new();
1122 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1124 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1126 // Cannot repay an invoice pending payment.
1127 match invoice_payer.pay_invoice(&invoice) {
1128 Err(PaymentError::Invoice("payment pending")) => {},
1129 Err(_) => panic!("unexpected error"),
1130 Ok(_) => panic!("expected invoice error"),
1133 // Can repay an invoice once cleared from cache.
1134 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1135 invoice_payer.remove_cached_payment(&payment_hash);
1136 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1138 // Cannot retry paying an invoice if cleared from cache.
1139 invoice_payer.remove_cached_payment(&payment_hash);
1140 let event = Event::PaymentPathFailed {
1143 network_update: None,
1144 rejected_by_dest: false,
1145 all_paths_failed: false,
1147 short_channel_id: None,
1148 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1150 invoice_payer.handle_event(&event);
1151 assert_eq!(*event_handled.borrow(), true);
1155 fn fails_paying_invoice_with_routing_errors() {
1156 let payer = TestPayer::new();
1157 let router = FailingRouter {};
1158 let scorer = RefCell::new(TestScorer::new());
1159 let logger = TestLogger::new();
1161 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1163 let payment_preimage = PaymentPreimage([1; 32]);
1164 let invoice = invoice(payment_preimage);
1165 match invoice_payer.pay_invoice(&invoice) {
1166 Err(PaymentError::Routing(_)) => {},
1167 Err(_) => panic!("unexpected error"),
1168 Ok(_) => panic!("expected routing error"),
1173 fn fails_paying_invoice_with_sending_errors() {
1174 let payment_preimage = PaymentPreimage([1; 32]);
1175 let invoice = invoice(payment_preimage);
1176 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1178 let payer = TestPayer::new()
1179 .fails_on_attempt(1)
1180 .expect_send(Amount::ForInvoice(final_value_msat));
1181 let router = TestRouter {};
1182 let scorer = RefCell::new(TestScorer::new());
1183 let logger = TestLogger::new();
1185 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1187 match invoice_payer.pay_invoice(&invoice) {
1188 Err(PaymentError::Sending(_)) => {},
1189 Err(_) => panic!("unexpected error"),
1190 Ok(_) => panic!("expected sending error"),
1195 fn pays_zero_value_invoice_using_amount() {
1196 let event_handled = core::cell::RefCell::new(false);
1197 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1199 let payment_preimage = PaymentPreimage([1; 32]);
1200 let invoice = zero_value_invoice(payment_preimage);
1201 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1202 let final_value_msat = 100;
1204 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1205 let router = TestRouter {};
1206 let scorer = RefCell::new(TestScorer::new());
1207 let logger = TestLogger::new();
1209 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1212 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1213 assert_eq!(*payer.attempts.borrow(), 1);
1215 invoice_payer.handle_event(&Event::PaymentSent {
1216 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1218 assert_eq!(*event_handled.borrow(), true);
1219 assert_eq!(*payer.attempts.borrow(), 1);
1223 fn fails_paying_zero_value_invoice_with_amount() {
1224 let event_handled = core::cell::RefCell::new(false);
1225 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1227 let payer = TestPayer::new();
1228 let router = TestRouter {};
1229 let scorer = RefCell::new(TestScorer::new());
1230 let logger = TestLogger::new();
1232 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1234 let payment_preimage = PaymentPreimage([1; 32]);
1235 let invoice = invoice(payment_preimage);
1237 // Cannot repay an invoice pending payment.
1238 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1239 Err(PaymentError::Invoice("amount unexpected")) => {},
1240 Err(_) => panic!("unexpected error"),
1241 Ok(_) => panic!("expected invoice error"),
1246 fn pays_pubkey_with_amount() {
1247 let event_handled = core::cell::RefCell::new(false);
1248 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1250 let pubkey = pubkey();
1251 let payment_preimage = PaymentPreimage([1; 32]);
1252 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1253 let final_value_msat = 100;
1254 let final_cltv_expiry_delta = 42;
1256 let payer = TestPayer::new()
1257 .expect_send(Amount::Spontaneous(final_value_msat))
1258 .expect_send(Amount::OnRetry(final_value_msat));
1259 let router = TestRouter {};
1260 let scorer = RefCell::new(TestScorer::new());
1261 let logger = TestLogger::new();
1263 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1265 let payment_id = Some(invoice_payer.pay_pubkey(
1266 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1268 assert_eq!(*payer.attempts.borrow(), 1);
1270 let retry = RouteParameters {
1271 payment_params: PaymentParameters::for_keysend(pubkey),
1273 final_cltv_expiry_delta,
1275 let event = Event::PaymentPathFailed {
1278 network_update: None,
1279 rejected_by_dest: false,
1280 all_paths_failed: false,
1282 short_channel_id: None,
1285 invoice_payer.handle_event(&event);
1286 assert_eq!(*event_handled.borrow(), false);
1287 assert_eq!(*payer.attempts.borrow(), 2);
1289 invoice_payer.handle_event(&Event::PaymentSent {
1290 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1292 assert_eq!(*event_handled.borrow(), true);
1293 assert_eq!(*payer.attempts.borrow(), 2);
1297 fn scores_failed_channel() {
1298 let event_handled = core::cell::RefCell::new(false);
1299 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1301 let payment_preimage = PaymentPreimage([1; 32]);
1302 let invoice = invoice(payment_preimage);
1303 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1304 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1305 let path = TestRouter::path_for_value(final_value_msat);
1306 let short_channel_id = Some(path[0].short_channel_id);
1308 // Expect that scorer is given short_channel_id upon handling the event.
1309 let payer = TestPayer::new()
1310 .expect_send(Amount::ForInvoice(final_value_msat))
1311 .expect_send(Amount::OnRetry(final_value_msat / 2));
1312 let router = TestRouter {};
1313 let scorer = RefCell::new(TestScorer::new().expect(TestResult::PaymentFailure {
1314 path: path.clone(), short_channel_id: path[0].short_channel_id,
1316 let logger = TestLogger::new();
1318 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1320 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1321 let event = Event::PaymentPathFailed {
1324 network_update: None,
1325 rejected_by_dest: false,
1326 all_paths_failed: false,
1329 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1331 invoice_payer.handle_event(&event);
1335 fn scores_successful_channels() {
1336 let event_handled = core::cell::RefCell::new(false);
1337 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1339 let payment_preimage = PaymentPreimage([1; 32]);
1340 let invoice = invoice(payment_preimage);
1341 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1342 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1343 let route = TestRouter::route_for_value(final_value_msat);
1345 // Expect that scorer is given short_channel_id upon handling the event.
1346 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1347 let router = TestRouter {};
1348 let scorer = RefCell::new(TestScorer::new()
1349 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1350 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() })
1352 let logger = TestLogger::new();
1354 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1356 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1357 let event = Event::PaymentPathSuccessful {
1358 payment_id, payment_hash, path: route.paths[0].clone()
1360 invoice_payer.handle_event(&event);
1361 let event = Event::PaymentPathSuccessful {
1362 payment_id, payment_hash, path: route.paths[1].clone()
1364 invoice_payer.handle_event(&event);
1370 fn route_for_value(final_value_msat: u64) -> Route {
1374 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1375 channel_features: ChannelFeatures::empty(),
1376 node_features: NodeFeatures::empty(),
1377 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1380 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1381 channel_features: ChannelFeatures::empty(),
1382 node_features: NodeFeatures::empty(),
1383 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1386 payment_params: None,
1390 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1391 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1394 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1395 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1396 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1397 .with_route_hints(invoice.route_hints());
1398 if let Some(features) = invoice.features() {
1399 payment_params = payment_params.with_features(features.clone());
1401 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1405 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1410 impl<S: Score> Router<S> for TestRouter {
1412 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1413 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1414 ) -> Result<Route, LightningError> {
1416 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1421 struct FailingRouter;
1423 impl<S: Score> Router<S> for FailingRouter {
1425 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1426 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1427 ) -> Result<Route, LightningError> {
1428 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1433 expectations: Option<VecDeque<TestResult>>,
1438 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1439 PaymentSuccess { path: Vec<RouteHop> },
1440 ProbeFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1441 ProbeSuccess { path: Vec<RouteHop> },
1451 fn expect(mut self, expectation: TestResult) -> Self {
1452 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1458 impl lightning::util::ser::Writeable for TestScorer {
1459 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1462 impl Score for TestScorer {
1463 fn channel_penalty_msat(
1464 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
1467 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1468 if let Some(expectations) = &mut self.expectations {
1469 match expectations.pop_front() {
1470 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1471 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1472 assert_eq!(actual_short_channel_id, short_channel_id);
1474 Some(TestResult::PaymentSuccess { path }) => {
1475 panic!("Unexpected successful payment path: {:?}", path)
1477 Some(TestResult::ProbeFailure { path, .. }) => {
1478 panic!("Unexpected failed payment probe: {:?}", path)
1480 Some(TestResult::ProbeSuccess { path }) => {
1481 panic!("Unexpected successful payment probe: {:?}", path)
1483 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1488 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1489 if let Some(expectations) = &mut self.expectations {
1490 match expectations.pop_front() {
1491 Some(TestResult::PaymentFailure { path, .. }) => {
1492 panic!("Unexpected payment path failure: {:?}", path)
1494 Some(TestResult::PaymentSuccess { path }) => {
1495 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1497 Some(TestResult::ProbeFailure { path, .. }) => {
1498 panic!("Unexpected failed payment probe: {:?}", path)
1500 Some(TestResult::ProbeSuccess { path }) => {
1501 panic!("Unexpected successful payment probe: {:?}", path)
1503 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1508 fn probe_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1509 if let Some(expectations) = &mut self.expectations {
1510 match expectations.pop_front() {
1511 Some(TestResult::PaymentFailure { path, .. }) => {
1512 panic!("Unexpected failed payment path: {:?}", path)
1514 Some(TestResult::PaymentSuccess { path }) => {
1515 panic!("Unexpected successful payment path: {:?}", path)
1517 Some(TestResult::ProbeFailure { path, short_channel_id }) => {
1518 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1519 assert_eq!(actual_short_channel_id, short_channel_id);
1521 Some(TestResult::ProbeSuccess { path }) => {
1522 panic!("Unexpected successful payment probe: {:?}", path)
1524 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1528 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1529 if let Some(expectations) = &mut self.expectations {
1530 match expectations.pop_front() {
1531 Some(TestResult::PaymentFailure { path, .. }) => {
1532 panic!("Unexpected payment path failure: {:?}", path)
1534 Some(TestResult::PaymentSuccess { path }) => {
1535 panic!("Unexpected successful payment path: {:?}", path)
1537 Some(TestResult::ProbeFailure { path, .. }) => {
1538 panic!("Unexpected failed payment probe: {:?}", path)
1540 Some(TestResult::ProbeSuccess { path }) => {
1541 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1543 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1549 impl Drop for TestScorer {
1550 fn drop(&mut self) {
1551 if std::thread::panicking() {
1555 if let Some(expectations) = &self.expectations {
1556 if !expectations.is_empty() {
1557 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1564 expectations: core::cell::RefCell<VecDeque<Amount>>,
1565 attempts: core::cell::RefCell<usize>,
1566 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1569 #[derive(Clone, Debug, PartialEq, Eq)]
1576 struct OnAttempt(usize);
1581 expectations: core::cell::RefCell::new(VecDeque::new()),
1582 attempts: core::cell::RefCell::new(0),
1583 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1587 fn expect_send(self, value_msat: Amount) -> Self {
1588 self.expectations.borrow_mut().push_back(value_msat);
1592 fn fails_on_attempt(self, attempt: usize) -> Self {
1593 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1594 self.fails_with(failure, OnAttempt(attempt))
1597 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1598 self.fails_with(PaymentSendFailure::PartialFailure {
1600 failed_paths_retry: Some(retry),
1601 payment_id: PaymentId([1; 32]),
1605 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1606 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1610 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1611 let mut attempts = self.attempts.borrow_mut();
1614 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1615 Some(failure) => Err(failure),
1616 None => Ok(PaymentId([1; 32])),
1620 fn check_value_msats(&self, actual_value_msats: Amount) {
1621 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1622 if let Some(expected_value_msats) = expected_value_msats {
1623 assert_eq!(actual_value_msats, expected_value_msats);
1625 panic!("Unexpected amount: {:?}", actual_value_msats);
1630 impl Drop for TestPayer {
1631 fn drop(&mut self) {
1632 if std::thread::panicking() {
1636 if !self.expectations.borrow().is_empty() {
1637 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1642 impl Payer for TestPayer {
1643 fn node_id(&self) -> PublicKey {
1644 let secp_ctx = Secp256k1::new();
1645 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1648 fn first_hops(&self) -> Vec<ChannelDetails> {
1653 &self, route: &Route, _payment_hash: PaymentHash,
1654 _payment_secret: &Option<PaymentSecret>
1655 ) -> Result<PaymentId, PaymentSendFailure> {
1656 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1657 self.check_attempts()
1660 fn send_spontaneous_payment(
1661 &self, route: &Route, _payment_preimage: PaymentPreimage,
1662 ) -> Result<PaymentId, PaymentSendFailure> {
1663 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1664 self.check_attempts()
1668 &self, route: &Route, _payment_id: PaymentId
1669 ) -> Result<(), PaymentSendFailure> {
1670 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1671 self.check_attempts().map(|_| ())
1674 fn abandon_payment(&self, _payment_id: PaymentId) { }
1677 // *** Full Featured Functional Tests with a Real ChannelManager ***
1678 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1680 impl<S: Score> Router<S> for ManualRouter {
1682 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1683 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1684 ) -> Result<Route, LightningError> {
1685 self.0.borrow_mut().pop_front().unwrap()
1689 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1690 self.0.borrow_mut().push_back(result);
1693 impl Drop for ManualRouter {
1694 fn drop(&mut self) {
1695 if std::thread::panicking() {
1698 assert!(self.0.borrow_mut().is_empty());
1703 fn retry_multi_path_single_failed_payment() {
1704 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1705 let chanmon_cfgs = create_chanmon_cfgs(2);
1706 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1707 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1708 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1710 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1711 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1712 let chans = nodes[0].node.list_usable_channels();
1713 let mut route = Route {
1716 pubkey: nodes[1].node.get_our_node_id(),
1717 node_features: NodeFeatures::known(),
1718 short_channel_id: chans[0].short_channel_id.unwrap(),
1719 channel_features: ChannelFeatures::known(),
1721 cltv_expiry_delta: 100,
1724 pubkey: nodes[1].node.get_our_node_id(),
1725 node_features: NodeFeatures::known(),
1726 short_channel_id: chans[1].short_channel_id.unwrap(),
1727 channel_features: ChannelFeatures::known(),
1728 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1729 cltv_expiry_delta: 100,
1732 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1734 let router = ManualRouter(RefCell::new(VecDeque::new()));
1735 router.expect_find_route(Ok(route.clone()));
1736 // On retry, split the payment across both channels.
1737 route.paths[0][0].fee_msat = 50_000_001;
1738 route.paths[1][0].fee_msat = 50_000_000;
1739 router.expect_find_route(Ok(route.clone()));
1741 let event_handler = |_: &_| { panic!(); };
1742 let scorer = RefCell::new(TestScorer::new());
1743 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1745 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1746 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1747 duration_since_epoch(), 3600).unwrap())
1749 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1750 assert_eq!(htlc_msgs.len(), 2);
1751 check_added_monitors!(nodes[0], 2);
1755 fn immediate_retry_on_failure() {
1756 // Tests that we can/will retry immediately after a failure
1757 let chanmon_cfgs = create_chanmon_cfgs(2);
1758 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1759 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1760 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1762 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1763 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1764 let chans = nodes[0].node.list_usable_channels();
1765 let mut route = Route {
1768 pubkey: nodes[1].node.get_our_node_id(),
1769 node_features: NodeFeatures::known(),
1770 short_channel_id: chans[0].short_channel_id.unwrap(),
1771 channel_features: ChannelFeatures::known(),
1772 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1773 cltv_expiry_delta: 100,
1776 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1778 let router = ManualRouter(RefCell::new(VecDeque::new()));
1779 router.expect_find_route(Ok(route.clone()));
1780 // On retry, split the payment across both channels.
1781 route.paths.push(route.paths[0].clone());
1782 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1783 route.paths[0][0].fee_msat = 50_000_000;
1784 route.paths[1][0].fee_msat = 50_000_001;
1785 router.expect_find_route(Ok(route.clone()));
1787 let event_handler = |_: &_| { panic!(); };
1788 let scorer = RefCell::new(TestScorer::new());
1789 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1791 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1792 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1793 duration_since_epoch(), 3600).unwrap())
1795 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1796 assert_eq!(htlc_msgs.len(), 2);
1797 check_added_monitors!(nodes[0], 2);
1801 fn no_extra_retries_on_back_to_back_fail() {
1802 // In a previous release, we had a race where we may exceed the payment retry count if we
1803 // get two failures in a row with the second having `all_paths_failed` set.
1804 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1805 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1806 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1807 // pending which we will see later. Thus, when we previously removed the retry tracking map
1808 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1809 // retry entry even though more events for the same payment were still pending. This led to
1810 // us retrying a payment again even though we'd already given up on it.
1812 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1813 // is used to remove the payment retry counter entries instead. This tests for the specific
1814 // excess-retry case while also testing `PaymentFailed` generation.
1816 let chanmon_cfgs = create_chanmon_cfgs(3);
1817 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1818 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1819 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1821 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;
1822 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;
1824 let mut route = Route {
1827 pubkey: nodes[1].node.get_our_node_id(),
1828 node_features: NodeFeatures::known(),
1829 short_channel_id: chan_1_scid,
1830 channel_features: ChannelFeatures::known(),
1832 cltv_expiry_delta: 100,
1834 pubkey: nodes[2].node.get_our_node_id(),
1835 node_features: NodeFeatures::known(),
1836 short_channel_id: chan_2_scid,
1837 channel_features: ChannelFeatures::known(),
1838 fee_msat: 100_000_000,
1839 cltv_expiry_delta: 100,
1842 pubkey: nodes[1].node.get_our_node_id(),
1843 node_features: NodeFeatures::known(),
1844 short_channel_id: chan_1_scid,
1845 channel_features: ChannelFeatures::known(),
1847 cltv_expiry_delta: 100,
1849 pubkey: nodes[2].node.get_our_node_id(),
1850 node_features: NodeFeatures::known(),
1851 short_channel_id: chan_2_scid,
1852 channel_features: ChannelFeatures::known(),
1853 fee_msat: 100_000_000,
1854 cltv_expiry_delta: 100,
1857 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1859 let router = ManualRouter(RefCell::new(VecDeque::new()));
1860 router.expect_find_route(Ok(route.clone()));
1861 // On retry, we'll only be asked for one path
1862 route.paths.remove(1);
1863 router.expect_find_route(Ok(route.clone()));
1865 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1866 let event_handler = |event: &Event| {
1867 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1868 event_checker(event);
1870 let scorer = RefCell::new(TestScorer::new());
1871 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1873 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1874 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1875 duration_since_epoch(), 3600).unwrap())
1877 let htlc_updates = SendEvent::from_node(&nodes[0]);
1878 check_added_monitors!(nodes[0], 1);
1879 assert_eq!(htlc_updates.msgs.len(), 1);
1881 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1882 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1883 check_added_monitors!(nodes[1], 1);
1884 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1886 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1887 check_added_monitors!(nodes[0], 1);
1888 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1890 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1891 check_added_monitors!(nodes[0], 1);
1892 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1894 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1895 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1896 check_added_monitors!(nodes[1], 1);
1897 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1899 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1900 check_added_monitors!(nodes[1], 1);
1901 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1903 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1904 check_added_monitors!(nodes[0], 1);
1906 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1907 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1908 check_added_monitors!(nodes[0], 1);
1909 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1911 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1912 check_added_monitors!(nodes[1], 1);
1913 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1915 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1919 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1921 check_added_monitors!(nodes[0], 1);
1923 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1924 check_added_monitors!(nodes[0], 1);
1925 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1927 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1928 check_added_monitors!(nodes[1], 1);
1929 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1930 check_added_monitors!(nodes[1], 1);
1931 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1933 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1934 check_added_monitors!(nodes[0], 1);
1936 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1937 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1938 // with it set. The first event will use up the only retry we are allowed, with the second
1939 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1940 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1941 // if the final HTLC failed.
1942 expected_events.borrow_mut().push_back(&|ev: &Event| {
1943 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1944 assert!(!rejected_by_dest);
1945 assert!(all_paths_failed);
1946 } else { panic!("Unexpected event"); }
1948 nodes[0].node.process_pending_events(&invoice_payer);
1949 assert!(expected_events.borrow().is_empty());
1951 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1952 check_added_monitors!(nodes[0], 1);
1954 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1955 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1956 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1957 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1958 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1960 expected_events.borrow_mut().push_back(&|ev: &Event| {
1961 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1962 assert!(!rejected_by_dest);
1963 assert!(all_paths_failed);
1964 } else { panic!("Unexpected event"); }
1966 expected_events.borrow_mut().push_back(&|ev: &Event| {
1967 if let Event::PaymentFailed { .. } = ev {
1968 } else { panic!("Unexpected event"); }
1970 nodes[0].node.process_pending_events(&invoice_payer);
1971 assert!(expected_events.borrow().is_empty());