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::gossip::NodeId;
149 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router};
150 use lightning::util::errors::APIError;
151 use lightning::util::events::{Event, EventHandler};
152 use lightning::util::logger::Logger;
153 use crate::time_utils::Time;
154 use crate::sync::Mutex;
156 use secp256k1::PublicKey;
159 use core::fmt::{Debug, Display, Formatter};
160 use core::future::Future;
161 use core::ops::Deref;
162 use core::time::Duration;
163 #[cfg(feature = "std")]
164 use std::time::SystemTime;
166 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
168 /// See [module-level documentation] for details.
170 /// [module-level documentation]: crate::payment
171 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
173 #[cfg(not(feature = "no-std"))]
174 type ConfiguredTime = std::time::Instant;
175 #[cfg(feature = "no-std")]
176 use crate::time_utils;
177 #[cfg(feature = "no-std")]
178 type ConfiguredTime = time_utils::Eternity;
180 /// Sealed trait with a blanket implementation to allow both sync and async implementations of event
181 /// handling to exist within the InvoicePayer.
183 pub trait BaseEventHandler {}
184 impl<T> BaseEventHandler for T {}
187 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
188 pub struct InvoicePayerUsingTime<
192 E: sealed::BaseEventHandler,
202 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
203 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
207 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
208 /// currently being made, or have outstanding paths that need retrying.
209 struct PaymentInfo<T: Time> {
210 attempts: PaymentAttempts<T>,
211 paths: Vec<Vec<RouteHop>>,
214 impl<T: Time> PaymentInfo<T> {
217 attempts: PaymentAttempts::new(),
223 /// Storing minimal payment attempts information required for determining if a outbound payment can
225 #[derive(Clone, Copy)]
226 struct PaymentAttempts<T: Time> {
227 /// This count will be incremented only after the result of the attempt is known. When it's 0,
228 /// it means the result of the first attempt is now known yet.
230 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
231 first_attempted_at: T
234 impl<T: Time> PaymentAttempts<T> {
238 first_attempted_at: T::now()
243 impl<T: Time> Display for PaymentAttempts<T> {
244 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
245 #[cfg(feature = "no-std")]
246 return write!( f, "attempts: {}", self.count);
247 #[cfg(not(feature = "no-std"))]
250 "attempts: {}, duration: {}s",
252 T::now().duration_since(self.first_attempted_at).as_secs()
257 /// A trait defining behavior of an [`Invoice`] payer.
259 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
260 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
262 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
264 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
265 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
266 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
267 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
269 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
271 /// Returns the payer's node id.
272 fn node_id(&self) -> PublicKey;
274 /// Returns the payer's channels.
275 fn first_hops(&self) -> Vec<ChannelDetails>;
277 /// Sends a payment over the Lightning Network using the given [`Route`].
279 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
280 payment_id: PaymentId
281 ) -> Result<(), PaymentSendFailure>;
283 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
284 fn send_spontaneous_payment(
285 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
286 ) -> Result<(), PaymentSendFailure>;
288 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
289 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
291 /// Signals that no further retries for the given payment will occur.
292 fn abandon_payment(&self, payment_id: PaymentId);
295 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
296 /// based on payment and probe success/failure.
298 /// [`Router`]: lightning::routing::router::Router
299 pub trait ScoringRouter: Router {
300 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
301 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
302 fn find_route_with_id(
303 &self, payer: &PublicKey, route_params: &RouteParameters,
304 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
305 _payment_hash: PaymentHash, _payment_id: PaymentId
306 ) -> Result<Route, LightningError> {
307 self.find_route(payer, route_params, first_hops, inflight_htlcs)
309 /// Lets the router know that payment through a specific path has failed.
310 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
311 /// Lets the router know that payment through a specific path was successful.
312 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
313 /// Lets the router know that a payment probe was successful.
314 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
315 /// Lets the router know that a payment probe failed.
316 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
319 /// Strategies available to retry payment path failures for an [`Invoice`].
321 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
323 /// Max number of attempts to retry payment.
325 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
326 /// payments, if this is less than the total number of paths, we will never even retry all of the
329 #[cfg(feature = "std")]
330 /// Time elapsed before abandoning retries for a payment.
335 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
336 match (self, attempts) {
337 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
338 max_retry_count >= &count
340 #[cfg(feature = "std")]
341 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
342 *max_duration >= T::now().duration_since(*first_attempted_at),
347 /// An error that may occur when making a payment.
348 #[derive(Clone, Debug)]
349 pub enum PaymentError {
350 /// An error resulting from the provided [`Invoice`] or payment hash.
351 Invoice(&'static str),
352 /// An error occurring when finding a route.
353 Routing(LightningError),
354 /// An error occurring when sending a payment.
355 Sending(PaymentSendFailure),
358 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
359 InvoicePayerUsingTime<P, R, L, E, T>
364 /// Creates an invoice payer that retries failed payment paths.
366 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
367 /// `retry` has been exceeded for a given [`Invoice`].
369 payer: P, router: R, logger: L, event_handler: E, retry: Retry
376 payment_cache: Mutex::new(HashMap::new()),
381 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
383 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
384 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
385 /// a second payment with the same [`PaymentHash`] is never sent.
387 /// If you wish to use a different payment idempotency token, see
388 /// [`Self::pay_invoice_with_id`].
389 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
390 let payment_id = PaymentId(invoice.payment_hash().into_inner());
391 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
394 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
395 /// in case a retry is needed.
397 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
398 /// payment completes or fails, no idempotency guarantees are made.
400 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
401 /// has never been paid before.
403 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
405 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
406 if invoice.amount_milli_satoshis().is_none() {
407 Err(PaymentError::Invoice("amount missing"))
409 self.pay_invoice_using_amount(invoice, None, payment_id)
413 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
414 /// case a retry is needed.
416 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
417 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
418 /// a second payment with the same [`PaymentHash`] is never sent.
420 /// If you wish to use a different payment idempotency token, see
421 /// [`Self::pay_zero_value_invoice_with_id`].
422 pub fn pay_zero_value_invoice(
423 &self, invoice: &Invoice, amount_msats: u64
424 ) -> Result<PaymentId, PaymentError> {
425 let payment_id = PaymentId(invoice.payment_hash().into_inner());
426 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
429 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
430 /// caching the invoice for later use in case a retry is needed.
432 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
433 /// payment completes or fails, no idempotency guarantees are made.
435 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
436 /// has never been paid before.
438 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
439 /// idempotency token.
440 pub fn pay_zero_value_invoice_with_id(
441 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
442 ) -> Result<(), PaymentError> {
443 if invoice.amount_milli_satoshis().is_some() {
444 Err(PaymentError::Invoice("amount unexpected"))
446 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
450 fn pay_invoice_using_amount(
451 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
452 ) -> Result<(), PaymentError> {
453 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
455 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
456 match self.payment_cache.lock().unwrap().entry(payment_hash) {
457 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
458 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
461 let payment_secret = Some(invoice.payment_secret().clone());
462 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
463 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
464 .with_route_hints(invoice.route_hints());
465 if let Some(features) = invoice.features() {
466 payment_params = payment_params.with_features(features.clone());
468 let route_params = RouteParameters {
470 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
471 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
474 let send_payment = |route: &Route| {
475 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
478 self.pay_internal(&route_params, payment_hash, send_payment)
479 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
482 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
483 /// case a retry is needed.
485 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
486 /// as long as the payment is still pending. Once the payment completes or fails, you must
487 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
489 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
490 final_cltv_expiry_delta: u32
491 ) -> Result<PaymentId, PaymentError> {
492 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
493 let payment_id = PaymentId(payment_hash.0);
494 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
495 final_cltv_expiry_delta)
496 .map(|()| payment_id)
499 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
500 /// caching the invoice for later use in case a retry is needed.
502 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
503 /// payment completes or fails, no idempotency guarantees are made.
505 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
506 /// [`PaymentHash`] has never been paid before.
507 pub fn pay_pubkey_with_id(
508 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
509 amount_msats: u64, final_cltv_expiry_delta: u32
510 ) -> Result<(), PaymentError> {
511 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
512 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
513 final_cltv_expiry_delta)
517 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
518 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
519 ) -> Result<(), PaymentError> {
520 match self.payment_cache.lock().unwrap().entry(payment_hash) {
521 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
522 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
525 let route_params = RouteParameters {
526 payment_params: PaymentParameters::for_keysend(pubkey),
527 final_value_msat: amount_msats,
528 final_cltv_expiry_delta,
531 let send_payment = |route: &Route| {
532 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
534 self.pay_internal(&route_params, payment_hash, send_payment)
535 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
538 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
539 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
540 ) -> Result<(), PaymentError> {
541 #[cfg(feature = "std")] {
542 if has_expired(params) {
543 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
544 return Err(PaymentError::Invoice("Invoice expired prior to send"));
548 let payer = self.payer.node_id();
549 let first_hops = self.payer.first_hops();
550 let inflight_htlcs = self.create_inflight_map();
551 let route = self.router.find_route(
552 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
553 ).map_err(|e| PaymentError::Routing(e))?;
555 match send_payment(&route) {
557 for path in route.paths {
558 self.process_path_inflight_htlcs(payment_hash, path);
563 PaymentSendFailure::ParameterError(_) => Err(e),
564 PaymentSendFailure::PathParameterError(_) => Err(e),
565 PaymentSendFailure::AllFailedRetrySafe(_) => {
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::AllFailedRetrySafe(_)) => {
677 self.retry_payment(payment_id, payment_hash, params)
679 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
680 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
681 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
682 // means that we are still waiting for our channel monitor update to complete.
683 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
685 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
686 self.process_path_inflight_htlcs(payment_hash, path);
692 if let Some(retry) = failed_paths_retry {
693 // Always return Ok for the same reason as noted in pay_internal.
694 let _ = self.retry_payment(payment_id, payment_hash, &retry);
701 /// Removes the payment cached by the given payment hash.
703 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
704 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
705 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
706 self.payment_cache.lock().unwrap().remove(payment_hash);
709 /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
710 /// channel id and direction to the amount being sent through it.
712 /// This function should be called whenever we need information about currently used up liquidity
714 fn create_inflight_map(&self) -> InFlightHtlcs {
715 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
716 // Make an attempt at finding existing payment information from `payment_cache`. If it
717 // does not exist, it probably is a fresh payment and we can just return an empty
719 for payment_info in self.payment_cache.lock().unwrap().values() {
720 for path in &payment_info.paths {
721 if path.is_empty() { break };
722 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
723 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
724 // the router excludes the payer node. In the following lines, the payer's information is
725 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
726 // in our sliding window of two.
727 let our_node_id: PublicKey = self.payer.node_id();
728 let reversed_hops_with_payer = path.iter().rev().skip(1)
729 .map(|hop| hop.pubkey)
730 .chain(core::iter::once(our_node_id));
731 let mut cumulative_msat = 0;
733 // Taking the reversed vector from above, we zip it with just the reversed hops list to
734 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
735 // the total amount sent.
736 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
737 cumulative_msat += next_hop.fee_msat;
739 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
740 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
741 .or_insert(cumulative_msat);
746 InFlightHtlcs::new(total_inflight_map)
750 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
751 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
754 #[cfg(feature = "std")]
755 fn has_expired(route_params: &RouteParameters) -> bool {
756 if let Some(expiry_time) = route_params.payment_params.expiry_time {
757 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
761 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
762 InvoicePayerUsingTime<P, R, L, E, T>
767 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
769 fn handle_event_internal(&self, event: &Event) -> bool {
771 Event::PaymentPathFailed { payment_hash, path, .. }
772 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
773 | Event::ProbeSuccessful { payment_hash, path, .. }
774 | Event::ProbeFailed { payment_hash, path, .. } => {
775 self.remove_path_inflight_htlcs(*payment_hash, path);
781 Event::PaymentPathFailed {
782 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
784 if let Some(short_channel_id) = short_channel_id {
785 let path = path.iter().collect::<Vec<_>>();
786 self.router.notify_payment_path_failed(&path, *short_channel_id)
789 if payment_id.is_none() {
790 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
791 } else if *payment_failed_permanently {
792 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
793 self.payer.abandon_payment(payment_id.unwrap());
794 } else if retry.is_none() {
795 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
796 self.payer.abandon_payment(payment_id.unwrap());
797 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
798 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
801 self.payer.abandon_payment(payment_id.unwrap());
804 Event::PaymentFailed { payment_hash, .. } => {
805 self.remove_cached_payment(&payment_hash);
807 Event::PaymentPathSuccessful { path, .. } => {
808 let path = path.iter().collect::<Vec<_>>();
809 self.router.notify_payment_path_successful(&path);
811 Event::PaymentSent { payment_hash, .. } => {
812 let mut payment_cache = self.payment_cache.lock().unwrap();
813 let attempts = payment_cache
814 .remove(payment_hash)
815 .map_or(1, |payment_info| payment_info.attempts.count + 1);
816 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
818 Event::ProbeSuccessful { payment_hash, path, .. } => {
819 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
820 let path = path.iter().collect::<Vec<_>>();
821 self.router.notify_payment_probe_successful(&path);
823 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
824 if let Some(short_channel_id) = short_channel_id {
825 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
826 let path = path.iter().collect::<Vec<_>>();
827 self.router.notify_payment_probe_failed(&path, *short_channel_id);
833 // Delegate to the decorated event handler unless the payment is retried.
838 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
839 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
844 fn handle_event(&self, event: Event) {
845 let should_forward = self.handle_event_internal(&event);
847 self.event_handler.handle_event(event)
852 impl<P: Deref, R: ScoringRouter, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
853 InvoicePayerUsingTime<P, R, L, H, T>
858 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
859 /// handler, if necessary, to handle them asynchronously.
860 pub async fn handle_event_async(&self, event: Event) {
861 let should_forward = self.handle_event_internal(&event);
863 (self.event_handler)(event).await;
871 use crate::{InvoiceBuilder, Currency};
872 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
873 use bitcoin_hashes::sha256::Hash as Sha256;
874 use lightning::ln::PaymentPreimage;
875 use lightning::ln::channelmanager;
876 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
877 use lightning::ln::functional_test_utils::*;
878 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
879 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
880 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
881 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
882 use lightning::util::test_utils::TestLogger;
883 use lightning::util::errors::APIError;
884 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
885 use secp256k1::{SecretKey, PublicKey, Secp256k1};
886 use std::cell::RefCell;
887 use std::collections::VecDeque;
888 use std::ops::DerefMut;
889 use std::time::{SystemTime, Duration};
890 use crate::time_utils::tests::SinceEpoch;
891 use crate::DEFAULT_EXPIRY_TIME;
892 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
894 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
895 let payment_hash = Sha256::hash(&payment_preimage.0);
896 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
898 InvoiceBuilder::new(Currency::Bitcoin)
899 .description("test".into())
900 .payment_hash(payment_hash)
901 .payment_secret(PaymentSecret([0; 32]))
902 .duration_since_epoch(duration_since_epoch())
903 .min_final_cltv_expiry(144)
904 .amount_milli_satoshis(128)
905 .build_signed(|hash| {
906 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
911 fn duration_since_epoch() -> Duration {
912 #[cfg(feature = "std")]
913 let duration_since_epoch =
914 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
915 #[cfg(not(feature = "std"))]
916 let duration_since_epoch = Duration::from_secs(1234567);
920 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
921 let payment_hash = Sha256::hash(&payment_preimage.0);
922 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
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_since_epoch())
929 .min_final_cltv_expiry(144)
930 .build_signed(|hash| {
931 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
936 #[cfg(feature = "std")]
937 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
938 let payment_hash = Sha256::hash(&payment_preimage.0);
939 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
940 let duration = duration_since_epoch()
941 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
943 InvoiceBuilder::new(Currency::Bitcoin)
944 .description("test".into())
945 .payment_hash(payment_hash)
946 .payment_secret(PaymentSecret([0; 32]))
947 .duration_since_epoch(duration)
948 .min_final_cltv_expiry(144)
949 .amount_milli_satoshis(128)
950 .build_signed(|hash| {
951 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
956 fn pubkey() -> PublicKey {
957 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
961 fn pays_invoice_on_first_attempt() {
962 let event_handled = core::cell::RefCell::new(false);
963 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
965 let payment_preimage = PaymentPreimage([1; 32]);
966 let invoice = invoice(payment_preimage);
967 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
968 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
970 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
971 let router = TestRouter::new(TestScorer::new());
972 let logger = TestLogger::new();
974 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
976 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
977 assert_eq!(*payer.attempts.borrow(), 1);
979 invoice_payer.handle_event(Event::PaymentSent {
980 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
982 assert_eq!(*event_handled.borrow(), true);
983 assert_eq!(*payer.attempts.borrow(), 1);
987 fn pays_invoice_on_retry() {
988 let event_handled = core::cell::RefCell::new(false);
989 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
991 let payment_preimage = PaymentPreimage([1; 32]);
992 let invoice = invoice(payment_preimage);
993 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
994 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
996 let payer = TestPayer::new()
997 .expect_send(Amount::ForInvoice(final_value_msat))
998 .expect_send(Amount::OnRetry(final_value_msat / 2));
999 let router = TestRouter::new(TestScorer::new());
1000 let logger = TestLogger::new();
1002 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1004 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1005 assert_eq!(*payer.attempts.borrow(), 1);
1007 let event = Event::PaymentPathFailed {
1010 network_update: None,
1011 payment_failed_permanently: false,
1012 all_paths_failed: false,
1013 path: TestRouter::path_for_value(final_value_msat),
1014 short_channel_id: None,
1015 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1017 invoice_payer.handle_event(event);
1018 assert_eq!(*event_handled.borrow(), false);
1019 assert_eq!(*payer.attempts.borrow(), 2);
1021 invoice_payer.handle_event(Event::PaymentSent {
1022 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1024 assert_eq!(*event_handled.borrow(), true);
1025 assert_eq!(*payer.attempts.borrow(), 2);
1029 fn pays_invoice_on_partial_failure() {
1030 let event_handler = |_: Event| { panic!() };
1032 let payment_preimage = PaymentPreimage([1; 32]);
1033 let invoice = invoice(payment_preimage);
1034 let retry = TestRouter::retry_for_invoice(&invoice);
1035 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1037 let payer = TestPayer::new()
1038 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
1039 .fails_with_partial_failure(retry, OnAttempt(2), None)
1040 .expect_send(Amount::ForInvoice(final_value_msat))
1041 .expect_send(Amount::OnRetry(final_value_msat / 2))
1042 .expect_send(Amount::OnRetry(final_value_msat / 2));
1043 let router = TestRouter::new(TestScorer::new());
1044 let logger = TestLogger::new();
1046 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1048 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1052 fn retries_payment_path_for_unknown_payment() {
1053 let event_handled = core::cell::RefCell::new(false);
1054 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1056 let payment_preimage = PaymentPreimage([1; 32]);
1057 let invoice = invoice(payment_preimage);
1058 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1059 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1061 let payer = TestPayer::new()
1062 .expect_send(Amount::OnRetry(final_value_msat / 2))
1063 .expect_send(Amount::OnRetry(final_value_msat / 2));
1064 let router = TestRouter::new(TestScorer::new());
1065 let logger = TestLogger::new();
1067 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1069 let payment_id = Some(PaymentId([1; 32]));
1070 let event = Event::PaymentPathFailed {
1073 network_update: None,
1074 payment_failed_permanently: false,
1075 all_paths_failed: false,
1076 path: TestRouter::path_for_value(final_value_msat),
1077 short_channel_id: None,
1078 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1080 invoice_payer.handle_event(event.clone());
1081 assert_eq!(*event_handled.borrow(), false);
1082 assert_eq!(*payer.attempts.borrow(), 1);
1084 invoice_payer.handle_event(event.clone());
1085 assert_eq!(*event_handled.borrow(), false);
1086 assert_eq!(*payer.attempts.borrow(), 2);
1088 invoice_payer.handle_event(Event::PaymentSent {
1089 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1091 assert_eq!(*event_handled.borrow(), true);
1092 assert_eq!(*payer.attempts.borrow(), 2);
1096 fn fails_paying_invoice_after_max_retry_counts() {
1097 let event_handled = core::cell::RefCell::new(false);
1098 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1100 let payment_preimage = PaymentPreimage([1; 32]);
1101 let invoice = invoice(payment_preimage);
1102 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1104 let payer = TestPayer::new()
1105 .expect_send(Amount::ForInvoice(final_value_msat))
1106 .expect_send(Amount::OnRetry(final_value_msat / 2))
1107 .expect_send(Amount::OnRetry(final_value_msat / 2));
1108 let router = TestRouter::new(TestScorer::new());
1109 let logger = TestLogger::new();
1111 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1113 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1114 assert_eq!(*payer.attempts.borrow(), 1);
1116 let event = Event::PaymentPathFailed {
1118 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1119 network_update: None,
1120 payment_failed_permanently: false,
1121 all_paths_failed: true,
1122 path: TestRouter::path_for_value(final_value_msat),
1123 short_channel_id: None,
1124 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1126 invoice_payer.handle_event(event);
1127 assert_eq!(*event_handled.borrow(), false);
1128 assert_eq!(*payer.attempts.borrow(), 2);
1130 let event = Event::PaymentPathFailed {
1132 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1133 network_update: None,
1134 payment_failed_permanently: false,
1135 all_paths_failed: false,
1136 path: TestRouter::path_for_value(final_value_msat / 2),
1137 short_channel_id: None,
1138 retry: Some(RouteParameters {
1139 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1142 invoice_payer.handle_event(event.clone());
1143 assert_eq!(*event_handled.borrow(), false);
1144 assert_eq!(*payer.attempts.borrow(), 3);
1146 invoice_payer.handle_event(event.clone());
1147 assert_eq!(*event_handled.borrow(), true);
1148 assert_eq!(*payer.attempts.borrow(), 3);
1151 #[cfg(feature = "std")]
1153 fn fails_paying_invoice_after_max_retry_timeout() {
1154 let event_handled = core::cell::RefCell::new(false);
1155 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1157 let payment_preimage = PaymentPreimage([1; 32]);
1158 let invoice = invoice(payment_preimage);
1159 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1161 let payer = TestPayer::new()
1162 .expect_send(Amount::ForInvoice(final_value_msat))
1163 .expect_send(Amount::OnRetry(final_value_msat / 2));
1165 let router = TestRouter::new(TestScorer::new());
1166 let logger = TestLogger::new();
1167 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1170 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1172 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1173 assert_eq!(*payer.attempts.borrow(), 1);
1175 let event = Event::PaymentPathFailed {
1177 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1178 network_update: None,
1179 payment_failed_permanently: false,
1180 all_paths_failed: true,
1181 path: TestRouter::path_for_value(final_value_msat),
1182 short_channel_id: None,
1183 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1185 invoice_payer.handle_event(event.clone());
1186 assert_eq!(*event_handled.borrow(), false);
1187 assert_eq!(*payer.attempts.borrow(), 2);
1189 SinceEpoch::advance(Duration::from_secs(121));
1191 invoice_payer.handle_event(event.clone());
1192 assert_eq!(*event_handled.borrow(), true);
1193 assert_eq!(*payer.attempts.borrow(), 2);
1197 fn fails_paying_invoice_with_missing_retry_params() {
1198 let event_handled = core::cell::RefCell::new(false);
1199 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1201 let payment_preimage = PaymentPreimage([1; 32]);
1202 let invoice = invoice(payment_preimage);
1203 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1205 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1206 let router = TestRouter::new(TestScorer::new());
1207 let logger = TestLogger::new();
1209 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1211 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1212 assert_eq!(*payer.attempts.borrow(), 1);
1214 let event = Event::PaymentPathFailed {
1216 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1217 network_update: None,
1218 payment_failed_permanently: false,
1219 all_paths_failed: false,
1221 short_channel_id: None,
1224 invoice_payer.handle_event(event);
1225 assert_eq!(*event_handled.borrow(), true);
1226 assert_eq!(*payer.attempts.borrow(), 1);
1229 // Expiration is checked only in an std environment
1230 #[cfg(feature = "std")]
1232 fn fails_paying_invoice_after_expiration() {
1233 let event_handled = core::cell::RefCell::new(false);
1234 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1236 let payer = TestPayer::new();
1237 let router = TestRouter::new(TestScorer::new());
1238 let logger = TestLogger::new();
1240 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1242 let payment_preimage = PaymentPreimage([1; 32]);
1243 let invoice = expired_invoice(payment_preimage);
1244 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1245 assert_eq!(msg, "Invoice expired prior to send");
1246 } else { panic!("Expected Invoice Error"); }
1249 // Expiration is checked only in an std environment
1250 #[cfg(feature = "std")]
1252 fn fails_retrying_invoice_after_expiration() {
1253 let event_handled = core::cell::RefCell::new(false);
1254 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1256 let payment_preimage = PaymentPreimage([1; 32]);
1257 let invoice = invoice(payment_preimage);
1258 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1260 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1261 let router = TestRouter::new(TestScorer::new());
1262 let logger = TestLogger::new();
1264 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1266 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1267 assert_eq!(*payer.attempts.borrow(), 1);
1269 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1270 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1271 .checked_sub(Duration::from_secs(2)).unwrap()
1272 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1273 let event = Event::PaymentPathFailed {
1275 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1276 network_update: None,
1277 payment_failed_permanently: false,
1278 all_paths_failed: false,
1280 short_channel_id: None,
1281 retry: Some(retry_data),
1283 invoice_payer.handle_event(event);
1284 assert_eq!(*event_handled.borrow(), true);
1285 assert_eq!(*payer.attempts.borrow(), 1);
1289 fn fails_paying_invoice_after_retry_error() {
1290 let event_handled = core::cell::RefCell::new(false);
1291 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1293 let payment_preimage = PaymentPreimage([1; 32]);
1294 let invoice = invoice(payment_preimage);
1295 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1297 let payer = TestPayer::new()
1298 .fails_on_attempt(2)
1299 .expect_send(Amount::ForInvoice(final_value_msat))
1300 .expect_send(Amount::OnRetry(final_value_msat / 2));
1301 let router = TestRouter::new(TestScorer::new());
1302 let logger = TestLogger::new();
1304 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1306 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1307 assert_eq!(*payer.attempts.borrow(), 1);
1309 let event = Event::PaymentPathFailed {
1311 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1312 network_update: None,
1313 payment_failed_permanently: false,
1314 all_paths_failed: false,
1315 path: TestRouter::path_for_value(final_value_msat / 2),
1316 short_channel_id: None,
1317 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1319 invoice_payer.handle_event(event);
1320 assert_eq!(*event_handled.borrow(), true);
1321 assert_eq!(*payer.attempts.borrow(), 2);
1325 fn fails_paying_invoice_after_rejected_by_payee() {
1326 let event_handled = core::cell::RefCell::new(false);
1327 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1329 let payment_preimage = PaymentPreimage([1; 32]);
1330 let invoice = invoice(payment_preimage);
1331 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1333 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1334 let router = TestRouter::new(TestScorer::new());
1335 let logger = TestLogger::new();
1337 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1339 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1340 assert_eq!(*payer.attempts.borrow(), 1);
1342 let event = Event::PaymentPathFailed {
1344 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1345 network_update: None,
1346 payment_failed_permanently: true,
1347 all_paths_failed: false,
1349 short_channel_id: None,
1350 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1352 invoice_payer.handle_event(event);
1353 assert_eq!(*event_handled.borrow(), true);
1354 assert_eq!(*payer.attempts.borrow(), 1);
1358 fn fails_repaying_invoice_with_pending_payment() {
1359 let event_handled = core::cell::RefCell::new(false);
1360 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1362 let payment_preimage = PaymentPreimage([1; 32]);
1363 let invoice = invoice(payment_preimage);
1364 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1366 let payer = TestPayer::new()
1367 .expect_send(Amount::ForInvoice(final_value_msat))
1368 .expect_send(Amount::ForInvoice(final_value_msat));
1369 let router = TestRouter::new(TestScorer::new());
1370 let logger = TestLogger::new();
1372 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1374 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1376 // Cannot repay an invoice pending payment.
1377 match invoice_payer.pay_invoice(&invoice) {
1378 Err(PaymentError::Invoice("payment pending")) => {},
1379 Err(_) => panic!("unexpected error"),
1380 Ok(_) => panic!("expected invoice error"),
1383 // Can repay an invoice once cleared from cache.
1384 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1385 invoice_payer.remove_cached_payment(&payment_hash);
1386 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1388 // Cannot retry paying an invoice if cleared from cache.
1389 invoice_payer.remove_cached_payment(&payment_hash);
1390 let event = Event::PaymentPathFailed {
1393 network_update: None,
1394 payment_failed_permanently: false,
1395 all_paths_failed: false,
1397 short_channel_id: None,
1398 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1400 invoice_payer.handle_event(event);
1401 assert_eq!(*event_handled.borrow(), true);
1405 fn fails_paying_invoice_with_routing_errors() {
1406 let payer = TestPayer::new();
1407 let router = FailingRouter {};
1408 let logger = TestLogger::new();
1410 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1412 let payment_preimage = PaymentPreimage([1; 32]);
1413 let invoice = invoice(payment_preimage);
1414 match invoice_payer.pay_invoice(&invoice) {
1415 Err(PaymentError::Routing(_)) => {},
1416 Err(_) => panic!("unexpected error"),
1417 Ok(_) => panic!("expected routing error"),
1422 fn fails_paying_invoice_with_sending_errors() {
1423 let payment_preimage = PaymentPreimage([1; 32]);
1424 let invoice = invoice(payment_preimage);
1425 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1427 let payer = TestPayer::new()
1428 .fails_on_attempt(1)
1429 .expect_send(Amount::ForInvoice(final_value_msat));
1430 let router = TestRouter::new(TestScorer::new());
1431 let logger = TestLogger::new();
1433 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1435 match invoice_payer.pay_invoice(&invoice) {
1436 Err(PaymentError::Sending(_)) => {},
1437 Err(_) => panic!("unexpected error"),
1438 Ok(_) => panic!("expected sending error"),
1443 fn pays_zero_value_invoice_using_amount() {
1444 let event_handled = core::cell::RefCell::new(false);
1445 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1447 let payment_preimage = PaymentPreimage([1; 32]);
1448 let invoice = zero_value_invoice(payment_preimage);
1449 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1450 let final_value_msat = 100;
1452 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1453 let router = TestRouter::new(TestScorer::new());
1454 let logger = TestLogger::new();
1456 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1459 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1460 assert_eq!(*payer.attempts.borrow(), 1);
1462 invoice_payer.handle_event(Event::PaymentSent {
1463 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1465 assert_eq!(*event_handled.borrow(), true);
1466 assert_eq!(*payer.attempts.borrow(), 1);
1470 fn fails_paying_zero_value_invoice_with_amount() {
1471 let event_handled = core::cell::RefCell::new(false);
1472 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1474 let payer = TestPayer::new();
1475 let router = TestRouter::new(TestScorer::new());
1476 let logger = TestLogger::new();
1478 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1480 let payment_preimage = PaymentPreimage([1; 32]);
1481 let invoice = invoice(payment_preimage);
1483 // Cannot repay an invoice pending payment.
1484 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1485 Err(PaymentError::Invoice("amount unexpected")) => {},
1486 Err(_) => panic!("unexpected error"),
1487 Ok(_) => panic!("expected invoice error"),
1492 fn pays_pubkey_with_amount() {
1493 let event_handled = core::cell::RefCell::new(false);
1494 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1496 let pubkey = pubkey();
1497 let payment_preimage = PaymentPreimage([1; 32]);
1498 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1499 let final_value_msat = 100;
1500 let final_cltv_expiry_delta = 42;
1502 let payer = TestPayer::new()
1503 .expect_send(Amount::Spontaneous(final_value_msat))
1504 .expect_send(Amount::OnRetry(final_value_msat));
1505 let router = TestRouter::new(TestScorer::new());
1506 let logger = TestLogger::new();
1508 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1510 let payment_id = Some(invoice_payer.pay_pubkey(
1511 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1513 assert_eq!(*payer.attempts.borrow(), 1);
1515 let retry = RouteParameters {
1516 payment_params: PaymentParameters::for_keysend(pubkey),
1518 final_cltv_expiry_delta,
1520 let event = Event::PaymentPathFailed {
1523 network_update: None,
1524 payment_failed_permanently: false,
1525 all_paths_failed: false,
1527 short_channel_id: None,
1530 invoice_payer.handle_event(event);
1531 assert_eq!(*event_handled.borrow(), false);
1532 assert_eq!(*payer.attempts.borrow(), 2);
1534 invoice_payer.handle_event(Event::PaymentSent {
1535 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1537 assert_eq!(*event_handled.borrow(), true);
1538 assert_eq!(*payer.attempts.borrow(), 2);
1542 fn scores_failed_channel() {
1543 let event_handled = core::cell::RefCell::new(false);
1544 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1546 let payment_preimage = PaymentPreimage([1; 32]);
1547 let invoice = invoice(payment_preimage);
1548 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1549 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1550 let path = TestRouter::path_for_value(final_value_msat);
1551 let short_channel_id = Some(path[0].short_channel_id);
1553 // Expect that scorer is given short_channel_id upon handling the event.
1554 let payer = TestPayer::new()
1555 .expect_send(Amount::ForInvoice(final_value_msat))
1556 .expect_send(Amount::OnRetry(final_value_msat / 2));
1557 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1558 path: path.clone(), short_channel_id: path[0].short_channel_id,
1560 let router = TestRouter::new(scorer);
1561 let logger = TestLogger::new();
1563 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1565 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1566 let event = Event::PaymentPathFailed {
1569 network_update: None,
1570 payment_failed_permanently: false,
1571 all_paths_failed: false,
1574 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1576 invoice_payer.handle_event(event);
1580 fn scores_successful_channels() {
1581 let event_handled = core::cell::RefCell::new(false);
1582 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1584 let payment_preimage = PaymentPreimage([1; 32]);
1585 let invoice = invoice(payment_preimage);
1586 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1587 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1588 let route = TestRouter::route_for_value(final_value_msat);
1590 // Expect that scorer is given short_channel_id upon handling the event.
1591 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1592 let scorer = TestScorer::new()
1593 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1594 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1595 let router = TestRouter::new(scorer);
1596 let logger = TestLogger::new();
1598 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1600 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1601 let event = Event::PaymentPathSuccessful {
1602 payment_id, payment_hash, path: route.paths[0].clone()
1604 invoice_payer.handle_event(event);
1605 let event = Event::PaymentPathSuccessful {
1606 payment_id, payment_hash, path: route.paths[1].clone()
1608 invoice_payer.handle_event(event);
1612 fn generates_correct_inflight_map_data() {
1613 let event_handled = core::cell::RefCell::new(false);
1614 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1616 let payment_preimage = PaymentPreimage([1; 32]);
1617 let invoice = invoice(payment_preimage);
1618 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1619 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1621 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1622 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1623 let route = TestRouter::route_for_value(final_value_msat);
1624 let router = TestRouter::new(TestScorer::new());
1625 let logger = TestLogger::new();
1627 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1629 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1631 let inflight_map = invoice_payer.create_inflight_map();
1633 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1634 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1635 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1637 // Second path check
1638 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1639 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1641 invoice_payer.handle_event(Event::PaymentPathSuccessful {
1642 payment_id, payment_hash, path: route.paths[0].clone()
1645 let inflight_map = invoice_payer.create_inflight_map();
1647 assert_eq!(inflight_map.0.get(&(0, false)), None);
1648 assert_eq!(inflight_map.0.get(&(1, true)), None);
1649 assert_eq!(inflight_map.0.get(&(2, false)), None);
1651 // Second path should still be inflight
1652 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1653 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1657 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1658 // First, let's just send a payment through, but only make sure one of the path completes
1659 let event_handled = core::cell::RefCell::new(false);
1660 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1662 let payment_preimage = PaymentPreimage([1; 32]);
1663 let payment_invoice = invoice(payment_preimage);
1664 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1665 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1667 let payer = TestPayer::new()
1668 .expect_send(Amount::ForInvoice(final_value_msat))
1669 .expect_send(Amount::ForInvoice(final_value_msat));
1670 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1671 let route = TestRouter::route_for_value(final_value_msat);
1672 let scorer = TestScorer::new()
1673 // 1st invoice, 1st path
1674 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1675 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1676 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1677 // 1st invoice, 2nd path
1678 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1679 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1680 // 2nd invoice, 1st path
1681 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1682 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1683 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1684 // 2nd invoice, 2nd path
1685 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1686 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1687 let router = TestRouter::new(scorer);
1688 let logger = TestLogger::new();
1690 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1692 // Succeed 1st path, leave 2nd path inflight
1693 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1694 invoice_payer.handle_event(Event::PaymentPathSuccessful {
1695 payment_id, payment_hash, path: route.paths[0].clone()
1698 // Let's pay a second invoice that will be using the same path. This should trigger the
1699 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1700 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1701 // have 64 msats inflight for paths considering the channel with scid of 1.
1702 let payment_preimage_2 = PaymentPreimage([2; 32]);
1703 let payment_invoice_2 = invoice(payment_preimage_2);
1704 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1708 fn considers_inflight_htlcs_between_retries() {
1709 // First, let's just send a payment through, but only make sure one of the path completes
1710 let event_handled = core::cell::RefCell::new(false);
1711 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1713 let payment_preimage = PaymentPreimage([1; 32]);
1714 let payment_invoice = invoice(payment_preimage);
1715 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1716 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1718 let payer = TestPayer::new()
1719 .expect_send(Amount::ForInvoice(final_value_msat))
1720 .expect_send(Amount::OnRetry(final_value_msat / 2))
1721 .expect_send(Amount::OnRetry(final_value_msat / 4));
1722 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1723 let scorer = TestScorer::new()
1724 // 1st invoice, 1st path
1725 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1726 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1727 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1728 // 1st invoice, 2nd path
1729 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1730 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1731 // Retry 1, 1st path
1732 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1733 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1734 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1735 // Retry 1, 2nd path
1736 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1737 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1738 // Retry 2, 1st path
1739 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1740 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1741 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1742 // Retry 2, 2nd path
1743 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1744 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1745 let router = TestRouter::new(scorer);
1746 let logger = TestLogger::new();
1748 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1750 // Fail 1st path, leave 2nd path inflight
1751 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1752 invoice_payer.handle_event(Event::PaymentPathFailed {
1755 network_update: None,
1756 payment_failed_permanently: false,
1757 all_paths_failed: false,
1758 path: TestRouter::path_for_value(final_value_msat),
1759 short_channel_id: None,
1760 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1763 // Fails again the 1st path of our retry
1764 invoice_payer.handle_event(Event::PaymentPathFailed {
1767 network_update: None,
1768 payment_failed_permanently: false,
1769 all_paths_failed: false,
1770 path: TestRouter::path_for_value(final_value_msat / 2),
1771 short_channel_id: None,
1772 retry: Some(RouteParameters {
1773 final_value_msat: final_value_msat / 4,
1774 ..TestRouter::retry_for_invoice(&payment_invoice)
1780 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1781 let event_handled = core::cell::RefCell::new(false);
1782 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1784 let payment_preimage = PaymentPreimage([1; 32]);
1785 let invoice_to_pay = invoice(payment_preimage);
1786 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1788 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1789 let payer = TestPayer::new()
1790 .fails_with_partial_failure(
1791 retry.clone(), OnAttempt(1),
1793 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1795 .expect_send(Amount::ForInvoice(final_value_msat));
1797 let router = TestRouter::new(TestScorer::new());
1798 let logger = TestLogger::new();
1800 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1802 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1803 let inflight_map = invoice_payer.create_inflight_map();
1805 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1806 // inflight map because retries are disabled.
1807 assert_eq!(inflight_map.0.len(), 2);
1811 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1812 let event_handled = core::cell::RefCell::new(false);
1813 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1815 let payment_preimage = PaymentPreimage([1; 32]);
1816 let invoice_to_pay = invoice(payment_preimage);
1817 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1819 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1820 let payer = TestPayer::new()
1821 .fails_with_partial_failure(
1822 retry.clone(), OnAttempt(1),
1824 Ok(()), Err(MonitorUpdateInProgress)
1826 .expect_send(Amount::ForInvoice(final_value_msat));
1828 let router = TestRouter::new(TestScorer::new());
1829 let logger = TestLogger::new();
1831 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1833 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1834 let inflight_map = invoice_payer.create_inflight_map();
1836 // All paths successful, hence we check of the existence of all 5 hops.
1837 assert_eq!(inflight_map.0.len(), 5);
1841 scorer: RefCell<TestScorer>,
1845 fn new(scorer: TestScorer) -> Self {
1846 TestRouter { scorer: RefCell::new(scorer) }
1849 fn route_for_value(final_value_msat: u64) -> Route {
1854 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1855 channel_features: ChannelFeatures::empty(),
1856 node_features: NodeFeatures::empty(),
1857 short_channel_id: 0,
1859 cltv_expiry_delta: 0
1862 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1863 channel_features: ChannelFeatures::empty(),
1864 node_features: NodeFeatures::empty(),
1865 short_channel_id: 1,
1867 cltv_expiry_delta: 0
1870 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1871 channel_features: ChannelFeatures::empty(),
1872 node_features: NodeFeatures::empty(),
1873 short_channel_id: 2,
1874 fee_msat: final_value_msat / 2,
1875 cltv_expiry_delta: 0
1880 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1881 channel_features: ChannelFeatures::empty(),
1882 node_features: NodeFeatures::empty(),
1883 short_channel_id: 3,
1885 cltv_expiry_delta: 144
1888 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1889 channel_features: ChannelFeatures::empty(),
1890 node_features: NodeFeatures::empty(),
1891 short_channel_id: 4,
1892 fee_msat: final_value_msat / 2,
1893 cltv_expiry_delta: 144
1897 payment_params: None,
1901 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1902 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1905 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1906 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1907 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1908 .with_route_hints(invoice.route_hints());
1909 if let Some(features) = invoice.features() {
1910 payment_params = payment_params.with_features(features.clone());
1912 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1916 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1921 impl Router for TestRouter {
1923 &self, payer: &PublicKey, route_params: &RouteParameters,
1924 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1925 ) -> Result<Route, LightningError> {
1926 // Simulate calling the Scorer just as you would in find_route
1927 let route = Self::route_for_value(route_params.final_value_msat);
1928 let mut locked_scorer = self.scorer.lock();
1929 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1930 for path in route.paths {
1931 let mut aggregate_msat = 0u64;
1932 for (idx, hop) in path.iter().rev().enumerate() {
1933 aggregate_msat += hop.fee_msat;
1934 let usage = ChannelUsage {
1935 amount_msat: aggregate_msat,
1936 inflight_htlc_msat: 0,
1937 effective_capacity: EffectiveCapacity::Unknown,
1940 // Since the path is reversed, the last element in our iteration is the first
1942 if idx == path.len() - 1 {
1943 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1945 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1951 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1956 impl ScoringRouter for TestRouter {
1957 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1958 self.scorer.lock().payment_path_failed(path, short_channel_id);
1961 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1962 self.scorer.lock().payment_path_successful(path);
1965 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1966 self.scorer.lock().probe_successful(path);
1969 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1970 self.scorer.lock().probe_failed(path, short_channel_id);
1974 struct FailingRouter;
1976 impl Router for FailingRouter {
1978 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1979 _inflight_htlcs: InFlightHtlcs,
1980 ) -> Result<Route, LightningError> {
1981 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1985 impl ScoringRouter for FailingRouter {
1986 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1988 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1990 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1992 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1996 event_expectations: Option<VecDeque<TestResult>>,
1997 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
2002 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
2003 PaymentSuccess { path: Vec<RouteHop> },
2009 event_expectations: None,
2010 scorer_expectations: RefCell::new(None),
2014 fn expect(mut self, expectation: TestResult) -> Self {
2015 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
2019 fn expect_usage(self, expectation: ChannelUsage) -> Self {
2020 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
2026 impl lightning::util::ser::Writeable for TestScorer {
2027 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
2030 impl Score for TestScorer {
2031 fn channel_penalty_msat(
2032 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
2034 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
2035 match scorer_expectations.pop_front() {
2036 Some(expectation) => {
2037 assert_eq!(expectation.amount_msat, usage.amount_msat);
2038 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
2046 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
2047 if let Some(expectations) = &mut self.event_expectations {
2048 match expectations.pop_front() {
2049 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
2050 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2051 assert_eq!(actual_short_channel_id, short_channel_id);
2053 Some(TestResult::PaymentSuccess { path }) => {
2054 panic!("Unexpected successful payment path: {:?}", path)
2056 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2061 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
2062 if let Some(expectations) = &mut self.event_expectations {
2063 match expectations.pop_front() {
2064 Some(TestResult::PaymentFailure { path, .. }) => {
2065 panic!("Unexpected payment path failure: {:?}", path)
2067 Some(TestResult::PaymentSuccess { path }) => {
2068 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2070 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2075 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
2076 if let Some(expectations) = &mut self.event_expectations {
2077 match expectations.pop_front() {
2078 Some(TestResult::PaymentFailure { path, .. }) => {
2079 panic!("Unexpected failed payment path: {:?}", path)
2081 Some(TestResult::PaymentSuccess { path }) => {
2082 panic!("Unexpected successful payment path: {:?}", path)
2084 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2088 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
2089 if let Some(expectations) = &mut self.event_expectations {
2090 match expectations.pop_front() {
2091 Some(TestResult::PaymentFailure { path, .. }) => {
2092 panic!("Unexpected payment path failure: {:?}", path)
2094 Some(TestResult::PaymentSuccess { path }) => {
2095 panic!("Unexpected successful payment path: {:?}", path)
2097 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2103 impl Drop for TestScorer {
2104 fn drop(&mut self) {
2105 if std::thread::panicking() {
2109 if let Some(event_expectations) = &self.event_expectations {
2110 if !event_expectations.is_empty() {
2111 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2115 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2116 if !scorer_expectations.is_empty() {
2117 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2124 expectations: core::cell::RefCell<VecDeque<Amount>>,
2125 attempts: core::cell::RefCell<usize>,
2126 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2129 #[derive(Clone, Debug, PartialEq, Eq)]
2136 struct OnAttempt(usize);
2141 expectations: core::cell::RefCell::new(VecDeque::new()),
2142 attempts: core::cell::RefCell::new(0),
2143 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2147 fn expect_send(self, value_msat: Amount) -> Self {
2148 self.expectations.borrow_mut().push_back(value_msat);
2152 fn fails_on_attempt(self, attempt: usize) -> Self {
2153 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2154 self.fails_with(failure, OnAttempt(attempt))
2157 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2158 self.fails_with(PaymentSendFailure::PartialFailure {
2159 results: results.unwrap_or(vec![]),
2160 failed_paths_retry: Some(retry),
2161 payment_id: PaymentId([1; 32]),
2165 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2166 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2170 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
2171 let mut attempts = self.attempts.borrow_mut();
2174 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2175 Some(failure) => Err(failure),
2180 fn check_value_msats(&self, actual_value_msats: Amount) {
2181 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2182 if let Some(expected_value_msats) = expected_value_msats {
2183 assert_eq!(actual_value_msats, expected_value_msats);
2185 panic!("Unexpected amount: {:?}", actual_value_msats);
2190 impl Drop for TestPayer {
2191 fn drop(&mut self) {
2192 if std::thread::panicking() {
2196 if !self.expectations.borrow().is_empty() {
2197 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2202 impl Payer for TestPayer {
2203 fn node_id(&self) -> PublicKey {
2204 let secp_ctx = Secp256k1::new();
2205 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2208 fn first_hops(&self) -> Vec<ChannelDetails> {
2213 &self, route: &Route, _payment_hash: PaymentHash,
2214 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2215 ) -> Result<(), PaymentSendFailure> {
2216 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2217 self.check_attempts()
2220 fn send_spontaneous_payment(
2221 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2222 ) -> Result<(), PaymentSendFailure> {
2223 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2224 self.check_attempts()
2228 &self, route: &Route, _payment_id: PaymentId
2229 ) -> Result<(), PaymentSendFailure> {
2230 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2231 self.check_attempts()
2234 fn abandon_payment(&self, _payment_id: PaymentId) { }
2237 // *** Full Featured Functional Tests with a Real ChannelManager ***
2238 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2240 impl Router for ManualRouter {
2242 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2243 _inflight_htlcs: InFlightHtlcs
2244 ) -> Result<Route, LightningError> {
2245 self.0.borrow_mut().pop_front().unwrap()
2248 impl ScoringRouter for ManualRouter {
2249 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2251 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2253 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2255 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2258 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2259 self.0.borrow_mut().push_back(result);
2262 impl Drop for ManualRouter {
2263 fn drop(&mut self) {
2264 if std::thread::panicking() {
2267 assert!(self.0.borrow_mut().is_empty());
2272 fn retry_multi_path_single_failed_payment() {
2273 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2274 let chanmon_cfgs = create_chanmon_cfgs(2);
2275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2279 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2280 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2281 let chans = nodes[0].node.list_usable_channels();
2282 let mut route = Route {
2285 pubkey: nodes[1].node.get_our_node_id(),
2286 node_features: channelmanager::provided_node_features(),
2287 short_channel_id: chans[0].short_channel_id.unwrap(),
2288 channel_features: channelmanager::provided_channel_features(),
2290 cltv_expiry_delta: 100,
2293 pubkey: nodes[1].node.get_our_node_id(),
2294 node_features: channelmanager::provided_node_features(),
2295 short_channel_id: chans[1].short_channel_id.unwrap(),
2296 channel_features: channelmanager::provided_channel_features(),
2297 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2298 cltv_expiry_delta: 100,
2301 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2303 let router = ManualRouter(RefCell::new(VecDeque::new()));
2304 router.expect_find_route(Ok(route.clone()));
2305 // On retry, split the payment across both channels.
2306 route.paths[0][0].fee_msat = 50_000_001;
2307 route.paths[1][0].fee_msat = 50_000_000;
2308 router.expect_find_route(Ok(route.clone()));
2310 let event_handler = |_: Event| { panic!(); };
2311 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2313 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2314 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2315 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2317 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2318 assert_eq!(htlc_msgs.len(), 2);
2319 check_added_monitors!(nodes[0], 2);
2323 fn immediate_retry_on_failure() {
2324 // Tests that we can/will retry immediately after a failure
2325 let chanmon_cfgs = create_chanmon_cfgs(2);
2326 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2327 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2328 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2330 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2331 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2332 let chans = nodes[0].node.list_usable_channels();
2333 let mut route = Route {
2336 pubkey: nodes[1].node.get_our_node_id(),
2337 node_features: channelmanager::provided_node_features(),
2338 short_channel_id: chans[0].short_channel_id.unwrap(),
2339 channel_features: channelmanager::provided_channel_features(),
2340 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2341 cltv_expiry_delta: 100,
2344 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2346 let router = ManualRouter(RefCell::new(VecDeque::new()));
2347 router.expect_find_route(Ok(route.clone()));
2348 // On retry, split the payment across both channels.
2349 route.paths.push(route.paths[0].clone());
2350 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2351 route.paths[0][0].fee_msat = 50_000_000;
2352 route.paths[1][0].fee_msat = 50_000_001;
2353 router.expect_find_route(Ok(route.clone()));
2355 let event_handler = |_: Event| { panic!(); };
2356 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2358 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2359 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2360 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2362 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2363 assert_eq!(htlc_msgs.len(), 2);
2364 check_added_monitors!(nodes[0], 2);
2368 fn no_extra_retries_on_back_to_back_fail() {
2369 // In a previous release, we had a race where we may exceed the payment retry count if we
2370 // get two failures in a row with the second having `all_paths_failed` set.
2371 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2372 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2373 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2374 // pending which we will see later. Thus, when we previously removed the retry tracking map
2375 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2376 // retry entry even though more events for the same payment were still pending. This led to
2377 // us retrying a payment again even though we'd already given up on it.
2379 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2380 // is used to remove the payment retry counter entries instead. This tests for the specific
2381 // excess-retry case while also testing `PaymentFailed` generation.
2383 let chanmon_cfgs = create_chanmon_cfgs(3);
2384 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2385 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2386 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2388 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;
2389 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;
2391 let mut route = Route {
2394 pubkey: nodes[1].node.get_our_node_id(),
2395 node_features: channelmanager::provided_node_features(),
2396 short_channel_id: chan_1_scid,
2397 channel_features: channelmanager::provided_channel_features(),
2399 cltv_expiry_delta: 100,
2401 pubkey: nodes[2].node.get_our_node_id(),
2402 node_features: channelmanager::provided_node_features(),
2403 short_channel_id: chan_2_scid,
2404 channel_features: channelmanager::provided_channel_features(),
2405 fee_msat: 100_000_000,
2406 cltv_expiry_delta: 100,
2409 pubkey: nodes[1].node.get_our_node_id(),
2410 node_features: channelmanager::provided_node_features(),
2411 short_channel_id: chan_1_scid,
2412 channel_features: channelmanager::provided_channel_features(),
2414 cltv_expiry_delta: 100,
2416 pubkey: nodes[2].node.get_our_node_id(),
2417 node_features: channelmanager::provided_node_features(),
2418 short_channel_id: chan_2_scid,
2419 channel_features: channelmanager::provided_channel_features(),
2420 fee_msat: 100_000_000,
2421 cltv_expiry_delta: 100,
2424 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2426 let router = ManualRouter(RefCell::new(VecDeque::new()));
2427 router.expect_find_route(Ok(route.clone()));
2428 // On retry, we'll only be asked for one path
2429 route.paths.remove(1);
2430 router.expect_find_route(Ok(route.clone()));
2432 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2433 let event_handler = |event: Event| {
2434 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2435 event_checker(event);
2437 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2439 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2440 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2441 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2443 let htlc_updates = SendEvent::from_node(&nodes[0]);
2444 check_added_monitors!(nodes[0], 1);
2445 assert_eq!(htlc_updates.msgs.len(), 1);
2447 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2448 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2449 check_added_monitors!(nodes[1], 1);
2450 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2452 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2453 check_added_monitors!(nodes[0], 1);
2454 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2456 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2457 check_added_monitors!(nodes[0], 1);
2458 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2460 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2461 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2462 check_added_monitors!(nodes[1], 1);
2463 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2465 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2466 check_added_monitors!(nodes[1], 1);
2467 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2469 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2470 check_added_monitors!(nodes[0], 1);
2472 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2473 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2474 check_added_monitors!(nodes[0], 1);
2475 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2477 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2478 check_added_monitors!(nodes[1], 1);
2479 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2482 check_added_monitors!(nodes[1], 1);
2483 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2485 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2486 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2487 check_added_monitors!(nodes[0], 1);
2489 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2490 check_added_monitors!(nodes[0], 1);
2491 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2493 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2494 check_added_monitors!(nodes[1], 1);
2495 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2496 check_added_monitors!(nodes[1], 1);
2497 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2499 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2500 check_added_monitors!(nodes[0], 1);
2502 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2503 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2504 // with it set. The first event will use up the only retry we are allowed, with the second
2505 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2506 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2507 // if the final HTLC failed.
2508 expected_events.borrow_mut().push_back(&|ev: Event| {
2509 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2510 assert!(!payment_failed_permanently);
2511 assert!(all_paths_failed);
2512 } else { panic!("Unexpected event"); }
2514 nodes[0].node.process_pending_events(&invoice_payer);
2515 assert!(expected_events.borrow().is_empty());
2517 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2518 check_added_monitors!(nodes[0], 1);
2520 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2521 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2522 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2523 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2524 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2526 expected_events.borrow_mut().push_back(&|ev: Event| {
2527 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2528 assert!(!payment_failed_permanently);
2529 assert!(all_paths_failed);
2530 } else { panic!("Unexpected event"); }
2532 expected_events.borrow_mut().push_back(&|ev: Event| {
2533 if let Event::PaymentFailed { .. } = ev {
2534 } else { panic!("Unexpected event"); }
2536 nodes[0].node.process_pending_events(&invoice_payer);
2537 assert!(expected_events.borrow().is_empty());