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`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, ScoringRouter};
48 //! # use secp256k1::PublicKey;
49 //! # use std::cell::RefCell;
50 //! # use std::ops::Deref;
52 //! # struct FakeEventProvider {}
53 //! # impl EventsProvider for FakeEventProvider {
54 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
57 //! # struct FakePayer {}
58 //! # impl Payer for FakePayer {
59 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
60 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
61 //! # fn send_payment(
62 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
63 //! # payment_id: PaymentId
64 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
65 //! # fn send_spontaneous_payment(
66 //! # &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
67 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
68 //! # fn retry_payment(
69 //! # &self, route: &Route, payment_id: PaymentId
70 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
71 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
74 //! # struct FakeRouter {}
75 //! # impl Router for FakeRouter {
77 //! # &self, payer: &PublicKey, params: &RouteParameters,
78 //! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
79 //! # ) -> Result<Route, LightningError> { unimplemented!() }
81 //! # impl ScoringRouter for FakeRouter {
82 //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
83 //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() }
84 //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() }
85 //! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
88 //! # struct FakeScorer {}
89 //! # impl Writeable for FakeScorer {
90 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
92 //! # impl Score for FakeScorer {
93 //! # fn channel_penalty_msat(
94 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
96 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
97 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
98 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
99 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
102 //! # struct FakeLogger {}
103 //! # impl Logger for FakeLogger {
104 //! # fn log(&self, record: &Record) { unimplemented!() }
108 //! let event_handler = |event: Event| {
110 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
111 //! Event::PaymentSent { .. } => println!("payment successful"),
115 //! # let payer = FakePayer {};
116 //! # let router = FakeRouter {};
117 //! # let scorer = RefCell::new(FakeScorer {});
118 //! # let logger = FakeLogger {};
119 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
121 //! let invoice = "...";
122 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
123 //! invoice_payer.pay_invoice(&invoice).unwrap();
125 //! # let event_provider = FakeEventProvider {};
127 //! event_provider.process_pending_events(&invoice_payer);
135 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
136 //! as updates to the network graph or changes to channel scores should be applied prior to
137 //! retries, typically by way of composing [`EventHandler`]s accordingly.
141 use bitcoin_hashes::Hash;
142 use bitcoin_hashes::sha256::Hash as Sha256;
144 use crate::prelude::*;
145 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
146 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
147 use lightning::ln::msgs::LightningError;
148 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router};
149 use lightning::util::errors::APIError;
150 use lightning::util::events::{Event, EventHandler};
151 use lightning::util::logger::Logger;
152 use crate::time_utils::Time;
153 use crate::sync::Mutex;
155 use secp256k1::PublicKey;
158 use core::fmt::{Debug, Display, Formatter};
159 use core::future::Future;
160 use core::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
167 /// See [module-level documentation] for details.
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
175 use crate::time_utils;
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
179 /// Sealed trait with a blanket implementation to allow both sync and async implementations of event
180 /// handling to exist within the InvoicePayer.
182 pub trait BaseEventHandler {}
183 impl<T> BaseEventHandler for T {}
186 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
187 pub struct InvoicePayerUsingTime<
191 E: sealed::BaseEventHandler,
201 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
202 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
206 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
207 /// currently being made, or have outstanding paths that need retrying.
208 struct PaymentInfo<T: Time> {
209 attempts: PaymentAttempts<T>,
210 paths: Vec<Vec<RouteHop>>,
213 impl<T: Time> PaymentInfo<T> {
216 attempts: PaymentAttempts::new(),
222 /// Storing minimal payment attempts information required for determining if a outbound payment can
224 #[derive(Clone, Copy)]
225 struct PaymentAttempts<T: Time> {
226 /// This count will be incremented only after the result of the attempt is known. When it's 0,
227 /// it means the result of the first attempt is now known yet.
229 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
230 first_attempted_at: T
233 impl<T: Time> PaymentAttempts<T> {
237 first_attempted_at: T::now()
242 impl<T: Time> Display for PaymentAttempts<T> {
243 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
244 #[cfg(feature = "no-std")]
245 return write!( f, "attempts: {}", self.count);
246 #[cfg(not(feature = "no-std"))]
249 "attempts: {}, duration: {}s",
251 T::now().duration_since(self.first_attempted_at).as_secs()
256 /// A trait defining behavior of an [`Invoice`] payer.
258 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
259 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
261 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
263 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
264 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
265 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
266 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
268 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
270 /// Returns the payer's node id.
271 fn node_id(&self) -> PublicKey;
273 /// Returns the payer's channels.
274 fn first_hops(&self) -> Vec<ChannelDetails>;
276 /// Sends a payment over the Lightning Network using the given [`Route`].
278 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
279 payment_id: PaymentId
280 ) -> Result<(), PaymentSendFailure>;
282 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
283 fn send_spontaneous_payment(
284 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
285 ) -> Result<(), PaymentSendFailure>;
287 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
288 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
290 /// Signals that no further retries for the given payment will occur.
291 fn abandon_payment(&self, payment_id: PaymentId);
294 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
295 /// based on payment and probe success/failure.
297 /// [`Router`]: lightning::routing::router::Router
298 pub trait ScoringRouter: Router {
299 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
300 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
301 fn find_route_with_id(
302 &self, payer: &PublicKey, route_params: &RouteParameters,
303 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
304 _payment_hash: PaymentHash, _payment_id: PaymentId
305 ) -> Result<Route, LightningError> {
306 self.find_route(payer, route_params, first_hops, inflight_htlcs)
308 /// Lets the router know that payment through a specific path has failed.
309 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
310 /// Lets the router know that payment through a specific path was successful.
311 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
312 /// Lets the router know that a payment probe was successful.
313 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
314 /// Lets the router know that a payment probe failed.
315 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
318 /// Strategies available to retry payment path failures for an [`Invoice`].
320 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
322 /// Max number of attempts to retry payment.
324 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
325 /// payments, if this is less than the total number of paths, we will never even retry all of the
328 #[cfg(feature = "std")]
329 /// Time elapsed before abandoning retries for a payment.
334 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
335 match (self, attempts) {
336 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
337 max_retry_count >= &count
339 #[cfg(feature = "std")]
340 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
341 *max_duration >= T::now().duration_since(*first_attempted_at),
346 /// An error that may occur when making a payment.
347 #[derive(Clone, Debug)]
348 pub enum PaymentError {
349 /// An error resulting from the provided [`Invoice`] or payment hash.
350 Invoice(&'static str),
351 /// An error occurring when finding a route.
352 Routing(LightningError),
353 /// An error occurring when sending a payment.
354 Sending(PaymentSendFailure),
357 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
358 InvoicePayerUsingTime<P, R, L, E, T>
363 /// Creates an invoice payer that retries failed payment paths.
365 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
366 /// `retry` has been exceeded for a given [`Invoice`].
368 payer: P, router: R, logger: L, event_handler: E, retry: Retry
375 payment_cache: Mutex::new(HashMap::new()),
380 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
382 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
383 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
384 /// a second payment with the same [`PaymentHash`] is never sent.
386 /// If you wish to use a different payment idempotency token, see
387 /// [`Self::pay_invoice_with_id`].
388 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
389 let payment_id = PaymentId(invoice.payment_hash().into_inner());
390 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
393 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
394 /// in case a retry is needed.
396 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
397 /// payment completes or fails, no idempotency guarantees are made.
399 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
400 /// has never been paid before.
402 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
404 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
405 if invoice.amount_milli_satoshis().is_none() {
406 Err(PaymentError::Invoice("amount missing"))
408 self.pay_invoice_using_amount(invoice, None, payment_id)
412 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
413 /// case a retry is needed.
415 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
416 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
417 /// a second payment with the same [`PaymentHash`] is never sent.
419 /// If you wish to use a different payment idempotency token, see
420 /// [`Self::pay_zero_value_invoice_with_id`].
421 pub fn pay_zero_value_invoice(
422 &self, invoice: &Invoice, amount_msats: u64
423 ) -> Result<PaymentId, PaymentError> {
424 let payment_id = PaymentId(invoice.payment_hash().into_inner());
425 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
428 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
429 /// caching the invoice for later use in case a retry is needed.
431 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
432 /// payment completes or fails, no idempotency guarantees are made.
434 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
435 /// has never been paid before.
437 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
438 /// idempotency token.
439 pub fn pay_zero_value_invoice_with_id(
440 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
441 ) -> Result<(), PaymentError> {
442 if invoice.amount_milli_satoshis().is_some() {
443 Err(PaymentError::Invoice("amount unexpected"))
445 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
449 fn pay_invoice_using_amount(
450 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
451 ) -> Result<(), PaymentError> {
452 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
454 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
455 match self.payment_cache.lock().unwrap().entry(payment_hash) {
456 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
457 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
460 let payment_secret = Some(invoice.payment_secret().clone());
461 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
462 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
463 .with_route_hints(invoice.route_hints());
464 if let Some(features) = invoice.features() {
465 payment_params = payment_params.with_features(features.clone());
467 let route_params = RouteParameters {
469 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
470 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
473 let send_payment = |route: &Route| {
474 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
477 self.pay_internal(&route_params, payment_hash, send_payment)
478 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
481 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
482 /// case a retry is needed.
484 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
485 /// as long as the payment is still pending. Once the payment completes or fails, you must
486 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
488 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
489 final_cltv_expiry_delta: u32
490 ) -> Result<PaymentId, PaymentError> {
491 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
492 let payment_id = PaymentId(payment_hash.0);
493 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
494 final_cltv_expiry_delta)
495 .map(|()| payment_id)
498 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
499 /// caching the invoice for later use in case a retry is needed.
501 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
502 /// payment completes or fails, no idempotency guarantees are made.
504 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
505 /// [`PaymentHash`] has never been paid before.
506 pub fn pay_pubkey_with_id(
507 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
508 amount_msats: u64, final_cltv_expiry_delta: u32
509 ) -> Result<(), PaymentError> {
510 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
511 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
512 final_cltv_expiry_delta)
516 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
517 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
518 ) -> Result<(), PaymentError> {
519 match self.payment_cache.lock().unwrap().entry(payment_hash) {
520 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
521 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
524 let route_params = RouteParameters {
525 payment_params: PaymentParameters::for_keysend(pubkey),
526 final_value_msat: amount_msats,
527 final_cltv_expiry_delta,
530 let send_payment = |route: &Route| {
531 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
533 self.pay_internal(&route_params, payment_hash, send_payment)
534 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
537 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
538 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
539 ) -> Result<(), PaymentError> {
540 #[cfg(feature = "std")] {
541 if has_expired(params) {
542 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
543 return Err(PaymentError::Invoice("Invoice expired prior to send"));
547 let payer = self.payer.node_id();
548 let first_hops = self.payer.first_hops();
549 let inflight_htlcs = self.create_inflight_map();
550 let route = self.router.find_route(
551 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
552 ).map_err(|e| PaymentError::Routing(e))?;
554 match send_payment(&route) {
556 for path in route.paths {
557 self.process_path_inflight_htlcs(payment_hash, path);
562 PaymentSendFailure::ParameterError(_) => Err(e),
563 PaymentSendFailure::PathParameterError(_) => Err(e),
564 PaymentSendFailure::DuplicatePayment => Err(e),
565 PaymentSendFailure::AllFailedResendSafe(_) => {
566 let mut payment_cache = self.payment_cache.lock().unwrap();
567 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
568 payment_info.attempts.count += 1;
569 if self.retry.is_retryable_now(&payment_info.attempts) {
570 core::mem::drop(payment_cache);
571 Ok(self.pay_internal(params, payment_hash, send_payment)?)
576 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
577 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
578 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
579 // means that we are still waiting for our channel monitor update to be completed.
580 for (result, path) in results.iter().zip(route.paths.into_iter()) {
582 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
583 self.process_path_inflight_htlcs(payment_hash, path);
589 if let Some(retry_data) = failed_paths_retry {
590 // Some paths were sent, even if we failed to send the full MPP value our
591 // recipient may misbehave and claim the funds, at which point we have to
592 // consider the payment sent, so return `Ok()` here, ignoring any retry
594 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
597 // This may happen if we send a payment and some paths fail, but
598 // only due to a temporary monitor failure or the like, implying
599 // they're really in-flight, but we haven't sent the initial
600 // HTLC-Add messages yet.
605 }.map_err(|e| PaymentError::Sending(e))
608 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
609 // that are pending retry.
610 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
611 self.payment_cache.lock().unwrap().entry(payment_hash)
612 .or_insert_with(|| PaymentInfo::new())
616 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
617 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
618 self.payment_cache.lock().unwrap().entry(payment_hash)
619 .and_modify(|payment_info| {
620 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
621 payment_info.paths.swap_remove(idx);
627 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
628 ) -> Result<(), ()> {
629 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
630 .and_modify(|info| info.attempts.count += 1 )
631 .or_insert_with(|| PaymentInfo {
632 attempts: PaymentAttempts {
634 first_attempted_at: T::now(),
639 if !self.retry.is_retryable_now(&attempts) {
640 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
644 #[cfg(feature = "std")] {
645 if has_expired(params) {
646 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
651 let payer = self.payer.node_id();
652 let first_hops = self.payer.first_hops();
653 let inflight_htlcs = self.create_inflight_map();
655 let route = self.router.find_route(
656 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
660 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
664 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
666 for path in route.unwrap().paths.into_iter() {
667 self.process_path_inflight_htlcs(payment_hash, path);
671 Err(PaymentSendFailure::ParameterError(_)) |
672 Err(PaymentSendFailure::PathParameterError(_)) => {
673 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
676 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
677 self.retry_payment(payment_id, payment_hash, params)
679 Err(PaymentSendFailure::DuplicatePayment) => {
680 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
683 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
684 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
685 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
686 // means that we are still waiting for our channel monitor update to complete.
687 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
689 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
690 self.process_path_inflight_htlcs(payment_hash, path);
696 if let Some(retry) = failed_paths_retry {
697 // Always return Ok for the same reason as noted in pay_internal.
698 let _ = self.retry_payment(payment_id, payment_hash, &retry);
705 /// Removes the payment cached by the given payment hash.
707 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
708 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
709 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
710 self.payment_cache.lock().unwrap().remove(payment_hash);
713 /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
714 /// channel id and direction to the amount being sent through it.
716 /// This function should be called whenever we need information about currently used up liquidity
718 fn create_inflight_map(&self) -> InFlightHtlcs {
719 let mut total_inflight_map = InFlightHtlcs::new();
720 // Make an attempt at finding existing payment information from `payment_cache`.
721 for payment_info in self.payment_cache.lock().unwrap().values() {
722 for path in &payment_info.paths {
723 total_inflight_map.process_path(path, self.payer.node_id());
731 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
732 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
735 #[cfg(feature = "std")]
736 fn has_expired(route_params: &RouteParameters) -> bool {
737 if let Some(expiry_time) = route_params.payment_params.expiry_time {
738 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
742 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
743 InvoicePayerUsingTime<P, R, L, E, T>
748 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
750 fn handle_event_internal(&self, event: &Event) -> bool {
752 Event::PaymentPathFailed { payment_hash, path, .. }
753 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
754 | Event::ProbeSuccessful { payment_hash, path, .. }
755 | Event::ProbeFailed { payment_hash, path, .. } => {
756 self.remove_path_inflight_htlcs(*payment_hash, path);
762 Event::PaymentPathFailed {
763 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
765 if let Some(short_channel_id) = short_channel_id {
766 let path = path.iter().collect::<Vec<_>>();
767 self.router.notify_payment_path_failed(&path, *short_channel_id)
770 if payment_id.is_none() {
771 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
772 } else if *payment_failed_permanently {
773 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
774 self.payer.abandon_payment(payment_id.unwrap());
775 } else if retry.is_none() {
776 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
777 self.payer.abandon_payment(payment_id.unwrap());
778 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
779 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
782 self.payer.abandon_payment(payment_id.unwrap());
785 Event::PaymentFailed { payment_hash, .. } => {
786 self.remove_cached_payment(&payment_hash);
788 Event::PaymentPathSuccessful { path, .. } => {
789 let path = path.iter().collect::<Vec<_>>();
790 self.router.notify_payment_path_successful(&path);
792 Event::PaymentSent { payment_hash, .. } => {
793 let mut payment_cache = self.payment_cache.lock().unwrap();
794 let attempts = payment_cache
795 .remove(payment_hash)
796 .map_or(1, |payment_info| payment_info.attempts.count + 1);
797 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
799 Event::ProbeSuccessful { payment_hash, path, .. } => {
800 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
801 let path = path.iter().collect::<Vec<_>>();
802 self.router.notify_payment_probe_successful(&path);
804 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
805 if let Some(short_channel_id) = short_channel_id {
806 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
807 let path = path.iter().collect::<Vec<_>>();
808 self.router.notify_payment_probe_failed(&path, *short_channel_id);
814 // Delegate to the decorated event handler unless the payment is retried.
819 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
820 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
825 fn handle_event(&self, event: Event) {
826 let should_forward = self.handle_event_internal(&event);
828 self.event_handler.handle_event(event)
833 impl<P: Deref, R: ScoringRouter, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
834 InvoicePayerUsingTime<P, R, L, H, T>
839 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
840 /// handler, if necessary, to handle them asynchronously.
841 pub async fn handle_event_async(&self, event: Event) {
842 let should_forward = self.handle_event_internal(&event);
844 (self.event_handler)(event).await;
852 use crate::{InvoiceBuilder, Currency};
853 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
854 use bitcoin_hashes::sha256::Hash as Sha256;
855 use lightning::ln::PaymentPreimage;
856 use lightning::ln::channelmanager;
857 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
858 use lightning::ln::functional_test_utils::*;
859 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
860 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
861 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
862 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
863 use lightning::util::test_utils::TestLogger;
864 use lightning::util::errors::APIError;
865 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
866 use secp256k1::{SecretKey, PublicKey, Secp256k1};
867 use std::cell::RefCell;
868 use std::collections::VecDeque;
869 use std::ops::DerefMut;
870 use std::time::{SystemTime, Duration};
871 use crate::time_utils::tests::SinceEpoch;
872 use crate::DEFAULT_EXPIRY_TIME;
873 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
875 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
876 let payment_hash = Sha256::hash(&payment_preimage.0);
877 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
879 InvoiceBuilder::new(Currency::Bitcoin)
880 .description("test".into())
881 .payment_hash(payment_hash)
882 .payment_secret(PaymentSecret([0; 32]))
883 .duration_since_epoch(duration_since_epoch())
884 .min_final_cltv_expiry(144)
885 .amount_milli_satoshis(128)
886 .build_signed(|hash| {
887 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
892 fn duration_since_epoch() -> Duration {
893 #[cfg(feature = "std")]
894 let duration_since_epoch =
895 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
896 #[cfg(not(feature = "std"))]
897 let duration_since_epoch = Duration::from_secs(1234567);
901 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
902 let payment_hash = Sha256::hash(&payment_preimage.0);
903 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
905 InvoiceBuilder::new(Currency::Bitcoin)
906 .description("test".into())
907 .payment_hash(payment_hash)
908 .payment_secret(PaymentSecret([0; 32]))
909 .duration_since_epoch(duration_since_epoch())
910 .min_final_cltv_expiry(144)
911 .build_signed(|hash| {
912 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
917 #[cfg(feature = "std")]
918 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
919 let payment_hash = Sha256::hash(&payment_preimage.0);
920 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
921 let duration = duration_since_epoch()
922 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
924 InvoiceBuilder::new(Currency::Bitcoin)
925 .description("test".into())
926 .payment_hash(payment_hash)
927 .payment_secret(PaymentSecret([0; 32]))
928 .duration_since_epoch(duration)
929 .min_final_cltv_expiry(144)
930 .amount_milli_satoshis(128)
931 .build_signed(|hash| {
932 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
937 fn pubkey() -> PublicKey {
938 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
942 fn pays_invoice_on_first_attempt() {
943 let event_handled = core::cell::RefCell::new(false);
944 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
946 let payment_preimage = PaymentPreimage([1; 32]);
947 let invoice = invoice(payment_preimage);
948 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
949 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
951 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
952 let router = TestRouter::new(TestScorer::new());
953 let logger = TestLogger::new();
955 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
957 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
958 assert_eq!(*payer.attempts.borrow(), 1);
960 invoice_payer.handle_event(Event::PaymentSent {
961 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
963 assert_eq!(*event_handled.borrow(), true);
964 assert_eq!(*payer.attempts.borrow(), 1);
968 fn pays_invoice_on_retry() {
969 let event_handled = core::cell::RefCell::new(false);
970 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
972 let payment_preimage = PaymentPreimage([1; 32]);
973 let invoice = invoice(payment_preimage);
974 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
975 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
977 let payer = TestPayer::new()
978 .expect_send(Amount::ForInvoice(final_value_msat))
979 .expect_send(Amount::OnRetry(final_value_msat / 2));
980 let router = TestRouter::new(TestScorer::new());
981 let logger = TestLogger::new();
983 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
985 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
986 assert_eq!(*payer.attempts.borrow(), 1);
988 let event = Event::PaymentPathFailed {
991 network_update: None,
992 payment_failed_permanently: false,
993 all_paths_failed: false,
994 path: TestRouter::path_for_value(final_value_msat),
995 short_channel_id: None,
996 retry: Some(TestRouter::retry_for_invoice(&invoice)),
998 invoice_payer.handle_event(event);
999 assert_eq!(*event_handled.borrow(), false);
1000 assert_eq!(*payer.attempts.borrow(), 2);
1002 invoice_payer.handle_event(Event::PaymentSent {
1003 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1005 assert_eq!(*event_handled.borrow(), true);
1006 assert_eq!(*payer.attempts.borrow(), 2);
1010 fn pays_invoice_on_partial_failure() {
1011 let event_handler = |_: Event| { panic!() };
1013 let payment_preimage = PaymentPreimage([1; 32]);
1014 let invoice = invoice(payment_preimage);
1015 let retry = TestRouter::retry_for_invoice(&invoice);
1016 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1018 let payer = TestPayer::new()
1019 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
1020 .fails_with_partial_failure(retry, OnAttempt(2), None)
1021 .expect_send(Amount::ForInvoice(final_value_msat))
1022 .expect_send(Amount::OnRetry(final_value_msat / 2))
1023 .expect_send(Amount::OnRetry(final_value_msat / 2));
1024 let router = TestRouter::new(TestScorer::new());
1025 let logger = TestLogger::new();
1027 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1029 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1033 fn retries_payment_path_for_unknown_payment() {
1034 let event_handled = core::cell::RefCell::new(false);
1035 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1037 let payment_preimage = PaymentPreimage([1; 32]);
1038 let invoice = invoice(payment_preimage);
1039 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1040 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1042 let payer = TestPayer::new()
1043 .expect_send(Amount::OnRetry(final_value_msat / 2))
1044 .expect_send(Amount::OnRetry(final_value_msat / 2));
1045 let router = TestRouter::new(TestScorer::new());
1046 let logger = TestLogger::new();
1048 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1050 let payment_id = Some(PaymentId([1; 32]));
1051 let event = Event::PaymentPathFailed {
1054 network_update: None,
1055 payment_failed_permanently: false,
1056 all_paths_failed: false,
1057 path: TestRouter::path_for_value(final_value_msat),
1058 short_channel_id: None,
1059 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1061 invoice_payer.handle_event(event.clone());
1062 assert_eq!(*event_handled.borrow(), false);
1063 assert_eq!(*payer.attempts.borrow(), 1);
1065 invoice_payer.handle_event(event.clone());
1066 assert_eq!(*event_handled.borrow(), false);
1067 assert_eq!(*payer.attempts.borrow(), 2);
1069 invoice_payer.handle_event(Event::PaymentSent {
1070 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1072 assert_eq!(*event_handled.borrow(), true);
1073 assert_eq!(*payer.attempts.borrow(), 2);
1077 fn fails_paying_invoice_after_max_retry_counts() {
1078 let event_handled = core::cell::RefCell::new(false);
1079 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1081 let payment_preimage = PaymentPreimage([1; 32]);
1082 let invoice = invoice(payment_preimage);
1083 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1085 let payer = TestPayer::new()
1086 .expect_send(Amount::ForInvoice(final_value_msat))
1087 .expect_send(Amount::OnRetry(final_value_msat / 2))
1088 .expect_send(Amount::OnRetry(final_value_msat / 2));
1089 let router = TestRouter::new(TestScorer::new());
1090 let logger = TestLogger::new();
1092 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1094 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1095 assert_eq!(*payer.attempts.borrow(), 1);
1097 let event = Event::PaymentPathFailed {
1099 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1100 network_update: None,
1101 payment_failed_permanently: false,
1102 all_paths_failed: true,
1103 path: TestRouter::path_for_value(final_value_msat),
1104 short_channel_id: None,
1105 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1107 invoice_payer.handle_event(event);
1108 assert_eq!(*event_handled.borrow(), false);
1109 assert_eq!(*payer.attempts.borrow(), 2);
1111 let event = Event::PaymentPathFailed {
1113 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1114 network_update: None,
1115 payment_failed_permanently: false,
1116 all_paths_failed: false,
1117 path: TestRouter::path_for_value(final_value_msat / 2),
1118 short_channel_id: None,
1119 retry: Some(RouteParameters {
1120 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1123 invoice_payer.handle_event(event.clone());
1124 assert_eq!(*event_handled.borrow(), false);
1125 assert_eq!(*payer.attempts.borrow(), 3);
1127 invoice_payer.handle_event(event.clone());
1128 assert_eq!(*event_handled.borrow(), true);
1129 assert_eq!(*payer.attempts.borrow(), 3);
1132 #[cfg(feature = "std")]
1134 fn fails_paying_invoice_after_max_retry_timeout() {
1135 let event_handled = core::cell::RefCell::new(false);
1136 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1138 let payment_preimage = PaymentPreimage([1; 32]);
1139 let invoice = invoice(payment_preimage);
1140 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1142 let payer = TestPayer::new()
1143 .expect_send(Amount::ForInvoice(final_value_msat))
1144 .expect_send(Amount::OnRetry(final_value_msat / 2));
1146 let router = TestRouter::new(TestScorer::new());
1147 let logger = TestLogger::new();
1148 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1151 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1153 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1154 assert_eq!(*payer.attempts.borrow(), 1);
1156 let event = Event::PaymentPathFailed {
1158 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1159 network_update: None,
1160 payment_failed_permanently: false,
1161 all_paths_failed: true,
1162 path: TestRouter::path_for_value(final_value_msat),
1163 short_channel_id: None,
1164 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1166 invoice_payer.handle_event(event.clone());
1167 assert_eq!(*event_handled.borrow(), false);
1168 assert_eq!(*payer.attempts.borrow(), 2);
1170 SinceEpoch::advance(Duration::from_secs(121));
1172 invoice_payer.handle_event(event.clone());
1173 assert_eq!(*event_handled.borrow(), true);
1174 assert_eq!(*payer.attempts.borrow(), 2);
1178 fn fails_paying_invoice_with_missing_retry_params() {
1179 let event_handled = core::cell::RefCell::new(false);
1180 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1182 let payment_preimage = PaymentPreimage([1; 32]);
1183 let invoice = invoice(payment_preimage);
1184 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1186 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1187 let router = TestRouter::new(TestScorer::new());
1188 let logger = TestLogger::new();
1190 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1192 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1193 assert_eq!(*payer.attempts.borrow(), 1);
1195 let event = Event::PaymentPathFailed {
1197 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1198 network_update: None,
1199 payment_failed_permanently: false,
1200 all_paths_failed: false,
1202 short_channel_id: None,
1205 invoice_payer.handle_event(event);
1206 assert_eq!(*event_handled.borrow(), true);
1207 assert_eq!(*payer.attempts.borrow(), 1);
1210 // Expiration is checked only in an std environment
1211 #[cfg(feature = "std")]
1213 fn fails_paying_invoice_after_expiration() {
1214 let event_handled = core::cell::RefCell::new(false);
1215 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1217 let payer = TestPayer::new();
1218 let router = TestRouter::new(TestScorer::new());
1219 let logger = TestLogger::new();
1221 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1223 let payment_preimage = PaymentPreimage([1; 32]);
1224 let invoice = expired_invoice(payment_preimage);
1225 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1226 assert_eq!(msg, "Invoice expired prior to send");
1227 } else { panic!("Expected Invoice Error"); }
1230 // Expiration is checked only in an std environment
1231 #[cfg(feature = "std")]
1233 fn fails_retrying_invoice_after_expiration() {
1234 let event_handled = core::cell::RefCell::new(false);
1235 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1237 let payment_preimage = PaymentPreimage([1; 32]);
1238 let invoice = invoice(payment_preimage);
1239 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1241 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1242 let router = TestRouter::new(TestScorer::new());
1243 let logger = TestLogger::new();
1245 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1247 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1248 assert_eq!(*payer.attempts.borrow(), 1);
1250 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1251 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1252 .checked_sub(Duration::from_secs(2)).unwrap()
1253 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1254 let event = Event::PaymentPathFailed {
1256 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1257 network_update: None,
1258 payment_failed_permanently: false,
1259 all_paths_failed: false,
1261 short_channel_id: None,
1262 retry: Some(retry_data),
1264 invoice_payer.handle_event(event);
1265 assert_eq!(*event_handled.borrow(), true);
1266 assert_eq!(*payer.attempts.borrow(), 1);
1270 fn fails_paying_invoice_after_retry_error() {
1271 let event_handled = core::cell::RefCell::new(false);
1272 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1274 let payment_preimage = PaymentPreimage([1; 32]);
1275 let invoice = invoice(payment_preimage);
1276 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1278 let payer = TestPayer::new()
1279 .fails_on_attempt(2)
1280 .expect_send(Amount::ForInvoice(final_value_msat))
1281 .expect_send(Amount::OnRetry(final_value_msat / 2));
1282 let router = TestRouter::new(TestScorer::new());
1283 let logger = TestLogger::new();
1285 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1287 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1288 assert_eq!(*payer.attempts.borrow(), 1);
1290 let event = Event::PaymentPathFailed {
1292 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1293 network_update: None,
1294 payment_failed_permanently: false,
1295 all_paths_failed: false,
1296 path: TestRouter::path_for_value(final_value_msat / 2),
1297 short_channel_id: None,
1298 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1300 invoice_payer.handle_event(event);
1301 assert_eq!(*event_handled.borrow(), true);
1302 assert_eq!(*payer.attempts.borrow(), 2);
1306 fn fails_paying_invoice_after_rejected_by_payee() {
1307 let event_handled = core::cell::RefCell::new(false);
1308 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1310 let payment_preimage = PaymentPreimage([1; 32]);
1311 let invoice = invoice(payment_preimage);
1312 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1314 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1315 let router = TestRouter::new(TestScorer::new());
1316 let logger = TestLogger::new();
1318 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1320 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1321 assert_eq!(*payer.attempts.borrow(), 1);
1323 let event = Event::PaymentPathFailed {
1325 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1326 network_update: None,
1327 payment_failed_permanently: true,
1328 all_paths_failed: false,
1330 short_channel_id: None,
1331 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1333 invoice_payer.handle_event(event);
1334 assert_eq!(*event_handled.borrow(), true);
1335 assert_eq!(*payer.attempts.borrow(), 1);
1339 fn fails_repaying_invoice_with_pending_payment() {
1340 let event_handled = core::cell::RefCell::new(false);
1341 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1343 let payment_preimage = PaymentPreimage([1; 32]);
1344 let invoice = invoice(payment_preimage);
1345 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1347 let payer = TestPayer::new()
1348 .expect_send(Amount::ForInvoice(final_value_msat))
1349 .expect_send(Amount::ForInvoice(final_value_msat));
1350 let router = TestRouter::new(TestScorer::new());
1351 let logger = TestLogger::new();
1353 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1355 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1357 // Cannot repay an invoice pending payment.
1358 match invoice_payer.pay_invoice(&invoice) {
1359 Err(PaymentError::Invoice("payment pending")) => {},
1360 Err(_) => panic!("unexpected error"),
1361 Ok(_) => panic!("expected invoice error"),
1364 // Can repay an invoice once cleared from cache.
1365 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1366 invoice_payer.remove_cached_payment(&payment_hash);
1367 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1369 // Cannot retry paying an invoice if cleared from cache.
1370 invoice_payer.remove_cached_payment(&payment_hash);
1371 let event = Event::PaymentPathFailed {
1374 network_update: None,
1375 payment_failed_permanently: false,
1376 all_paths_failed: false,
1378 short_channel_id: None,
1379 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1381 invoice_payer.handle_event(event);
1382 assert_eq!(*event_handled.borrow(), true);
1386 fn fails_paying_invoice_with_routing_errors() {
1387 let payer = TestPayer::new();
1388 let router = FailingRouter {};
1389 let logger = TestLogger::new();
1391 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1393 let payment_preimage = PaymentPreimage([1; 32]);
1394 let invoice = invoice(payment_preimage);
1395 match invoice_payer.pay_invoice(&invoice) {
1396 Err(PaymentError::Routing(_)) => {},
1397 Err(_) => panic!("unexpected error"),
1398 Ok(_) => panic!("expected routing error"),
1403 fn fails_paying_invoice_with_sending_errors() {
1404 let payment_preimage = PaymentPreimage([1; 32]);
1405 let invoice = invoice(payment_preimage);
1406 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1408 let payer = TestPayer::new()
1409 .fails_on_attempt(1)
1410 .expect_send(Amount::ForInvoice(final_value_msat));
1411 let router = TestRouter::new(TestScorer::new());
1412 let logger = TestLogger::new();
1414 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1416 match invoice_payer.pay_invoice(&invoice) {
1417 Err(PaymentError::Sending(_)) => {},
1418 Err(_) => panic!("unexpected error"),
1419 Ok(_) => panic!("expected sending error"),
1424 fn pays_zero_value_invoice_using_amount() {
1425 let event_handled = core::cell::RefCell::new(false);
1426 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1428 let payment_preimage = PaymentPreimage([1; 32]);
1429 let invoice = zero_value_invoice(payment_preimage);
1430 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1431 let final_value_msat = 100;
1433 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1434 let router = TestRouter::new(TestScorer::new());
1435 let logger = TestLogger::new();
1437 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1440 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1441 assert_eq!(*payer.attempts.borrow(), 1);
1443 invoice_payer.handle_event(Event::PaymentSent {
1444 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1446 assert_eq!(*event_handled.borrow(), true);
1447 assert_eq!(*payer.attempts.borrow(), 1);
1451 fn fails_paying_zero_value_invoice_with_amount() {
1452 let event_handled = core::cell::RefCell::new(false);
1453 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1455 let payer = TestPayer::new();
1456 let router = TestRouter::new(TestScorer::new());
1457 let logger = TestLogger::new();
1459 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1461 let payment_preimage = PaymentPreimage([1; 32]);
1462 let invoice = invoice(payment_preimage);
1464 // Cannot repay an invoice pending payment.
1465 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1466 Err(PaymentError::Invoice("amount unexpected")) => {},
1467 Err(_) => panic!("unexpected error"),
1468 Ok(_) => panic!("expected invoice error"),
1473 fn pays_pubkey_with_amount() {
1474 let event_handled = core::cell::RefCell::new(false);
1475 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1477 let pubkey = pubkey();
1478 let payment_preimage = PaymentPreimage([1; 32]);
1479 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1480 let final_value_msat = 100;
1481 let final_cltv_expiry_delta = 42;
1483 let payer = TestPayer::new()
1484 .expect_send(Amount::Spontaneous(final_value_msat))
1485 .expect_send(Amount::OnRetry(final_value_msat));
1486 let router = TestRouter::new(TestScorer::new());
1487 let logger = TestLogger::new();
1489 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1491 let payment_id = Some(invoice_payer.pay_pubkey(
1492 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1494 assert_eq!(*payer.attempts.borrow(), 1);
1496 let retry = RouteParameters {
1497 payment_params: PaymentParameters::for_keysend(pubkey),
1499 final_cltv_expiry_delta,
1501 let event = Event::PaymentPathFailed {
1504 network_update: None,
1505 payment_failed_permanently: false,
1506 all_paths_failed: false,
1508 short_channel_id: None,
1511 invoice_payer.handle_event(event);
1512 assert_eq!(*event_handled.borrow(), false);
1513 assert_eq!(*payer.attempts.borrow(), 2);
1515 invoice_payer.handle_event(Event::PaymentSent {
1516 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1518 assert_eq!(*event_handled.borrow(), true);
1519 assert_eq!(*payer.attempts.borrow(), 2);
1523 fn scores_failed_channel() {
1524 let event_handled = core::cell::RefCell::new(false);
1525 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1527 let payment_preimage = PaymentPreimage([1; 32]);
1528 let invoice = invoice(payment_preimage);
1529 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1530 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1531 let path = TestRouter::path_for_value(final_value_msat);
1532 let short_channel_id = Some(path[0].short_channel_id);
1534 // Expect that scorer is given short_channel_id upon handling the event.
1535 let payer = TestPayer::new()
1536 .expect_send(Amount::ForInvoice(final_value_msat))
1537 .expect_send(Amount::OnRetry(final_value_msat / 2));
1538 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1539 path: path.clone(), short_channel_id: path[0].short_channel_id,
1541 let router = TestRouter::new(scorer);
1542 let logger = TestLogger::new();
1544 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1546 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1547 let event = Event::PaymentPathFailed {
1550 network_update: None,
1551 payment_failed_permanently: false,
1552 all_paths_failed: false,
1555 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1557 invoice_payer.handle_event(event);
1561 fn scores_successful_channels() {
1562 let event_handled = core::cell::RefCell::new(false);
1563 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1565 let payment_preimage = PaymentPreimage([1; 32]);
1566 let invoice = invoice(payment_preimage);
1567 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1568 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1569 let route = TestRouter::route_for_value(final_value_msat);
1571 // Expect that scorer is given short_channel_id upon handling the event.
1572 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1573 let scorer = TestScorer::new()
1574 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1575 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1576 let router = TestRouter::new(scorer);
1577 let logger = TestLogger::new();
1579 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1581 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1582 let event = Event::PaymentPathSuccessful {
1583 payment_id, payment_hash, path: route.paths[0].clone()
1585 invoice_payer.handle_event(event);
1586 let event = Event::PaymentPathSuccessful {
1587 payment_id, payment_hash, path: route.paths[1].clone()
1589 invoice_payer.handle_event(event);
1593 fn generates_correct_inflight_map_data() {
1594 let event_handled = core::cell::RefCell::new(false);
1595 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1597 let payment_preimage = PaymentPreimage([1; 32]);
1598 let invoice = invoice(payment_preimage);
1599 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1600 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1602 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1603 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1604 let route = TestRouter::route_for_value(final_value_msat);
1605 let router = TestRouter::new(TestScorer::new());
1606 let logger = TestLogger::new();
1608 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1610 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1612 let inflight_map = invoice_payer.create_inflight_map();
1614 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1615 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1616 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1618 // Second path check
1619 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1620 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1622 invoice_payer.handle_event(Event::PaymentPathSuccessful {
1623 payment_id, payment_hash, path: route.paths[0].clone()
1626 let inflight_map = invoice_payer.create_inflight_map();
1628 assert_eq!(inflight_map.0.get(&(0, false)), None);
1629 assert_eq!(inflight_map.0.get(&(1, true)), None);
1630 assert_eq!(inflight_map.0.get(&(2, false)), None);
1632 // Second path should still be inflight
1633 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1634 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1638 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1639 // First, let's just send a payment through, but only make sure one of the path completes
1640 let event_handled = core::cell::RefCell::new(false);
1641 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1643 let payment_preimage = PaymentPreimage([1; 32]);
1644 let payment_invoice = invoice(payment_preimage);
1645 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1646 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1648 let payer = TestPayer::new()
1649 .expect_send(Amount::ForInvoice(final_value_msat))
1650 .expect_send(Amount::ForInvoice(final_value_msat));
1651 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1652 let route = TestRouter::route_for_value(final_value_msat);
1653 let scorer = TestScorer::new()
1654 // 1st invoice, 1st path
1655 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1656 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1657 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1658 // 1st invoice, 2nd path
1659 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1660 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1661 // 2nd invoice, 1st path
1662 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1663 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1664 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1665 // 2nd invoice, 2nd path
1666 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1667 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1668 let router = TestRouter::new(scorer);
1669 let logger = TestLogger::new();
1671 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1673 // Succeed 1st path, leave 2nd path inflight
1674 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1675 invoice_payer.handle_event(Event::PaymentPathSuccessful {
1676 payment_id, payment_hash, path: route.paths[0].clone()
1679 // Let's pay a second invoice that will be using the same path. This should trigger the
1680 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1681 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1682 // have 64 msats inflight for paths considering the channel with scid of 1.
1683 let payment_preimage_2 = PaymentPreimage([2; 32]);
1684 let payment_invoice_2 = invoice(payment_preimage_2);
1685 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1689 fn considers_inflight_htlcs_between_retries() {
1690 // First, let's just send a payment through, but only make sure one of the path completes
1691 let event_handled = core::cell::RefCell::new(false);
1692 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1694 let payment_preimage = PaymentPreimage([1; 32]);
1695 let payment_invoice = invoice(payment_preimage);
1696 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1697 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1699 let payer = TestPayer::new()
1700 .expect_send(Amount::ForInvoice(final_value_msat))
1701 .expect_send(Amount::OnRetry(final_value_msat / 2))
1702 .expect_send(Amount::OnRetry(final_value_msat / 4));
1703 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1704 let scorer = TestScorer::new()
1705 // 1st invoice, 1st path
1706 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1707 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1708 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1709 // 1st invoice, 2nd path
1710 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1711 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1712 // Retry 1, 1st path
1713 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1714 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1715 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1716 // Retry 1, 2nd path
1717 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1718 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1719 // Retry 2, 1st path
1720 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1721 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1722 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1723 // Retry 2, 2nd path
1724 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1725 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1726 let router = TestRouter::new(scorer);
1727 let logger = TestLogger::new();
1729 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1731 // Fail 1st path, leave 2nd path inflight
1732 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1733 invoice_payer.handle_event(Event::PaymentPathFailed {
1736 network_update: None,
1737 payment_failed_permanently: false,
1738 all_paths_failed: false,
1739 path: TestRouter::path_for_value(final_value_msat),
1740 short_channel_id: None,
1741 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1744 // Fails again the 1st path of our retry
1745 invoice_payer.handle_event(Event::PaymentPathFailed {
1748 network_update: None,
1749 payment_failed_permanently: false,
1750 all_paths_failed: false,
1751 path: TestRouter::path_for_value(final_value_msat / 2),
1752 short_channel_id: None,
1753 retry: Some(RouteParameters {
1754 final_value_msat: final_value_msat / 4,
1755 ..TestRouter::retry_for_invoice(&payment_invoice)
1761 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1762 let event_handled = core::cell::RefCell::new(false);
1763 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1765 let payment_preimage = PaymentPreimage([1; 32]);
1766 let invoice_to_pay = invoice(payment_preimage);
1767 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1769 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1770 let payer = TestPayer::new()
1771 .fails_with_partial_failure(
1772 retry.clone(), OnAttempt(1),
1774 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1776 .expect_send(Amount::ForInvoice(final_value_msat));
1778 let router = TestRouter::new(TestScorer::new());
1779 let logger = TestLogger::new();
1781 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1783 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1784 let inflight_map = invoice_payer.create_inflight_map();
1786 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1787 // inflight map because retries are disabled.
1788 assert_eq!(inflight_map.0.len(), 2);
1792 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1793 let event_handled = core::cell::RefCell::new(false);
1794 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1796 let payment_preimage = PaymentPreimage([1; 32]);
1797 let invoice_to_pay = invoice(payment_preimage);
1798 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1800 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1801 let payer = TestPayer::new()
1802 .fails_with_partial_failure(
1803 retry.clone(), OnAttempt(1),
1805 Ok(()), Err(MonitorUpdateInProgress)
1807 .expect_send(Amount::ForInvoice(final_value_msat));
1809 let router = TestRouter::new(TestScorer::new());
1810 let logger = TestLogger::new();
1812 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1814 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1815 let inflight_map = invoice_payer.create_inflight_map();
1817 // All paths successful, hence we check of the existence of all 5 hops.
1818 assert_eq!(inflight_map.0.len(), 5);
1822 scorer: RefCell<TestScorer>,
1826 fn new(scorer: TestScorer) -> Self {
1827 TestRouter { scorer: RefCell::new(scorer) }
1830 fn route_for_value(final_value_msat: u64) -> Route {
1835 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1836 channel_features: ChannelFeatures::empty(),
1837 node_features: NodeFeatures::empty(),
1838 short_channel_id: 0,
1840 cltv_expiry_delta: 0
1843 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1844 channel_features: ChannelFeatures::empty(),
1845 node_features: NodeFeatures::empty(),
1846 short_channel_id: 1,
1848 cltv_expiry_delta: 0
1851 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1852 channel_features: ChannelFeatures::empty(),
1853 node_features: NodeFeatures::empty(),
1854 short_channel_id: 2,
1855 fee_msat: final_value_msat / 2,
1856 cltv_expiry_delta: 0
1861 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1862 channel_features: ChannelFeatures::empty(),
1863 node_features: NodeFeatures::empty(),
1864 short_channel_id: 3,
1866 cltv_expiry_delta: 144
1869 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1870 channel_features: ChannelFeatures::empty(),
1871 node_features: NodeFeatures::empty(),
1872 short_channel_id: 4,
1873 fee_msat: final_value_msat / 2,
1874 cltv_expiry_delta: 144
1878 payment_params: None,
1882 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1883 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1886 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1887 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1888 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1889 .with_route_hints(invoice.route_hints());
1890 if let Some(features) = invoice.features() {
1891 payment_params = payment_params.with_features(features.clone());
1893 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1897 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1902 impl Router for TestRouter {
1904 &self, payer: &PublicKey, route_params: &RouteParameters,
1905 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1906 ) -> Result<Route, LightningError> {
1907 // Simulate calling the Scorer just as you would in find_route
1908 let route = Self::route_for_value(route_params.final_value_msat);
1909 let mut locked_scorer = self.scorer.lock();
1910 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1911 for path in route.paths {
1912 let mut aggregate_msat = 0u64;
1913 for (idx, hop) in path.iter().rev().enumerate() {
1914 aggregate_msat += hop.fee_msat;
1915 let usage = ChannelUsage {
1916 amount_msat: aggregate_msat,
1917 inflight_htlc_msat: 0,
1918 effective_capacity: EffectiveCapacity::Unknown,
1921 // Since the path is reversed, the last element in our iteration is the first
1923 if idx == path.len() - 1 {
1924 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1926 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1932 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1937 impl ScoringRouter for TestRouter {
1938 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1939 self.scorer.lock().payment_path_failed(path, short_channel_id);
1942 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1943 self.scorer.lock().payment_path_successful(path);
1946 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1947 self.scorer.lock().probe_successful(path);
1950 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1951 self.scorer.lock().probe_failed(path, short_channel_id);
1955 struct FailingRouter;
1957 impl Router for FailingRouter {
1959 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1960 _inflight_htlcs: InFlightHtlcs,
1961 ) -> Result<Route, LightningError> {
1962 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1966 impl ScoringRouter for FailingRouter {
1967 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1969 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1971 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1973 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1977 event_expectations: Option<VecDeque<TestResult>>,
1978 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1983 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1984 PaymentSuccess { path: Vec<RouteHop> },
1990 event_expectations: None,
1991 scorer_expectations: RefCell::new(None),
1995 fn expect(mut self, expectation: TestResult) -> Self {
1996 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
2000 fn expect_usage(self, expectation: ChannelUsage) -> Self {
2001 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
2007 impl lightning::util::ser::Writeable for TestScorer {
2008 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
2011 impl Score for TestScorer {
2012 fn channel_penalty_msat(
2013 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
2015 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
2016 match scorer_expectations.pop_front() {
2017 Some(expectation) => {
2018 assert_eq!(expectation.amount_msat, usage.amount_msat);
2019 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
2027 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
2028 if let Some(expectations) = &mut self.event_expectations {
2029 match expectations.pop_front() {
2030 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
2031 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2032 assert_eq!(actual_short_channel_id, short_channel_id);
2034 Some(TestResult::PaymentSuccess { path }) => {
2035 panic!("Unexpected successful payment path: {:?}", path)
2037 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2042 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
2043 if let Some(expectations) = &mut self.event_expectations {
2044 match expectations.pop_front() {
2045 Some(TestResult::PaymentFailure { path, .. }) => {
2046 panic!("Unexpected payment path failure: {:?}", path)
2048 Some(TestResult::PaymentSuccess { path }) => {
2049 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2051 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2056 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
2057 if let Some(expectations) = &mut self.event_expectations {
2058 match expectations.pop_front() {
2059 Some(TestResult::PaymentFailure { path, .. }) => {
2060 panic!("Unexpected failed payment path: {:?}", path)
2062 Some(TestResult::PaymentSuccess { path }) => {
2063 panic!("Unexpected successful payment path: {:?}", path)
2065 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2069 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
2070 if let Some(expectations) = &mut self.event_expectations {
2071 match expectations.pop_front() {
2072 Some(TestResult::PaymentFailure { path, .. }) => {
2073 panic!("Unexpected payment path failure: {:?}", path)
2075 Some(TestResult::PaymentSuccess { path }) => {
2076 panic!("Unexpected successful payment path: {:?}", path)
2078 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2084 impl Drop for TestScorer {
2085 fn drop(&mut self) {
2086 if std::thread::panicking() {
2090 if let Some(event_expectations) = &self.event_expectations {
2091 if !event_expectations.is_empty() {
2092 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2096 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2097 if !scorer_expectations.is_empty() {
2098 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2105 expectations: core::cell::RefCell<VecDeque<Amount>>,
2106 attempts: core::cell::RefCell<usize>,
2107 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2110 #[derive(Clone, Debug, PartialEq, Eq)]
2117 struct OnAttempt(usize);
2122 expectations: core::cell::RefCell::new(VecDeque::new()),
2123 attempts: core::cell::RefCell::new(0),
2124 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2128 fn expect_send(self, value_msat: Amount) -> Self {
2129 self.expectations.borrow_mut().push_back(value_msat);
2133 fn fails_on_attempt(self, attempt: usize) -> Self {
2134 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2135 self.fails_with(failure, OnAttempt(attempt))
2138 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2139 self.fails_with(PaymentSendFailure::PartialFailure {
2140 results: results.unwrap_or(vec![]),
2141 failed_paths_retry: Some(retry),
2142 payment_id: PaymentId([1; 32]),
2146 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2147 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2151 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
2152 let mut attempts = self.attempts.borrow_mut();
2155 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2156 Some(failure) => Err(failure),
2161 fn check_value_msats(&self, actual_value_msats: Amount) {
2162 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2163 if let Some(expected_value_msats) = expected_value_msats {
2164 assert_eq!(actual_value_msats, expected_value_msats);
2166 panic!("Unexpected amount: {:?}", actual_value_msats);
2171 impl Drop for TestPayer {
2172 fn drop(&mut self) {
2173 if std::thread::panicking() {
2177 if !self.expectations.borrow().is_empty() {
2178 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2183 impl Payer for TestPayer {
2184 fn node_id(&self) -> PublicKey {
2185 let secp_ctx = Secp256k1::new();
2186 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2189 fn first_hops(&self) -> Vec<ChannelDetails> {
2194 &self, route: &Route, _payment_hash: PaymentHash,
2195 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2196 ) -> Result<(), PaymentSendFailure> {
2197 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2198 self.check_attempts()
2201 fn send_spontaneous_payment(
2202 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2203 ) -> Result<(), PaymentSendFailure> {
2204 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2205 self.check_attempts()
2209 &self, route: &Route, _payment_id: PaymentId
2210 ) -> Result<(), PaymentSendFailure> {
2211 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2212 self.check_attempts()
2215 fn abandon_payment(&self, _payment_id: PaymentId) { }
2218 // *** Full Featured Functional Tests with a Real ChannelManager ***
2219 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2221 impl Router for ManualRouter {
2223 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2224 _inflight_htlcs: InFlightHtlcs
2225 ) -> Result<Route, LightningError> {
2226 self.0.borrow_mut().pop_front().unwrap()
2229 impl ScoringRouter for ManualRouter {
2230 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2232 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2234 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2236 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2239 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2240 self.0.borrow_mut().push_back(result);
2243 impl Drop for ManualRouter {
2244 fn drop(&mut self) {
2245 if std::thread::panicking() {
2248 assert!(self.0.borrow_mut().is_empty());
2253 fn retry_multi_path_single_failed_payment() {
2254 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2255 let chanmon_cfgs = create_chanmon_cfgs(2);
2256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2258 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2260 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2261 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2262 let chans = nodes[0].node.list_usable_channels();
2263 let mut route = Route {
2266 pubkey: nodes[1].node.get_our_node_id(),
2267 node_features: channelmanager::provided_node_features(),
2268 short_channel_id: chans[0].short_channel_id.unwrap(),
2269 channel_features: channelmanager::provided_channel_features(),
2271 cltv_expiry_delta: 100,
2274 pubkey: nodes[1].node.get_our_node_id(),
2275 node_features: channelmanager::provided_node_features(),
2276 short_channel_id: chans[1].short_channel_id.unwrap(),
2277 channel_features: channelmanager::provided_channel_features(),
2278 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2279 cltv_expiry_delta: 100,
2282 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2284 let router = ManualRouter(RefCell::new(VecDeque::new()));
2285 router.expect_find_route(Ok(route.clone()));
2286 // On retry, split the payment across both channels.
2287 route.paths[0][0].fee_msat = 50_000_001;
2288 route.paths[1][0].fee_msat = 50_000_000;
2289 router.expect_find_route(Ok(route.clone()));
2291 let event_handler = |_: Event| { panic!(); };
2292 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2294 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2295 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2296 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2298 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2299 assert_eq!(htlc_msgs.len(), 2);
2300 check_added_monitors!(nodes[0], 2);
2304 fn immediate_retry_on_failure() {
2305 // Tests that we can/will retry immediately after a failure
2306 let chanmon_cfgs = create_chanmon_cfgs(2);
2307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2311 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2312 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2313 let chans = nodes[0].node.list_usable_channels();
2314 let mut route = Route {
2317 pubkey: nodes[1].node.get_our_node_id(),
2318 node_features: channelmanager::provided_node_features(),
2319 short_channel_id: chans[0].short_channel_id.unwrap(),
2320 channel_features: channelmanager::provided_channel_features(),
2321 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2322 cltv_expiry_delta: 100,
2325 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2327 let router = ManualRouter(RefCell::new(VecDeque::new()));
2328 router.expect_find_route(Ok(route.clone()));
2329 // On retry, split the payment across both channels.
2330 route.paths.push(route.paths[0].clone());
2331 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2332 route.paths[0][0].fee_msat = 50_000_000;
2333 route.paths[1][0].fee_msat = 50_000_001;
2334 router.expect_find_route(Ok(route.clone()));
2336 let event_handler = |_: Event| { panic!(); };
2337 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2339 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2340 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2341 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2343 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2344 assert_eq!(htlc_msgs.len(), 2);
2345 check_added_monitors!(nodes[0], 2);
2349 fn no_extra_retries_on_back_to_back_fail() {
2350 // In a previous release, we had a race where we may exceed the payment retry count if we
2351 // get two failures in a row with the second having `all_paths_failed` set.
2352 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2353 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2354 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2355 // pending which we will see later. Thus, when we previously removed the retry tracking map
2356 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2357 // retry entry even though more events for the same payment were still pending. This led to
2358 // us retrying a payment again even though we'd already given up on it.
2360 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2361 // is used to remove the payment retry counter entries instead. This tests for the specific
2362 // excess-retry case while also testing `PaymentFailed` generation.
2364 let chanmon_cfgs = create_chanmon_cfgs(3);
2365 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2366 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2367 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2369 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2370 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2372 let mut route = Route {
2375 pubkey: nodes[1].node.get_our_node_id(),
2376 node_features: channelmanager::provided_node_features(),
2377 short_channel_id: chan_1_scid,
2378 channel_features: channelmanager::provided_channel_features(),
2380 cltv_expiry_delta: 100,
2382 pubkey: nodes[2].node.get_our_node_id(),
2383 node_features: channelmanager::provided_node_features(),
2384 short_channel_id: chan_2_scid,
2385 channel_features: channelmanager::provided_channel_features(),
2386 fee_msat: 100_000_000,
2387 cltv_expiry_delta: 100,
2390 pubkey: nodes[1].node.get_our_node_id(),
2391 node_features: channelmanager::provided_node_features(),
2392 short_channel_id: chan_1_scid,
2393 channel_features: channelmanager::provided_channel_features(),
2395 cltv_expiry_delta: 100,
2397 pubkey: nodes[2].node.get_our_node_id(),
2398 node_features: channelmanager::provided_node_features(),
2399 short_channel_id: chan_2_scid,
2400 channel_features: channelmanager::provided_channel_features(),
2401 fee_msat: 100_000_000,
2402 cltv_expiry_delta: 100,
2405 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2407 let router = ManualRouter(RefCell::new(VecDeque::new()));
2408 router.expect_find_route(Ok(route.clone()));
2409 // On retry, we'll only be asked for one path
2410 route.paths.remove(1);
2411 router.expect_find_route(Ok(route.clone()));
2413 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2414 let event_handler = |event: Event| {
2415 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2416 event_checker(event);
2418 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2420 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2421 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2422 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2424 let htlc_updates = SendEvent::from_node(&nodes[0]);
2425 check_added_monitors!(nodes[0], 1);
2426 assert_eq!(htlc_updates.msgs.len(), 1);
2428 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2429 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2430 check_added_monitors!(nodes[1], 1);
2431 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2433 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2434 check_added_monitors!(nodes[0], 1);
2435 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2437 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2438 check_added_monitors!(nodes[0], 1);
2439 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2441 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2442 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2443 check_added_monitors!(nodes[1], 1);
2444 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2446 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2447 check_added_monitors!(nodes[1], 1);
2448 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2450 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2451 check_added_monitors!(nodes[0], 1);
2453 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2454 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2455 check_added_monitors!(nodes[0], 1);
2456 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2458 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2459 check_added_monitors!(nodes[1], 1);
2460 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2462 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2463 check_added_monitors!(nodes[1], 1);
2464 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2466 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2467 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2468 check_added_monitors!(nodes[0], 1);
2470 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2471 check_added_monitors!(nodes[0], 1);
2472 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2474 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2475 check_added_monitors!(nodes[1], 1);
2476 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2477 check_added_monitors!(nodes[1], 1);
2478 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2481 check_added_monitors!(nodes[0], 1);
2483 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2484 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2485 // with it set. The first event will use up the only retry we are allowed, with the second
2486 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2487 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2488 // if the final HTLC failed.
2489 expected_events.borrow_mut().push_back(&|ev: Event| {
2490 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2491 assert!(!payment_failed_permanently);
2492 assert!(all_paths_failed);
2493 } else { panic!("Unexpected event"); }
2495 nodes[0].node.process_pending_events(&invoice_payer);
2496 assert!(expected_events.borrow().is_empty());
2498 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2499 check_added_monitors!(nodes[0], 1);
2501 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2502 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2503 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2504 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2505 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2507 expected_events.borrow_mut().push_back(&|ev: Event| {
2508 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2509 assert!(!payment_failed_permanently);
2510 assert!(all_paths_failed);
2511 } else { panic!("Unexpected event"); }
2513 expected_events.borrow_mut().push_back(&|ev: Event| {
2514 if let Event::PaymentFailed { .. } = ev {
2515 } else { panic!("Unexpected event"); }
2517 nodes[0].node.process_pending_events(&invoice_payer);
2518 assert!(expected_events.borrow().is_empty());