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::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
167 /// See [module-level documentation] for details.
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
175 use crate::time_utils;
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
179 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
180 pub struct InvoicePayerUsingTime<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
189 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
190 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
194 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
195 /// currently being made, or have outstanding paths that need retrying.
196 struct PaymentInfo<T: Time> {
197 attempts: PaymentAttempts<T>,
198 paths: Vec<Vec<RouteHop>>,
201 impl<T: Time> PaymentInfo<T> {
204 attempts: PaymentAttempts::new(),
210 /// Storing minimal payment attempts information required for determining if a outbound payment can
212 #[derive(Clone, Copy)]
213 struct PaymentAttempts<T: Time> {
214 /// This count will be incremented only after the result of the attempt is known. When it's 0,
215 /// it means the result of the first attempt is now known yet.
217 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
218 first_attempted_at: T
221 impl<T: Time> PaymentAttempts<T> {
225 first_attempted_at: T::now()
230 impl<T: Time> Display for PaymentAttempts<T> {
231 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
232 #[cfg(feature = "no-std")]
233 return write!( f, "attempts: {}", self.count);
234 #[cfg(not(feature = "no-std"))]
237 "attempts: {}, duration: {}s",
239 T::now().duration_since(self.first_attempted_at).as_secs()
244 /// A trait defining behavior of an [`Invoice`] payer.
246 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
247 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
249 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
251 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
252 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
253 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
254 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
256 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
258 /// Returns the payer's node id.
259 fn node_id(&self) -> PublicKey;
261 /// Returns the payer's channels.
262 fn first_hops(&self) -> Vec<ChannelDetails>;
264 /// Sends a payment over the Lightning Network using the given [`Route`].
266 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
267 payment_id: PaymentId
268 ) -> Result<(), PaymentSendFailure>;
270 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
271 fn send_spontaneous_payment(
272 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
273 ) -> Result<(), PaymentSendFailure>;
275 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
276 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
278 /// Signals that no further retries for the given payment will occur.
279 fn abandon_payment(&self, payment_id: PaymentId);
282 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
283 /// based on payment and probe success/failure.
285 /// [`Router`]: lightning::routing::router::Router
286 pub trait ScoringRouter: Router {
287 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
288 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
289 fn find_route_with_id(
290 &self, payer: &PublicKey, route_params: &RouteParameters,
291 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
292 _payment_hash: PaymentHash, _payment_id: PaymentId
293 ) -> Result<Route, LightningError> {
294 self.find_route(payer, route_params, first_hops, inflight_htlcs)
296 /// Lets the router know that payment through a specific path has failed.
297 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
298 /// Lets the router know that payment through a specific path was successful.
299 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
300 /// Lets the router know that a payment probe was successful.
301 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
302 /// Lets the router know that a payment probe failed.
303 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
306 /// Strategies available to retry payment path failures for an [`Invoice`].
308 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
310 /// Max number of attempts to retry payment.
312 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
313 /// payments, if this is less than the total number of paths, we will never even retry all of the
316 #[cfg(feature = "std")]
317 /// Time elapsed before abandoning retries for a payment.
322 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
323 match (self, attempts) {
324 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
325 max_retry_count >= &count
327 #[cfg(feature = "std")]
328 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
329 *max_duration >= T::now().duration_since(*first_attempted_at),
334 /// An error that may occur when making a payment.
335 #[derive(Clone, Debug)]
336 pub enum PaymentError {
337 /// An error resulting from the provided [`Invoice`] or payment hash.
338 Invoice(&'static str),
339 /// An error occurring when finding a route.
340 Routing(LightningError),
341 /// An error occurring when sending a payment.
342 Sending(PaymentSendFailure),
345 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
350 /// Creates an invoice payer that retries failed payment paths.
352 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
353 /// `retry` has been exceeded for a given [`Invoice`].
355 payer: P, router: R, logger: L, event_handler: E, retry: Retry
362 payment_cache: Mutex::new(HashMap::new()),
367 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
369 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
370 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
371 /// a second payment with the same [`PaymentHash`] is never sent.
373 /// If you wish to use a different payment idempotency token, see
374 /// [`Self::pay_invoice_with_id`].
375 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
376 let payment_id = PaymentId(invoice.payment_hash().into_inner());
377 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
380 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
381 /// in case a retry is needed.
383 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
384 /// payment completes or fails, no idempotency guarantees are made.
386 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
387 /// has never been paid before.
389 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
391 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
392 if invoice.amount_milli_satoshis().is_none() {
393 Err(PaymentError::Invoice("amount missing"))
395 self.pay_invoice_using_amount(invoice, None, payment_id)
399 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
400 /// case a retry is needed.
402 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
403 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
404 /// a second payment with the same [`PaymentHash`] is never sent.
406 /// If you wish to use a different payment idempotency token, see
407 /// [`Self::pay_zero_value_invoice_with_id`].
408 pub fn pay_zero_value_invoice(
409 &self, invoice: &Invoice, amount_msats: u64
410 ) -> Result<PaymentId, PaymentError> {
411 let payment_id = PaymentId(invoice.payment_hash().into_inner());
412 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
415 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
416 /// caching the invoice for later use in case a retry is needed.
418 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
419 /// payment completes or fails, no idempotency guarantees are made.
421 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
422 /// has never been paid before.
424 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
425 /// idempotency token.
426 pub fn pay_zero_value_invoice_with_id(
427 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
428 ) -> Result<(), PaymentError> {
429 if invoice.amount_milli_satoshis().is_some() {
430 Err(PaymentError::Invoice("amount unexpected"))
432 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
436 fn pay_invoice_using_amount(
437 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
438 ) -> Result<(), PaymentError> {
439 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
441 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
442 match self.payment_cache.lock().unwrap().entry(payment_hash) {
443 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
444 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
447 let payment_secret = Some(invoice.payment_secret().clone());
448 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
449 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
450 .with_route_hints(invoice.route_hints());
451 if let Some(features) = invoice.features() {
452 payment_params = payment_params.with_features(features.clone());
454 let route_params = RouteParameters {
456 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
457 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
460 let send_payment = |route: &Route| {
461 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
464 self.pay_internal(&route_params, payment_hash, send_payment)
465 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
468 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
469 /// case a retry is needed.
471 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
472 /// as long as the payment is still pending. Once the payment completes or fails, you must
473 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
475 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
476 final_cltv_expiry_delta: u32
477 ) -> Result<PaymentId, PaymentError> {
478 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
479 let payment_id = PaymentId(payment_hash.0);
480 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
481 final_cltv_expiry_delta)
482 .map(|()| payment_id)
485 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
486 /// caching the invoice for later use in case a retry is needed.
488 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
489 /// payment completes or fails, no idempotency guarantees are made.
491 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
492 /// [`PaymentHash`] has never been paid before.
493 pub fn pay_pubkey_with_id(
494 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
495 amount_msats: u64, final_cltv_expiry_delta: u32
496 ) -> Result<(), PaymentError> {
497 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
498 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
499 final_cltv_expiry_delta)
503 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
504 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
505 ) -> Result<(), PaymentError> {
506 match self.payment_cache.lock().unwrap().entry(payment_hash) {
507 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
508 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
511 let route_params = RouteParameters {
512 payment_params: PaymentParameters::for_keysend(pubkey),
513 final_value_msat: amount_msats,
514 final_cltv_expiry_delta,
517 let send_payment = |route: &Route| {
518 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
520 self.pay_internal(&route_params, payment_hash, send_payment)
521 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
524 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
525 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
526 ) -> Result<(), PaymentError> {
527 #[cfg(feature = "std")] {
528 if has_expired(params) {
529 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
530 return Err(PaymentError::Invoice("Invoice expired prior to send"));
534 let payer = self.payer.node_id();
535 let first_hops = self.payer.first_hops();
536 let inflight_htlcs = self.create_inflight_map();
537 let route = self.router.find_route(
538 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
539 ).map_err(|e| PaymentError::Routing(e))?;
541 match send_payment(&route) {
543 for path in route.paths {
544 self.process_path_inflight_htlcs(payment_hash, path);
549 PaymentSendFailure::ParameterError(_) => Err(e),
550 PaymentSendFailure::PathParameterError(_) => Err(e),
551 PaymentSendFailure::AllFailedRetrySafe(_) => {
552 let mut payment_cache = self.payment_cache.lock().unwrap();
553 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
554 payment_info.attempts.count += 1;
555 if self.retry.is_retryable_now(&payment_info.attempts) {
556 core::mem::drop(payment_cache);
557 Ok(self.pay_internal(params, payment_hash, send_payment)?)
562 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
563 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
564 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
565 // means that we are still waiting for our channel monitor update to be completed.
566 for (result, path) in results.iter().zip(route.paths.into_iter()) {
568 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
569 self.process_path_inflight_htlcs(payment_hash, path);
575 if let Some(retry_data) = failed_paths_retry {
576 // Some paths were sent, even if we failed to send the full MPP value our
577 // recipient may misbehave and claim the funds, at which point we have to
578 // consider the payment sent, so return `Ok()` here, ignoring any retry
580 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
583 // This may happen if we send a payment and some paths fail, but
584 // only due to a temporary monitor failure or the like, implying
585 // they're really in-flight, but we haven't sent the initial
586 // HTLC-Add messages yet.
591 }.map_err(|e| PaymentError::Sending(e))
594 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
595 // that are pending retry.
596 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
597 self.payment_cache.lock().unwrap().entry(payment_hash)
598 .or_insert_with(|| PaymentInfo::new())
602 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
603 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
604 self.payment_cache.lock().unwrap().entry(payment_hash)
605 .and_modify(|payment_info| {
606 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
607 payment_info.paths.swap_remove(idx);
613 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
614 ) -> Result<(), ()> {
615 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
616 .and_modify(|info| info.attempts.count += 1 )
617 .or_insert_with(|| PaymentInfo {
618 attempts: PaymentAttempts {
620 first_attempted_at: T::now(),
625 if !self.retry.is_retryable_now(&attempts) {
626 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
630 #[cfg(feature = "std")] {
631 if has_expired(params) {
632 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
637 let payer = self.payer.node_id();
638 let first_hops = self.payer.first_hops();
639 let inflight_htlcs = self.create_inflight_map();
641 let route = self.router.find_route(
642 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
646 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
650 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
652 for path in route.unwrap().paths.into_iter() {
653 self.process_path_inflight_htlcs(payment_hash, path);
657 Err(PaymentSendFailure::ParameterError(_)) |
658 Err(PaymentSendFailure::PathParameterError(_)) => {
659 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
662 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
663 self.retry_payment(payment_id, payment_hash, params)
665 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
666 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
667 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
668 // means that we are still waiting for our channel monitor update to complete.
669 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
671 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
672 self.process_path_inflight_htlcs(payment_hash, path);
678 if let Some(retry) = failed_paths_retry {
679 // Always return Ok for the same reason as noted in pay_internal.
680 let _ = self.retry_payment(payment_id, payment_hash, &retry);
687 /// Removes the payment cached by the given payment hash.
689 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
690 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
691 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
692 self.payment_cache.lock().unwrap().remove(payment_hash);
695 /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
696 /// channel id and direction to the amount being sent through it.
698 /// This function should be called whenever we need information about currently used up liquidity
700 fn create_inflight_map(&self) -> InFlightHtlcs {
701 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
702 // Make an attempt at finding existing payment information from `payment_cache`. If it
703 // does not exist, it probably is a fresh payment and we can just return an empty
705 for payment_info in self.payment_cache.lock().unwrap().values() {
706 for path in &payment_info.paths {
707 if path.is_empty() { break };
708 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
709 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
710 // the router excludes the payer node. In the following lines, the payer's information is
711 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
712 // in our sliding window of two.
713 let our_node_id: PublicKey = self.payer.node_id();
714 let reversed_hops_with_payer = path.iter().rev().skip(1)
715 .map(|hop| hop.pubkey)
716 .chain(core::iter::once(our_node_id));
717 let mut cumulative_msat = 0;
719 // Taking the reversed vector from above, we zip it with just the reversed hops list to
720 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
721 // the total amount sent.
722 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
723 cumulative_msat += next_hop.fee_msat;
725 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
726 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
727 .or_insert(cumulative_msat);
732 InFlightHtlcs::new(total_inflight_map)
736 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
737 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
740 #[cfg(feature = "std")]
741 fn has_expired(route_params: &RouteParameters) -> bool {
742 if let Some(expiry_time) = route_params.payment_params.expiry_time {
743 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
747 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
752 fn handle_event(&self, event: &Event) {
754 Event::PaymentPathFailed { payment_hash, path, .. }
755 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
756 | Event::ProbeSuccessful { payment_hash, path, .. }
757 | Event::ProbeFailed { payment_hash, path, .. } => {
758 self.remove_path_inflight_htlcs(*payment_hash, path);
764 Event::PaymentPathFailed {
765 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
767 if let Some(short_channel_id) = short_channel_id {
768 let path = path.iter().collect::<Vec<_>>();
769 self.router.notify_payment_path_failed(&path, *short_channel_id)
772 if payment_id.is_none() {
773 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
774 } else if *payment_failed_permanently {
775 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
776 self.payer.abandon_payment(payment_id.unwrap());
777 } else if retry.is_none() {
778 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
779 self.payer.abandon_payment(payment_id.unwrap());
780 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
781 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
784 self.payer.abandon_payment(payment_id.unwrap());
787 Event::PaymentFailed { payment_hash, .. } => {
788 self.remove_cached_payment(&payment_hash);
790 Event::PaymentPathSuccessful { path, .. } => {
791 let path = path.iter().collect::<Vec<_>>();
792 self.router.notify_payment_path_successful(&path);
794 Event::PaymentSent { payment_hash, .. } => {
795 let mut payment_cache = self.payment_cache.lock().unwrap();
796 let attempts = payment_cache
797 .remove(payment_hash)
798 .map_or(1, |payment_info| payment_info.attempts.count + 1);
799 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
801 Event::ProbeSuccessful { payment_hash, path, .. } => {
802 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
803 let path = path.iter().collect::<Vec<_>>();
804 self.router.notify_payment_probe_successful(&path);
806 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
807 if let Some(short_channel_id) = short_channel_id {
808 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
809 let path = path.iter().collect::<Vec<_>>();
810 self.router.notify_payment_probe_failed(&path, *short_channel_id);
816 // Delegate to the decorated event handler unless the payment is retried.
817 self.event_handler.handle_event(event)
824 use crate::{InvoiceBuilder, Currency};
825 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
826 use bitcoin_hashes::sha256::Hash as Sha256;
827 use lightning::ln::PaymentPreimage;
828 use lightning::ln::channelmanager;
829 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
830 use lightning::ln::functional_test_utils::*;
831 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
832 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
833 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
834 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
835 use lightning::util::test_utils::TestLogger;
836 use lightning::util::errors::APIError;
837 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
838 use secp256k1::{SecretKey, PublicKey, Secp256k1};
839 use std::cell::RefCell;
840 use std::collections::VecDeque;
841 use std::ops::DerefMut;
842 use std::time::{SystemTime, Duration};
843 use crate::time_utils::tests::SinceEpoch;
844 use crate::DEFAULT_EXPIRY_TIME;
845 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
847 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
848 let payment_hash = Sha256::hash(&payment_preimage.0);
849 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
851 InvoiceBuilder::new(Currency::Bitcoin)
852 .description("test".into())
853 .payment_hash(payment_hash)
854 .payment_secret(PaymentSecret([0; 32]))
855 .duration_since_epoch(duration_since_epoch())
856 .min_final_cltv_expiry(144)
857 .amount_milli_satoshis(128)
858 .build_signed(|hash| {
859 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
864 fn duration_since_epoch() -> Duration {
865 #[cfg(feature = "std")]
866 let duration_since_epoch =
867 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
868 #[cfg(not(feature = "std"))]
869 let duration_since_epoch = Duration::from_secs(1234567);
873 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
874 let payment_hash = Sha256::hash(&payment_preimage.0);
875 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
877 InvoiceBuilder::new(Currency::Bitcoin)
878 .description("test".into())
879 .payment_hash(payment_hash)
880 .payment_secret(PaymentSecret([0; 32]))
881 .duration_since_epoch(duration_since_epoch())
882 .min_final_cltv_expiry(144)
883 .build_signed(|hash| {
884 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
889 #[cfg(feature = "std")]
890 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
891 let payment_hash = Sha256::hash(&payment_preimage.0);
892 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
893 let duration = duration_since_epoch()
894 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
896 InvoiceBuilder::new(Currency::Bitcoin)
897 .description("test".into())
898 .payment_hash(payment_hash)
899 .payment_secret(PaymentSecret([0; 32]))
900 .duration_since_epoch(duration)
901 .min_final_cltv_expiry(144)
902 .amount_milli_satoshis(128)
903 .build_signed(|hash| {
904 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
909 fn pubkey() -> PublicKey {
910 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
914 fn pays_invoice_on_first_attempt() {
915 let event_handled = core::cell::RefCell::new(false);
916 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
918 let payment_preimage = PaymentPreimage([1; 32]);
919 let invoice = invoice(payment_preimage);
920 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
921 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
923 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
924 let router = TestRouter::new(TestScorer::new());
925 let logger = TestLogger::new();
927 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
929 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
930 assert_eq!(*payer.attempts.borrow(), 1);
932 invoice_payer.handle_event(&Event::PaymentSent {
933 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
935 assert_eq!(*event_handled.borrow(), true);
936 assert_eq!(*payer.attempts.borrow(), 1);
940 fn pays_invoice_on_retry() {
941 let event_handled = core::cell::RefCell::new(false);
942 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
944 let payment_preimage = PaymentPreimage([1; 32]);
945 let invoice = invoice(payment_preimage);
946 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
947 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
949 let payer = TestPayer::new()
950 .expect_send(Amount::ForInvoice(final_value_msat))
951 .expect_send(Amount::OnRetry(final_value_msat / 2));
952 let router = TestRouter::new(TestScorer::new());
953 let logger = TestLogger::new();
955 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
957 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
958 assert_eq!(*payer.attempts.borrow(), 1);
960 let event = Event::PaymentPathFailed {
963 network_update: None,
964 payment_failed_permanently: false,
965 all_paths_failed: false,
966 path: TestRouter::path_for_value(final_value_msat),
967 short_channel_id: None,
968 retry: Some(TestRouter::retry_for_invoice(&invoice)),
970 invoice_payer.handle_event(&event);
971 assert_eq!(*event_handled.borrow(), false);
972 assert_eq!(*payer.attempts.borrow(), 2);
974 invoice_payer.handle_event(&Event::PaymentSent {
975 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
977 assert_eq!(*event_handled.borrow(), true);
978 assert_eq!(*payer.attempts.borrow(), 2);
982 fn pays_invoice_on_partial_failure() {
983 let event_handler = |_: &_| { panic!() };
985 let payment_preimage = PaymentPreimage([1; 32]);
986 let invoice = invoice(payment_preimage);
987 let retry = TestRouter::retry_for_invoice(&invoice);
988 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
990 let payer = TestPayer::new()
991 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
992 .fails_with_partial_failure(retry, OnAttempt(2), None)
993 .expect_send(Amount::ForInvoice(final_value_msat))
994 .expect_send(Amount::OnRetry(final_value_msat / 2))
995 .expect_send(Amount::OnRetry(final_value_msat / 2));
996 let router = TestRouter::new(TestScorer::new());
997 let logger = TestLogger::new();
999 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1001 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1005 fn retries_payment_path_for_unknown_payment() {
1006 let event_handled = core::cell::RefCell::new(false);
1007 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1009 let payment_preimage = PaymentPreimage([1; 32]);
1010 let invoice = invoice(payment_preimage);
1011 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1012 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1014 let payer = TestPayer::new()
1015 .expect_send(Amount::OnRetry(final_value_msat / 2))
1016 .expect_send(Amount::OnRetry(final_value_msat / 2));
1017 let router = TestRouter::new(TestScorer::new());
1018 let logger = TestLogger::new();
1020 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1022 let payment_id = Some(PaymentId([1; 32]));
1023 let event = Event::PaymentPathFailed {
1026 network_update: None,
1027 payment_failed_permanently: false,
1028 all_paths_failed: false,
1029 path: TestRouter::path_for_value(final_value_msat),
1030 short_channel_id: None,
1031 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1033 invoice_payer.handle_event(&event);
1034 assert_eq!(*event_handled.borrow(), false);
1035 assert_eq!(*payer.attempts.borrow(), 1);
1037 invoice_payer.handle_event(&event);
1038 assert_eq!(*event_handled.borrow(), false);
1039 assert_eq!(*payer.attempts.borrow(), 2);
1041 invoice_payer.handle_event(&Event::PaymentSent {
1042 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1044 assert_eq!(*event_handled.borrow(), true);
1045 assert_eq!(*payer.attempts.borrow(), 2);
1049 fn fails_paying_invoice_after_max_retry_counts() {
1050 let event_handled = core::cell::RefCell::new(false);
1051 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1053 let payment_preimage = PaymentPreimage([1; 32]);
1054 let invoice = invoice(payment_preimage);
1055 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1057 let payer = TestPayer::new()
1058 .expect_send(Amount::ForInvoice(final_value_msat))
1059 .expect_send(Amount::OnRetry(final_value_msat / 2))
1060 .expect_send(Amount::OnRetry(final_value_msat / 2));
1061 let router = TestRouter::new(TestScorer::new());
1062 let logger = TestLogger::new();
1064 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1066 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1067 assert_eq!(*payer.attempts.borrow(), 1);
1069 let event = Event::PaymentPathFailed {
1071 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1072 network_update: None,
1073 payment_failed_permanently: false,
1074 all_paths_failed: true,
1075 path: TestRouter::path_for_value(final_value_msat),
1076 short_channel_id: None,
1077 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1079 invoice_payer.handle_event(&event);
1080 assert_eq!(*event_handled.borrow(), false);
1081 assert_eq!(*payer.attempts.borrow(), 2);
1083 let event = Event::PaymentPathFailed {
1085 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1086 network_update: None,
1087 payment_failed_permanently: false,
1088 all_paths_failed: false,
1089 path: TestRouter::path_for_value(final_value_msat / 2),
1090 short_channel_id: None,
1091 retry: Some(RouteParameters {
1092 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1095 invoice_payer.handle_event(&event);
1096 assert_eq!(*event_handled.borrow(), false);
1097 assert_eq!(*payer.attempts.borrow(), 3);
1099 invoice_payer.handle_event(&event);
1100 assert_eq!(*event_handled.borrow(), true);
1101 assert_eq!(*payer.attempts.borrow(), 3);
1104 #[cfg(feature = "std")]
1106 fn fails_paying_invoice_after_max_retry_timeout() {
1107 let event_handled = core::cell::RefCell::new(false);
1108 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1110 let payment_preimage = PaymentPreimage([1; 32]);
1111 let invoice = invoice(payment_preimage);
1112 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1114 let payer = TestPayer::new()
1115 .expect_send(Amount::ForInvoice(final_value_msat))
1116 .expect_send(Amount::OnRetry(final_value_msat / 2));
1118 let router = TestRouter::new(TestScorer::new());
1119 let logger = TestLogger::new();
1120 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1123 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1125 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1126 assert_eq!(*payer.attempts.borrow(), 1);
1128 let event = Event::PaymentPathFailed {
1130 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1131 network_update: None,
1132 payment_failed_permanently: false,
1133 all_paths_failed: true,
1134 path: TestRouter::path_for_value(final_value_msat),
1135 short_channel_id: None,
1136 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1138 invoice_payer.handle_event(&event);
1139 assert_eq!(*event_handled.borrow(), false);
1140 assert_eq!(*payer.attempts.borrow(), 2);
1142 SinceEpoch::advance(Duration::from_secs(121));
1144 invoice_payer.handle_event(&event);
1145 assert_eq!(*event_handled.borrow(), true);
1146 assert_eq!(*payer.attempts.borrow(), 2);
1150 fn fails_paying_invoice_with_missing_retry_params() {
1151 let event_handled = core::cell::RefCell::new(false);
1152 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1154 let payment_preimage = PaymentPreimage([1; 32]);
1155 let invoice = invoice(payment_preimage);
1156 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1158 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1159 let router = TestRouter::new(TestScorer::new());
1160 let logger = TestLogger::new();
1162 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1164 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1165 assert_eq!(*payer.attempts.borrow(), 1);
1167 let event = Event::PaymentPathFailed {
1169 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1170 network_update: None,
1171 payment_failed_permanently: false,
1172 all_paths_failed: false,
1174 short_channel_id: None,
1177 invoice_payer.handle_event(&event);
1178 assert_eq!(*event_handled.borrow(), true);
1179 assert_eq!(*payer.attempts.borrow(), 1);
1182 // Expiration is checked only in an std environment
1183 #[cfg(feature = "std")]
1185 fn fails_paying_invoice_after_expiration() {
1186 let event_handled = core::cell::RefCell::new(false);
1187 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1189 let payer = TestPayer::new();
1190 let router = TestRouter::new(TestScorer::new());
1191 let logger = TestLogger::new();
1193 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1195 let payment_preimage = PaymentPreimage([1; 32]);
1196 let invoice = expired_invoice(payment_preimage);
1197 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1198 assert_eq!(msg, "Invoice expired prior to send");
1199 } else { panic!("Expected Invoice Error"); }
1202 // Expiration is checked only in an std environment
1203 #[cfg(feature = "std")]
1205 fn fails_retrying_invoice_after_expiration() {
1206 let event_handled = core::cell::RefCell::new(false);
1207 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1209 let payment_preimage = PaymentPreimage([1; 32]);
1210 let invoice = invoice(payment_preimage);
1211 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1213 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1214 let router = TestRouter::new(TestScorer::new());
1215 let logger = TestLogger::new();
1217 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1219 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1220 assert_eq!(*payer.attempts.borrow(), 1);
1222 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1223 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1224 .checked_sub(Duration::from_secs(2)).unwrap()
1225 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1226 let event = Event::PaymentPathFailed {
1228 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1229 network_update: None,
1230 payment_failed_permanently: false,
1231 all_paths_failed: false,
1233 short_channel_id: None,
1234 retry: Some(retry_data),
1236 invoice_payer.handle_event(&event);
1237 assert_eq!(*event_handled.borrow(), true);
1238 assert_eq!(*payer.attempts.borrow(), 1);
1242 fn fails_paying_invoice_after_retry_error() {
1243 let event_handled = core::cell::RefCell::new(false);
1244 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1246 let payment_preimage = PaymentPreimage([1; 32]);
1247 let invoice = invoice(payment_preimage);
1248 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1250 let payer = TestPayer::new()
1251 .fails_on_attempt(2)
1252 .expect_send(Amount::ForInvoice(final_value_msat))
1253 .expect_send(Amount::OnRetry(final_value_msat / 2));
1254 let router = TestRouter::new(TestScorer::new());
1255 let logger = TestLogger::new();
1257 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1259 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1260 assert_eq!(*payer.attempts.borrow(), 1);
1262 let event = Event::PaymentPathFailed {
1264 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1265 network_update: None,
1266 payment_failed_permanently: false,
1267 all_paths_failed: false,
1268 path: TestRouter::path_for_value(final_value_msat / 2),
1269 short_channel_id: None,
1270 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1272 invoice_payer.handle_event(&event);
1273 assert_eq!(*event_handled.borrow(), true);
1274 assert_eq!(*payer.attempts.borrow(), 2);
1278 fn fails_paying_invoice_after_rejected_by_payee() {
1279 let event_handled = core::cell::RefCell::new(false);
1280 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1282 let payment_preimage = PaymentPreimage([1; 32]);
1283 let invoice = invoice(payment_preimage);
1284 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1286 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1287 let router = TestRouter::new(TestScorer::new());
1288 let logger = TestLogger::new();
1290 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1292 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1293 assert_eq!(*payer.attempts.borrow(), 1);
1295 let event = Event::PaymentPathFailed {
1297 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1298 network_update: None,
1299 payment_failed_permanently: true,
1300 all_paths_failed: false,
1302 short_channel_id: None,
1303 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1305 invoice_payer.handle_event(&event);
1306 assert_eq!(*event_handled.borrow(), true);
1307 assert_eq!(*payer.attempts.borrow(), 1);
1311 fn fails_repaying_invoice_with_pending_payment() {
1312 let event_handled = core::cell::RefCell::new(false);
1313 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1315 let payment_preimage = PaymentPreimage([1; 32]);
1316 let invoice = invoice(payment_preimage);
1317 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1319 let payer = TestPayer::new()
1320 .expect_send(Amount::ForInvoice(final_value_msat))
1321 .expect_send(Amount::ForInvoice(final_value_msat));
1322 let router = TestRouter::new(TestScorer::new());
1323 let logger = TestLogger::new();
1325 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1327 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1329 // Cannot repay an invoice pending payment.
1330 match invoice_payer.pay_invoice(&invoice) {
1331 Err(PaymentError::Invoice("payment pending")) => {},
1332 Err(_) => panic!("unexpected error"),
1333 Ok(_) => panic!("expected invoice error"),
1336 // Can repay an invoice once cleared from cache.
1337 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1338 invoice_payer.remove_cached_payment(&payment_hash);
1339 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1341 // Cannot retry paying an invoice if cleared from cache.
1342 invoice_payer.remove_cached_payment(&payment_hash);
1343 let event = Event::PaymentPathFailed {
1346 network_update: None,
1347 payment_failed_permanently: false,
1348 all_paths_failed: false,
1350 short_channel_id: None,
1351 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1353 invoice_payer.handle_event(&event);
1354 assert_eq!(*event_handled.borrow(), true);
1358 fn fails_paying_invoice_with_routing_errors() {
1359 let payer = TestPayer::new();
1360 let router = FailingRouter {};
1361 let logger = TestLogger::new();
1363 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1365 let payment_preimage = PaymentPreimage([1; 32]);
1366 let invoice = invoice(payment_preimage);
1367 match invoice_payer.pay_invoice(&invoice) {
1368 Err(PaymentError::Routing(_)) => {},
1369 Err(_) => panic!("unexpected error"),
1370 Ok(_) => panic!("expected routing error"),
1375 fn fails_paying_invoice_with_sending_errors() {
1376 let payment_preimage = PaymentPreimage([1; 32]);
1377 let invoice = invoice(payment_preimage);
1378 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1380 let payer = TestPayer::new()
1381 .fails_on_attempt(1)
1382 .expect_send(Amount::ForInvoice(final_value_msat));
1383 let router = TestRouter::new(TestScorer::new());
1384 let logger = TestLogger::new();
1386 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1388 match invoice_payer.pay_invoice(&invoice) {
1389 Err(PaymentError::Sending(_)) => {},
1390 Err(_) => panic!("unexpected error"),
1391 Ok(_) => panic!("expected sending error"),
1396 fn pays_zero_value_invoice_using_amount() {
1397 let event_handled = core::cell::RefCell::new(false);
1398 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1400 let payment_preimage = PaymentPreimage([1; 32]);
1401 let invoice = zero_value_invoice(payment_preimage);
1402 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1403 let final_value_msat = 100;
1405 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1406 let router = TestRouter::new(TestScorer::new());
1407 let logger = TestLogger::new();
1409 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1412 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1413 assert_eq!(*payer.attempts.borrow(), 1);
1415 invoice_payer.handle_event(&Event::PaymentSent {
1416 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1418 assert_eq!(*event_handled.borrow(), true);
1419 assert_eq!(*payer.attempts.borrow(), 1);
1423 fn fails_paying_zero_value_invoice_with_amount() {
1424 let event_handled = core::cell::RefCell::new(false);
1425 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1427 let payer = TestPayer::new();
1428 let router = TestRouter::new(TestScorer::new());
1429 let logger = TestLogger::new();
1431 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1433 let payment_preimage = PaymentPreimage([1; 32]);
1434 let invoice = invoice(payment_preimage);
1436 // Cannot repay an invoice pending payment.
1437 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1438 Err(PaymentError::Invoice("amount unexpected")) => {},
1439 Err(_) => panic!("unexpected error"),
1440 Ok(_) => panic!("expected invoice error"),
1445 fn pays_pubkey_with_amount() {
1446 let event_handled = core::cell::RefCell::new(false);
1447 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1449 let pubkey = pubkey();
1450 let payment_preimage = PaymentPreimage([1; 32]);
1451 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1452 let final_value_msat = 100;
1453 let final_cltv_expiry_delta = 42;
1455 let payer = TestPayer::new()
1456 .expect_send(Amount::Spontaneous(final_value_msat))
1457 .expect_send(Amount::OnRetry(final_value_msat));
1458 let router = TestRouter::new(TestScorer::new());
1459 let logger = TestLogger::new();
1461 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1463 let payment_id = Some(invoice_payer.pay_pubkey(
1464 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1466 assert_eq!(*payer.attempts.borrow(), 1);
1468 let retry = RouteParameters {
1469 payment_params: PaymentParameters::for_keysend(pubkey),
1471 final_cltv_expiry_delta,
1473 let event = Event::PaymentPathFailed {
1476 network_update: None,
1477 payment_failed_permanently: false,
1478 all_paths_failed: false,
1480 short_channel_id: None,
1483 invoice_payer.handle_event(&event);
1484 assert_eq!(*event_handled.borrow(), false);
1485 assert_eq!(*payer.attempts.borrow(), 2);
1487 invoice_payer.handle_event(&Event::PaymentSent {
1488 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1490 assert_eq!(*event_handled.borrow(), true);
1491 assert_eq!(*payer.attempts.borrow(), 2);
1495 fn scores_failed_channel() {
1496 let event_handled = core::cell::RefCell::new(false);
1497 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1499 let payment_preimage = PaymentPreimage([1; 32]);
1500 let invoice = invoice(payment_preimage);
1501 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1502 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1503 let path = TestRouter::path_for_value(final_value_msat);
1504 let short_channel_id = Some(path[0].short_channel_id);
1506 // Expect that scorer is given short_channel_id upon handling the event.
1507 let payer = TestPayer::new()
1508 .expect_send(Amount::ForInvoice(final_value_msat))
1509 .expect_send(Amount::OnRetry(final_value_msat / 2));
1510 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1511 path: path.clone(), short_channel_id: path[0].short_channel_id,
1513 let router = TestRouter::new(scorer);
1514 let logger = TestLogger::new();
1516 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1518 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1519 let event = Event::PaymentPathFailed {
1522 network_update: None,
1523 payment_failed_permanently: false,
1524 all_paths_failed: false,
1527 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1529 invoice_payer.handle_event(&event);
1533 fn scores_successful_channels() {
1534 let event_handled = core::cell::RefCell::new(false);
1535 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1537 let payment_preimage = PaymentPreimage([1; 32]);
1538 let invoice = invoice(payment_preimage);
1539 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1540 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1541 let route = TestRouter::route_for_value(final_value_msat);
1543 // Expect that scorer is given short_channel_id upon handling the event.
1544 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1545 let scorer = TestScorer::new()
1546 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1547 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1548 let router = TestRouter::new(scorer);
1549 let logger = TestLogger::new();
1551 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1553 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1554 let event = Event::PaymentPathSuccessful {
1555 payment_id, payment_hash, path: route.paths[0].clone()
1557 invoice_payer.handle_event(&event);
1558 let event = Event::PaymentPathSuccessful {
1559 payment_id, payment_hash, path: route.paths[1].clone()
1561 invoice_payer.handle_event(&event);
1565 fn generates_correct_inflight_map_data() {
1566 let event_handled = core::cell::RefCell::new(false);
1567 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1569 let payment_preimage = PaymentPreimage([1; 32]);
1570 let invoice = invoice(payment_preimage);
1571 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1572 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1574 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1575 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1576 let route = TestRouter::route_for_value(final_value_msat);
1577 let router = TestRouter::new(TestScorer::new());
1578 let logger = TestLogger::new();
1580 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1582 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1584 let inflight_map = invoice_payer.create_inflight_map();
1586 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1587 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1588 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1590 // Second path check
1591 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1592 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1594 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1595 payment_id, payment_hash, path: route.paths[0].clone()
1598 let inflight_map = invoice_payer.create_inflight_map();
1600 assert_eq!(inflight_map.0.get(&(0, false)), None);
1601 assert_eq!(inflight_map.0.get(&(1, true)), None);
1602 assert_eq!(inflight_map.0.get(&(2, false)), None);
1604 // Second path should still be inflight
1605 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1606 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1610 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1611 // First, let's just send a payment through, but only make sure one of the path completes
1612 let event_handled = core::cell::RefCell::new(false);
1613 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1615 let payment_preimage = PaymentPreimage([1; 32]);
1616 let payment_invoice = invoice(payment_preimage);
1617 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1618 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1620 let payer = TestPayer::new()
1621 .expect_send(Amount::ForInvoice(final_value_msat))
1622 .expect_send(Amount::ForInvoice(final_value_msat));
1623 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1624 let route = TestRouter::route_for_value(final_value_msat);
1625 let scorer = TestScorer::new()
1626 // 1st invoice, 1st path
1627 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1628 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1629 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1630 // 1st invoice, 2nd path
1631 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1632 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1633 // 2nd invoice, 1st path
1634 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1635 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1636 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1637 // 2nd invoice, 2nd path
1638 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1639 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1640 let router = TestRouter::new(scorer);
1641 let logger = TestLogger::new();
1643 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1645 // Succeed 1st path, leave 2nd path inflight
1646 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1647 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1648 payment_id, payment_hash, path: route.paths[0].clone()
1651 // Let's pay a second invoice that will be using the same path. This should trigger the
1652 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1653 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1654 // have 64 msats inflight for paths considering the channel with scid of 1.
1655 let payment_preimage_2 = PaymentPreimage([2; 32]);
1656 let payment_invoice_2 = invoice(payment_preimage_2);
1657 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1661 fn considers_inflight_htlcs_between_retries() {
1662 // First, let's just send a payment through, but only make sure one of the path completes
1663 let event_handled = core::cell::RefCell::new(false);
1664 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1666 let payment_preimage = PaymentPreimage([1; 32]);
1667 let payment_invoice = invoice(payment_preimage);
1668 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1669 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1671 let payer = TestPayer::new()
1672 .expect_send(Amount::ForInvoice(final_value_msat))
1673 .expect_send(Amount::OnRetry(final_value_msat / 2))
1674 .expect_send(Amount::OnRetry(final_value_msat / 4));
1675 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1676 let scorer = TestScorer::new()
1677 // 1st invoice, 1st path
1678 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1679 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1680 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1681 // 1st invoice, 2nd path
1682 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1683 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1684 // Retry 1, 1st path
1685 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1686 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1687 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1688 // Retry 1, 2nd path
1689 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1690 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1691 // Retry 2, 1st path
1692 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1693 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1694 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1695 // Retry 2, 2nd path
1696 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1697 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1698 let router = TestRouter::new(scorer);
1699 let logger = TestLogger::new();
1701 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1703 // Fail 1st path, leave 2nd path inflight
1704 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1705 invoice_payer.handle_event(&Event::PaymentPathFailed {
1708 network_update: None,
1709 payment_failed_permanently: false,
1710 all_paths_failed: false,
1711 path: TestRouter::path_for_value(final_value_msat),
1712 short_channel_id: None,
1713 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1716 // Fails again the 1st path of our retry
1717 invoice_payer.handle_event(&Event::PaymentPathFailed {
1720 network_update: None,
1721 payment_failed_permanently: false,
1722 all_paths_failed: false,
1723 path: TestRouter::path_for_value(final_value_msat / 2),
1724 short_channel_id: None,
1725 retry: Some(RouteParameters {
1726 final_value_msat: final_value_msat / 4,
1727 ..TestRouter::retry_for_invoice(&payment_invoice)
1733 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1734 let event_handled = core::cell::RefCell::new(false);
1735 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1737 let payment_preimage = PaymentPreimage([1; 32]);
1738 let invoice_to_pay = invoice(payment_preimage);
1739 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1741 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1742 let payer = TestPayer::new()
1743 .fails_with_partial_failure(
1744 retry.clone(), OnAttempt(1),
1746 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1748 .expect_send(Amount::ForInvoice(final_value_msat));
1750 let router = TestRouter::new(TestScorer::new());
1751 let logger = TestLogger::new();
1753 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1755 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1756 let inflight_map = invoice_payer.create_inflight_map();
1758 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1759 // inflight map because retries are disabled.
1760 assert_eq!(inflight_map.0.len(), 2);
1764 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1765 let event_handled = core::cell::RefCell::new(false);
1766 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1768 let payment_preimage = PaymentPreimage([1; 32]);
1769 let invoice_to_pay = invoice(payment_preimage);
1770 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1772 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1773 let payer = TestPayer::new()
1774 .fails_with_partial_failure(
1775 retry.clone(), OnAttempt(1),
1777 Ok(()), Err(MonitorUpdateInProgress)
1779 .expect_send(Amount::ForInvoice(final_value_msat));
1781 let router = TestRouter::new(TestScorer::new());
1782 let logger = TestLogger::new();
1784 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1786 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1787 let inflight_map = invoice_payer.create_inflight_map();
1789 // All paths successful, hence we check of the existence of all 5 hops.
1790 assert_eq!(inflight_map.0.len(), 5);
1794 scorer: RefCell<TestScorer>,
1798 fn new(scorer: TestScorer) -> Self {
1799 TestRouter { scorer: RefCell::new(scorer) }
1802 fn route_for_value(final_value_msat: u64) -> Route {
1807 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1808 channel_features: ChannelFeatures::empty(),
1809 node_features: NodeFeatures::empty(),
1810 short_channel_id: 0,
1812 cltv_expiry_delta: 0
1815 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1816 channel_features: ChannelFeatures::empty(),
1817 node_features: NodeFeatures::empty(),
1818 short_channel_id: 1,
1820 cltv_expiry_delta: 0
1823 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1824 channel_features: ChannelFeatures::empty(),
1825 node_features: NodeFeatures::empty(),
1826 short_channel_id: 2,
1827 fee_msat: final_value_msat / 2,
1828 cltv_expiry_delta: 0
1833 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1834 channel_features: ChannelFeatures::empty(),
1835 node_features: NodeFeatures::empty(),
1836 short_channel_id: 3,
1838 cltv_expiry_delta: 144
1841 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1842 channel_features: ChannelFeatures::empty(),
1843 node_features: NodeFeatures::empty(),
1844 short_channel_id: 4,
1845 fee_msat: final_value_msat / 2,
1846 cltv_expiry_delta: 144
1850 payment_params: None,
1854 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1855 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1858 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1859 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1860 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1861 .with_route_hints(invoice.route_hints());
1862 if let Some(features) = invoice.features() {
1863 payment_params = payment_params.with_features(features.clone());
1865 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1869 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1874 impl Router for TestRouter {
1876 &self, payer: &PublicKey, route_params: &RouteParameters,
1877 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1878 ) -> Result<Route, LightningError> {
1879 // Simulate calling the Scorer just as you would in find_route
1880 let route = Self::route_for_value(route_params.final_value_msat);
1881 let mut locked_scorer = self.scorer.lock();
1882 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1883 for path in route.paths {
1884 let mut aggregate_msat = 0u64;
1885 for (idx, hop) in path.iter().rev().enumerate() {
1886 aggregate_msat += hop.fee_msat;
1887 let usage = ChannelUsage {
1888 amount_msat: aggregate_msat,
1889 inflight_htlc_msat: 0,
1890 effective_capacity: EffectiveCapacity::Unknown,
1893 // Since the path is reversed, the last element in our iteration is the first
1895 if idx == path.len() - 1 {
1896 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1898 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1904 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1909 impl ScoringRouter for TestRouter {
1910 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1911 self.scorer.lock().payment_path_failed(path, short_channel_id);
1914 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1915 self.scorer.lock().payment_path_successful(path);
1918 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1919 self.scorer.lock().probe_successful(path);
1922 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1923 self.scorer.lock().probe_failed(path, short_channel_id);
1927 struct FailingRouter;
1929 impl Router for FailingRouter {
1931 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1932 _inflight_htlcs: InFlightHtlcs,
1933 ) -> Result<Route, LightningError> {
1934 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1938 impl ScoringRouter for FailingRouter {
1939 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1941 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1943 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1945 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1949 event_expectations: Option<VecDeque<TestResult>>,
1950 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1955 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1956 PaymentSuccess { path: Vec<RouteHop> },
1962 event_expectations: None,
1963 scorer_expectations: RefCell::new(None),
1967 fn expect(mut self, expectation: TestResult) -> Self {
1968 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1972 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1973 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1979 impl lightning::util::ser::Writeable for TestScorer {
1980 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1983 impl Score for TestScorer {
1984 fn channel_penalty_msat(
1985 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1987 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1988 match scorer_expectations.pop_front() {
1989 Some(expectation) => {
1990 assert_eq!(expectation.amount_msat, usage.amount_msat);
1991 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1999 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
2000 if let Some(expectations) = &mut self.event_expectations {
2001 match expectations.pop_front() {
2002 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
2003 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2004 assert_eq!(actual_short_channel_id, short_channel_id);
2006 Some(TestResult::PaymentSuccess { path }) => {
2007 panic!("Unexpected successful payment path: {:?}", path)
2009 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2014 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
2015 if let Some(expectations) = &mut self.event_expectations {
2016 match expectations.pop_front() {
2017 Some(TestResult::PaymentFailure { path, .. }) => {
2018 panic!("Unexpected payment path failure: {:?}", path)
2020 Some(TestResult::PaymentSuccess { path }) => {
2021 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2023 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2028 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
2029 if let Some(expectations) = &mut self.event_expectations {
2030 match expectations.pop_front() {
2031 Some(TestResult::PaymentFailure { path, .. }) => {
2032 panic!("Unexpected failed payment path: {:?}", path)
2034 Some(TestResult::PaymentSuccess { path }) => {
2035 panic!("Unexpected successful payment path: {:?}", path)
2037 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2041 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
2042 if let Some(expectations) = &mut self.event_expectations {
2043 match expectations.pop_front() {
2044 Some(TestResult::PaymentFailure { path, .. }) => {
2045 panic!("Unexpected payment path failure: {:?}", path)
2047 Some(TestResult::PaymentSuccess { path }) => {
2048 panic!("Unexpected successful payment path: {:?}", path)
2050 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2056 impl Drop for TestScorer {
2057 fn drop(&mut self) {
2058 if std::thread::panicking() {
2062 if let Some(event_expectations) = &self.event_expectations {
2063 if !event_expectations.is_empty() {
2064 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2068 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2069 if !scorer_expectations.is_empty() {
2070 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2077 expectations: core::cell::RefCell<VecDeque<Amount>>,
2078 attempts: core::cell::RefCell<usize>,
2079 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2082 #[derive(Clone, Debug, PartialEq, Eq)]
2089 struct OnAttempt(usize);
2094 expectations: core::cell::RefCell::new(VecDeque::new()),
2095 attempts: core::cell::RefCell::new(0),
2096 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2100 fn expect_send(self, value_msat: Amount) -> Self {
2101 self.expectations.borrow_mut().push_back(value_msat);
2105 fn fails_on_attempt(self, attempt: usize) -> Self {
2106 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2107 self.fails_with(failure, OnAttempt(attempt))
2110 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2111 self.fails_with(PaymentSendFailure::PartialFailure {
2112 results: results.unwrap_or(vec![]),
2113 failed_paths_retry: Some(retry),
2114 payment_id: PaymentId([1; 32]),
2118 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2119 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2123 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
2124 let mut attempts = self.attempts.borrow_mut();
2127 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2128 Some(failure) => Err(failure),
2133 fn check_value_msats(&self, actual_value_msats: Amount) {
2134 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2135 if let Some(expected_value_msats) = expected_value_msats {
2136 assert_eq!(actual_value_msats, expected_value_msats);
2138 panic!("Unexpected amount: {:?}", actual_value_msats);
2143 impl Drop for TestPayer {
2144 fn drop(&mut self) {
2145 if std::thread::panicking() {
2149 if !self.expectations.borrow().is_empty() {
2150 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2155 impl Payer for TestPayer {
2156 fn node_id(&self) -> PublicKey {
2157 let secp_ctx = Secp256k1::new();
2158 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2161 fn first_hops(&self) -> Vec<ChannelDetails> {
2166 &self, route: &Route, _payment_hash: PaymentHash,
2167 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2168 ) -> Result<(), PaymentSendFailure> {
2169 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2170 self.check_attempts()
2173 fn send_spontaneous_payment(
2174 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2175 ) -> Result<(), PaymentSendFailure> {
2176 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2177 self.check_attempts()
2181 &self, route: &Route, _payment_id: PaymentId
2182 ) -> Result<(), PaymentSendFailure> {
2183 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2184 self.check_attempts()
2187 fn abandon_payment(&self, _payment_id: PaymentId) { }
2190 // *** Full Featured Functional Tests with a Real ChannelManager ***
2191 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2193 impl Router for ManualRouter {
2195 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2196 _inflight_htlcs: InFlightHtlcs
2197 ) -> Result<Route, LightningError> {
2198 self.0.borrow_mut().pop_front().unwrap()
2201 impl ScoringRouter for ManualRouter {
2202 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2204 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2206 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2208 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2211 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2212 self.0.borrow_mut().push_back(result);
2215 impl Drop for ManualRouter {
2216 fn drop(&mut self) {
2217 if std::thread::panicking() {
2220 assert!(self.0.borrow_mut().is_empty());
2225 fn retry_multi_path_single_failed_payment() {
2226 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2227 let chanmon_cfgs = create_chanmon_cfgs(2);
2228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2232 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2233 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2234 let chans = nodes[0].node.list_usable_channels();
2235 let mut route = Route {
2238 pubkey: nodes[1].node.get_our_node_id(),
2239 node_features: channelmanager::provided_node_features(),
2240 short_channel_id: chans[0].short_channel_id.unwrap(),
2241 channel_features: channelmanager::provided_channel_features(),
2243 cltv_expiry_delta: 100,
2246 pubkey: nodes[1].node.get_our_node_id(),
2247 node_features: channelmanager::provided_node_features(),
2248 short_channel_id: chans[1].short_channel_id.unwrap(),
2249 channel_features: channelmanager::provided_channel_features(),
2250 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2251 cltv_expiry_delta: 100,
2254 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2256 let router = ManualRouter(RefCell::new(VecDeque::new()));
2257 router.expect_find_route(Ok(route.clone()));
2258 // On retry, split the payment across both channels.
2259 route.paths[0][0].fee_msat = 50_000_001;
2260 route.paths[1][0].fee_msat = 50_000_000;
2261 router.expect_find_route(Ok(route.clone()));
2263 let event_handler = |_: &_| { panic!(); };
2264 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2266 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2267 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2268 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2270 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2271 assert_eq!(htlc_msgs.len(), 2);
2272 check_added_monitors!(nodes[0], 2);
2276 fn immediate_retry_on_failure() {
2277 // Tests that we can/will retry immediately after a failure
2278 let chanmon_cfgs = create_chanmon_cfgs(2);
2279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2281 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2283 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2284 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2285 let chans = nodes[0].node.list_usable_channels();
2286 let mut route = Route {
2289 pubkey: nodes[1].node.get_our_node_id(),
2290 node_features: channelmanager::provided_node_features(),
2291 short_channel_id: chans[0].short_channel_id.unwrap(),
2292 channel_features: channelmanager::provided_channel_features(),
2293 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2294 cltv_expiry_delta: 100,
2297 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2299 let router = ManualRouter(RefCell::new(VecDeque::new()));
2300 router.expect_find_route(Ok(route.clone()));
2301 // On retry, split the payment across both channels.
2302 route.paths.push(route.paths[0].clone());
2303 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2304 route.paths[0][0].fee_msat = 50_000_000;
2305 route.paths[1][0].fee_msat = 50_000_001;
2306 router.expect_find_route(Ok(route.clone()));
2308 let event_handler = |_: &_| { panic!(); };
2309 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2311 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2312 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2313 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2315 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2316 assert_eq!(htlc_msgs.len(), 2);
2317 check_added_monitors!(nodes[0], 2);
2321 fn no_extra_retries_on_back_to_back_fail() {
2322 // In a previous release, we had a race where we may exceed the payment retry count if we
2323 // get two failures in a row with the second having `all_paths_failed` set.
2324 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2325 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2326 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2327 // pending which we will see later. Thus, when we previously removed the retry tracking map
2328 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2329 // retry entry even though more events for the same payment were still pending. This led to
2330 // us retrying a payment again even though we'd already given up on it.
2332 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2333 // is used to remove the payment retry counter entries instead. This tests for the specific
2334 // excess-retry case while also testing `PaymentFailed` generation.
2336 let chanmon_cfgs = create_chanmon_cfgs(3);
2337 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2338 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2339 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2341 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;
2342 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;
2344 let mut route = Route {
2347 pubkey: nodes[1].node.get_our_node_id(),
2348 node_features: channelmanager::provided_node_features(),
2349 short_channel_id: chan_1_scid,
2350 channel_features: channelmanager::provided_channel_features(),
2352 cltv_expiry_delta: 100,
2354 pubkey: nodes[2].node.get_our_node_id(),
2355 node_features: channelmanager::provided_node_features(),
2356 short_channel_id: chan_2_scid,
2357 channel_features: channelmanager::provided_channel_features(),
2358 fee_msat: 100_000_000,
2359 cltv_expiry_delta: 100,
2362 pubkey: nodes[1].node.get_our_node_id(),
2363 node_features: channelmanager::provided_node_features(),
2364 short_channel_id: chan_1_scid,
2365 channel_features: channelmanager::provided_channel_features(),
2367 cltv_expiry_delta: 100,
2369 pubkey: nodes[2].node.get_our_node_id(),
2370 node_features: channelmanager::provided_node_features(),
2371 short_channel_id: chan_2_scid,
2372 channel_features: channelmanager::provided_channel_features(),
2373 fee_msat: 100_000_000,
2374 cltv_expiry_delta: 100,
2377 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2379 let router = ManualRouter(RefCell::new(VecDeque::new()));
2380 router.expect_find_route(Ok(route.clone()));
2381 // On retry, we'll only be asked for one path
2382 route.paths.remove(1);
2383 router.expect_find_route(Ok(route.clone()));
2385 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2386 let event_handler = |event: &Event| {
2387 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2388 event_checker(event);
2390 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2392 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2393 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2394 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2396 let htlc_updates = SendEvent::from_node(&nodes[0]);
2397 check_added_monitors!(nodes[0], 1);
2398 assert_eq!(htlc_updates.msgs.len(), 1);
2400 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2401 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2402 check_added_monitors!(nodes[1], 1);
2403 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2405 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2406 check_added_monitors!(nodes[0], 1);
2407 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2409 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2410 check_added_monitors!(nodes[0], 1);
2411 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2414 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2415 check_added_monitors!(nodes[1], 1);
2416 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2418 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2419 check_added_monitors!(nodes[1], 1);
2420 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2422 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2423 check_added_monitors!(nodes[0], 1);
2425 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2426 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2427 check_added_monitors!(nodes[0], 1);
2428 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2430 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2431 check_added_monitors!(nodes[1], 1);
2432 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2434 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2435 check_added_monitors!(nodes[1], 1);
2436 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2438 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2439 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2440 check_added_monitors!(nodes[0], 1);
2442 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2443 check_added_monitors!(nodes[0], 1);
2444 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2446 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2447 check_added_monitors!(nodes[1], 1);
2448 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2449 check_added_monitors!(nodes[1], 1);
2450 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2452 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2453 check_added_monitors!(nodes[0], 1);
2455 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2456 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2457 // with it set. The first event will use up the only retry we are allowed, with the second
2458 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2459 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2460 // if the final HTLC failed.
2461 expected_events.borrow_mut().push_back(&|ev: &Event| {
2462 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2463 assert!(!payment_failed_permanently);
2464 assert!(all_paths_failed);
2465 } else { panic!("Unexpected event"); }
2467 nodes[0].node.process_pending_events(&invoice_payer);
2468 assert!(expected_events.borrow().is_empty());
2470 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2471 check_added_monitors!(nodes[0], 1);
2473 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2474 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2475 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2476 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2477 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2479 expected_events.borrow_mut().push_back(&|ev: &Event| {
2480 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2481 assert!(!payment_failed_permanently);
2482 assert!(all_paths_failed);
2483 } else { panic!("Unexpected event"); }
2485 expected_events.borrow_mut().push_back(&|ev: &Event| {
2486 if let Event::PaymentFailed { .. } = ev {
2487 } else { panic!("Unexpected event"); }
2489 nodes[0].node.process_pending_events(&invoice_payer);
2490 assert!(expected_events.borrow().is_empty());