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::{Route, RouteHop, RouteParameters};
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::{InFlightHtlcs, InvoicePayer, Payer, Retry, Router};
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, payment_hash: &PaymentHash,
78 //! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
79 //! # ) -> Result<Route, LightningError> { unimplemented!() }
81 //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
82 //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() }
83 //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() }
84 //! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
101 //! # struct FakeLogger {}
102 //! # impl Logger for FakeLogger {
103 //! # fn log(&self, record: &Record) { unimplemented!() }
107 //! let event_handler = |event: &Event| {
109 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
110 //! Event::PaymentSent { .. } => println!("payment successful"),
114 //! # let payer = FakePayer {};
115 //! # let router = FakeRouter {};
116 //! # let scorer = RefCell::new(FakeScorer {});
117 //! # let logger = FakeLogger {};
118 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
120 //! let invoice = "...";
121 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
122 //! invoice_payer.pay_invoice(&invoice).unwrap();
124 //! # let event_provider = FakeEventProvider {};
126 //! event_provider.process_pending_events(&invoice_payer);
134 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
135 //! as updates to the network graph or changes to channel scores should be applied prior to
136 //! retries, typically by way of composing [`EventHandler`]s accordingly.
140 use bitcoin_hashes::Hash;
141 use bitcoin_hashes::sha256::Hash as Sha256;
143 use crate::prelude::*;
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::{PaymentParameters, Route, RouteHop, RouteParameters};
150 use lightning::util::errors::APIError;
151 use lightning::util::events::{Event, EventHandler};
152 use lightning::util::logger::Logger;
153 use lightning::util::ser::Writeable;
154 use crate::time_utils::Time;
155 use crate::sync::Mutex;
157 use secp256k1::PublicKey;
160 use core::fmt::{Debug, Display, Formatter};
161 use core::ops::Deref;
162 use core::time::Duration;
163 #[cfg(feature = "std")]
164 use std::time::SystemTime;
166 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
168 /// See [module-level documentation] for details.
170 /// [module-level documentation]: crate::payment
171 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
173 #[cfg(not(feature = "no-std"))]
174 type ConfiguredTime = std::time::Instant;
175 #[cfg(feature = "no-std")]
176 use crate::time_utils;
177 #[cfg(feature = "no-std")]
178 type ConfiguredTime = time_utils::Eternity;
180 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
181 pub struct InvoicePayerUsingTime<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time>
190 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
191 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
195 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
196 /// currently being made, or have outstanding paths that need retrying.
197 struct PaymentInfo<T: Time> {
198 attempts: PaymentAttempts<T>,
199 paths: Vec<Vec<RouteHop>>,
202 impl<T: Time> PaymentInfo<T> {
205 attempts: PaymentAttempts::new(),
211 /// Storing minimal payment attempts information required for determining if a outbound payment can
213 #[derive(Clone, Copy)]
214 struct PaymentAttempts<T: Time> {
215 /// This count will be incremented only after the result of the attempt is known. When it's 0,
216 /// it means the result of the first attempt is now known yet.
218 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
219 first_attempted_at: T
222 impl<T: Time> PaymentAttempts<T> {
226 first_attempted_at: T::now()
231 impl<T: Time> Display for PaymentAttempts<T> {
232 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
233 #[cfg(feature = "no-std")]
234 return write!( f, "attempts: {}", self.count);
235 #[cfg(not(feature = "no-std"))]
238 "attempts: {}, duration: {}s",
240 T::now().duration_since(self.first_attempted_at).as_secs()
245 /// A trait defining behavior of an [`Invoice`] payer.
247 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
248 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
250 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
252 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
253 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
254 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
255 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
257 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
259 /// Returns the payer's node id.
260 fn node_id(&self) -> PublicKey;
262 /// Returns the payer's channels.
263 fn first_hops(&self) -> Vec<ChannelDetails>;
265 /// Sends a payment over the Lightning Network using the given [`Route`].
267 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
268 payment_id: PaymentId
269 ) -> Result<(), PaymentSendFailure>;
271 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
272 fn send_spontaneous_payment(
273 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
274 ) -> Result<(), PaymentSendFailure>;
276 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
277 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
279 /// Signals that no further retries for the given payment will occur.
280 fn abandon_payment(&self, payment_id: PaymentId);
283 /// A trait defining behavior for routing an [`Invoice`] payment.
285 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
287 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
288 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
289 ) -> Result<Route, LightningError>;
290 /// Lets the router know that payment through a specific path has failed.
291 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
292 /// Lets the router know that payment through a specific path was successful.
293 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
294 /// Lets the router know that a payment probe was successful.
295 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
296 /// Lets the router know that a payment probe failed.
297 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
300 /// Strategies available to retry payment path failures for an [`Invoice`].
302 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
304 /// Max number of attempts to retry payment.
306 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
307 /// payments, if this is less than the total number of paths, we will never even retry all of the
310 #[cfg(feature = "std")]
311 /// Time elapsed before abandoning retries for a payment.
316 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
317 match (self, attempts) {
318 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
319 max_retry_count >= &count
321 #[cfg(feature = "std")]
322 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
323 *max_duration >= T::now().duration_since(*first_attempted_at),
328 /// An error that may occur when making a payment.
329 #[derive(Clone, Debug)]
330 pub enum PaymentError {
331 /// An error resulting from the provided [`Invoice`] or payment hash.
332 Invoice(&'static str),
333 /// An error occurring when finding a route.
334 Routing(LightningError),
335 /// An error occurring when sending a payment.
336 Sending(PaymentSendFailure),
339 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
344 /// Creates an invoice payer that retries failed payment paths.
346 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
347 /// `retry` has been exceeded for a given [`Invoice`].
349 payer: P, router: R, logger: L, event_handler: E, retry: Retry
356 payment_cache: Mutex::new(HashMap::new()),
361 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
363 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
364 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
365 /// a second payment with the same [`PaymentHash`] is never sent.
367 /// If you wish to use a different payment idempotency token, see
368 /// [`Self::pay_invoice_with_id`].
369 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
370 let payment_id = PaymentId(invoice.payment_hash().into_inner());
371 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
374 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
375 /// in case a retry is needed.
377 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
378 /// payment completes or fails, no idempotency guarantees are made.
380 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
381 /// has never been paid before.
383 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
385 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
386 if invoice.amount_milli_satoshis().is_none() {
387 Err(PaymentError::Invoice("amount missing"))
389 self.pay_invoice_using_amount(invoice, None, payment_id)
393 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
394 /// case a retry is needed.
396 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
397 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
398 /// a second payment with the same [`PaymentHash`] is never sent.
400 /// If you wish to use a different payment idempotency token, see
401 /// [`Self::pay_zero_value_invoice_with_id`].
402 pub fn pay_zero_value_invoice(
403 &self, invoice: &Invoice, amount_msats: u64
404 ) -> Result<PaymentId, PaymentError> {
405 let payment_id = PaymentId(invoice.payment_hash().into_inner());
406 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
409 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
410 /// caching the invoice for later use in case a retry is needed.
412 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
413 /// payment completes or fails, no idempotency guarantees are made.
415 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
416 /// has never been paid before.
418 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
419 /// idempotency token.
420 pub fn pay_zero_value_invoice_with_id(
421 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
422 ) -> Result<(), PaymentError> {
423 if invoice.amount_milli_satoshis().is_some() {
424 Err(PaymentError::Invoice("amount unexpected"))
426 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
430 fn pay_invoice_using_amount(
431 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
432 ) -> Result<(), PaymentError> {
433 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
435 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
436 match self.payment_cache.lock().unwrap().entry(payment_hash) {
437 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
438 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
441 let payment_secret = Some(invoice.payment_secret().clone());
442 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
443 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
444 .with_route_hints(invoice.route_hints());
445 if let Some(features) = invoice.features() {
446 payment_params = payment_params.with_features(features.clone());
448 let route_params = RouteParameters {
450 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
451 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
454 let send_payment = |route: &Route| {
455 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
458 self.pay_internal(&route_params, payment_hash, send_payment)
459 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
462 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
463 /// case a retry is needed.
465 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
466 /// as long as the payment is still pending. Once the payment completes or fails, you must
467 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
469 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
470 final_cltv_expiry_delta: u32
471 ) -> Result<PaymentId, PaymentError> {
472 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
473 let payment_id = PaymentId(payment_hash.0);
474 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
475 final_cltv_expiry_delta)
476 .map(|()| payment_id)
479 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
480 /// caching the invoice for later use in case a retry is needed.
482 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
483 /// payment completes or fails, no idempotency guarantees are made.
485 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
486 /// [`PaymentHash`] has never been paid before.
487 pub fn pay_pubkey_with_id(
488 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
489 amount_msats: u64, final_cltv_expiry_delta: u32
490 ) -> Result<(), PaymentError> {
491 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
492 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
493 final_cltv_expiry_delta)
497 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
498 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
499 ) -> Result<(), PaymentError> {
500 match self.payment_cache.lock().unwrap().entry(payment_hash) {
501 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
502 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
505 let route_params = RouteParameters {
506 payment_params: PaymentParameters::for_keysend(pubkey),
507 final_value_msat: amount_msats,
508 final_cltv_expiry_delta,
511 let send_payment = |route: &Route| {
512 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
514 self.pay_internal(&route_params, payment_hash, send_payment)
515 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
518 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
519 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
520 ) -> Result<(), PaymentError> {
521 #[cfg(feature = "std")] {
522 if has_expired(params) {
523 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
524 return Err(PaymentError::Invoice("Invoice expired prior to send"));
528 let payer = self.payer.node_id();
529 let first_hops = self.payer.first_hops();
530 let inflight_htlcs = self.create_inflight_map();
531 let route = self.router.find_route(
532 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
534 ).map_err(|e| PaymentError::Routing(e))?;
536 match send_payment(&route) {
538 for path in route.paths {
539 self.process_path_inflight_htlcs(payment_hash, path);
544 PaymentSendFailure::ParameterError(_) => Err(e),
545 PaymentSendFailure::PathParameterError(_) => Err(e),
546 PaymentSendFailure::AllFailedRetrySafe(_) => {
547 let mut payment_cache = self.payment_cache.lock().unwrap();
548 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
549 payment_info.attempts.count += 1;
550 if self.retry.is_retryable_now(&payment_info.attempts) {
551 core::mem::drop(payment_cache);
552 Ok(self.pay_internal(params, payment_hash, send_payment)?)
557 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
558 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
559 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
560 // means that we are still waiting for our channel monitor update to be completed.
561 for (result, path) in results.iter().zip(route.paths.into_iter()) {
563 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
564 self.process_path_inflight_htlcs(payment_hash, path);
570 if let Some(retry_data) = failed_paths_retry {
571 // Some paths were sent, even if we failed to send the full MPP value our
572 // recipient may misbehave and claim the funds, at which point we have to
573 // consider the payment sent, so return `Ok()` here, ignoring any retry
575 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
578 // This may happen if we send a payment and some paths fail, but
579 // only due to a temporary monitor failure or the like, implying
580 // they're really in-flight, but we haven't sent the initial
581 // HTLC-Add messages yet.
586 }.map_err(|e| PaymentError::Sending(e))
589 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
590 // that are pending retry.
591 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
592 self.payment_cache.lock().unwrap().entry(payment_hash)
593 .or_insert_with(|| PaymentInfo::new())
597 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
598 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
599 self.payment_cache.lock().unwrap().entry(payment_hash)
600 .and_modify(|payment_info| {
601 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
602 payment_info.paths.swap_remove(idx);
608 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
609 ) -> Result<(), ()> {
610 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
611 .and_modify(|info| info.attempts.count += 1 )
612 .or_insert_with(|| PaymentInfo {
613 attempts: PaymentAttempts {
615 first_attempted_at: T::now(),
620 if !self.retry.is_retryable_now(&attempts) {
621 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
625 #[cfg(feature = "std")] {
626 if has_expired(params) {
627 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
632 let payer = self.payer.node_id();
633 let first_hops = self.payer.first_hops();
634 let inflight_htlcs = self.create_inflight_map();
636 let route = self.router.find_route(
637 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
642 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
646 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
648 for path in route.unwrap().paths.into_iter() {
649 self.process_path_inflight_htlcs(payment_hash, path);
653 Err(PaymentSendFailure::ParameterError(_)) |
654 Err(PaymentSendFailure::PathParameterError(_)) => {
655 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
658 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
659 self.retry_payment(payment_id, payment_hash, params)
661 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
662 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
663 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
664 // means that we are still waiting for our channel monitor update to complete.
665 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
667 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
668 self.process_path_inflight_htlcs(payment_hash, path);
674 if let Some(retry) = failed_paths_retry {
675 // Always return Ok for the same reason as noted in pay_internal.
676 let _ = self.retry_payment(payment_id, payment_hash, &retry);
683 /// Removes the payment cached by the given payment hash.
685 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
686 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
687 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
688 self.payment_cache.lock().unwrap().remove(payment_hash);
691 /// Given a [`PaymentHash`], this function looks up inflight path attempts in the payment_cache.
692 /// Then, it uses the path information inside the cache to construct a HashMap mapping a channel's
693 /// short channel id and direction to the amount being sent through it.
695 /// This function should be called whenever we need information about currently used up liquidity
697 fn create_inflight_map(&self) -> InFlightHtlcs {
698 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
699 // Make an attempt at finding existing payment information from `payment_cache`. If it
700 // does not exist, it probably is a fresh payment and we can just return an empty
702 for payment_info in self.payment_cache.lock().unwrap().values() {
703 for path in &payment_info.paths {
704 if path.is_empty() { break };
705 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
706 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
707 // the router excludes the payer node. In the following lines, the payer's information is
708 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
709 // in our sliding window of two.
710 let our_node_id: PublicKey = self.payer.node_id();
711 let reversed_hops_with_payer = path.iter().rev().skip(1)
712 .map(|hop| hop.pubkey)
713 .chain(core::iter::once(our_node_id));
714 let mut cumulative_msat = 0;
716 // Taking the reversed vector from above, we zip it with just the reversed hops list to
717 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
718 // the total amount sent.
719 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
720 cumulative_msat += next_hop.fee_msat;
722 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
723 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
724 .or_insert(cumulative_msat);
729 InFlightHtlcs(total_inflight_map)
733 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
734 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
737 #[cfg(feature = "std")]
738 fn has_expired(route_params: &RouteParameters) -> bool {
739 if let Some(expiry_time) = route_params.payment_params.expiry_time {
740 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
744 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
749 fn handle_event(&self, event: &Event) {
751 Event::PaymentPathFailed { payment_hash, path, .. }
752 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
753 | Event::ProbeSuccessful { payment_hash, path, .. }
754 | Event::ProbeFailed { payment_hash, path, .. } => {
755 self.remove_path_inflight_htlcs(*payment_hash, path);
761 Event::PaymentPathFailed {
762 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
764 if let Some(short_channel_id) = short_channel_id {
765 let path = path.iter().collect::<Vec<_>>();
766 self.router.notify_payment_path_failed(&path, *short_channel_id)
769 if payment_id.is_none() {
770 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
771 } else if *payment_failed_permanently {
772 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
773 self.payer.abandon_payment(payment_id.unwrap());
774 } else if retry.is_none() {
775 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
776 self.payer.abandon_payment(payment_id.unwrap());
777 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
778 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
781 self.payer.abandon_payment(payment_id.unwrap());
784 Event::PaymentFailed { payment_hash, .. } => {
785 self.remove_cached_payment(&payment_hash);
787 Event::PaymentPathSuccessful { path, .. } => {
788 let path = path.iter().collect::<Vec<_>>();
789 self.router.notify_payment_path_successful(&path);
791 Event::PaymentSent { payment_hash, .. } => {
792 let mut payment_cache = self.payment_cache.lock().unwrap();
793 let attempts = payment_cache
794 .remove(payment_hash)
795 .map_or(1, |payment_info| payment_info.attempts.count + 1);
796 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
798 Event::ProbeSuccessful { payment_hash, path, .. } => {
799 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
800 let path = path.iter().collect::<Vec<_>>();
801 self.router.notify_payment_probe_successful(&path);
803 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
804 if let Some(short_channel_id) = short_channel_id {
805 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
806 let path = path.iter().collect::<Vec<_>>();
807 self.router.notify_payment_probe_failed(&path, *short_channel_id);
813 // Delegate to the decorated event handler unless the payment is retried.
814 self.event_handler.handle_event(event)
818 /// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
819 /// is traveling in. The direction boolean is determined by checking if the HTLC source's public
820 /// key is less than its destination. See [`InFlightHtlcs::used_liquidity_msat`] for more
822 pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
825 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
827 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
828 self.0.get(&(channel_scid, source < target)).map(|v| *v)
832 impl Writeable for InFlightHtlcs {
833 fn write<W: lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
836 impl lightning::util::ser::Readable for InFlightHtlcs {
837 fn read<R: io::Read>(reader: &mut R) -> Result<Self, lightning::ln::msgs::DecodeError> {
838 let infight_map: HashMap<(u64, bool), u64> = lightning::util::ser::Readable::read(reader)?;
839 Ok(Self(infight_map))
846 use crate::{InvoiceBuilder, Currency};
847 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
848 use bitcoin_hashes::sha256::Hash as Sha256;
849 use lightning::ln::PaymentPreimage;
850 use lightning::ln::channelmanager;
851 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
852 use lightning::ln::functional_test_utils::*;
853 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
854 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
855 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
856 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
857 use lightning::util::test_utils::TestLogger;
858 use lightning::util::errors::APIError;
859 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
860 use secp256k1::{SecretKey, PublicKey, Secp256k1};
861 use std::cell::RefCell;
862 use std::collections::VecDeque;
863 use std::ops::DerefMut;
864 use std::time::{SystemTime, Duration};
865 use crate::time_utils::tests::SinceEpoch;
866 use crate::DEFAULT_EXPIRY_TIME;
867 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
869 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
870 let payment_hash = Sha256::hash(&payment_preimage.0);
871 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
873 InvoiceBuilder::new(Currency::Bitcoin)
874 .description("test".into())
875 .payment_hash(payment_hash)
876 .payment_secret(PaymentSecret([0; 32]))
877 .duration_since_epoch(duration_since_epoch())
878 .min_final_cltv_expiry(144)
879 .amount_milli_satoshis(128)
880 .build_signed(|hash| {
881 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
886 fn duration_since_epoch() -> Duration {
887 #[cfg(feature = "std")]
888 let duration_since_epoch =
889 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
890 #[cfg(not(feature = "std"))]
891 let duration_since_epoch = Duration::from_secs(1234567);
895 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
896 let payment_hash = Sha256::hash(&payment_preimage.0);
897 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
899 InvoiceBuilder::new(Currency::Bitcoin)
900 .description("test".into())
901 .payment_hash(payment_hash)
902 .payment_secret(PaymentSecret([0; 32]))
903 .duration_since_epoch(duration_since_epoch())
904 .min_final_cltv_expiry(144)
905 .build_signed(|hash| {
906 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
911 #[cfg(feature = "std")]
912 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
913 let payment_hash = Sha256::hash(&payment_preimage.0);
914 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
915 let duration = duration_since_epoch()
916 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
918 InvoiceBuilder::new(Currency::Bitcoin)
919 .description("test".into())
920 .payment_hash(payment_hash)
921 .payment_secret(PaymentSecret([0; 32]))
922 .duration_since_epoch(duration)
923 .min_final_cltv_expiry(144)
924 .amount_milli_satoshis(128)
925 .build_signed(|hash| {
926 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
931 fn pubkey() -> PublicKey {
932 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
936 fn pays_invoice_on_first_attempt() {
937 let event_handled = core::cell::RefCell::new(false);
938 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
940 let payment_preimage = PaymentPreimage([1; 32]);
941 let invoice = invoice(payment_preimage);
942 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
943 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
945 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
946 let router = TestRouter::new(TestScorer::new());
947 let logger = TestLogger::new();
949 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
951 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
952 assert_eq!(*payer.attempts.borrow(), 1);
954 invoice_payer.handle_event(&Event::PaymentSent {
955 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
957 assert_eq!(*event_handled.borrow(), true);
958 assert_eq!(*payer.attempts.borrow(), 1);
962 fn pays_invoice_on_retry() {
963 let event_handled = core::cell::RefCell::new(false);
964 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
966 let payment_preimage = PaymentPreimage([1; 32]);
967 let invoice = invoice(payment_preimage);
968 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
969 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
971 let payer = TestPayer::new()
972 .expect_send(Amount::ForInvoice(final_value_msat))
973 .expect_send(Amount::OnRetry(final_value_msat / 2));
974 let router = TestRouter::new(TestScorer::new());
975 let logger = TestLogger::new();
977 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
979 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
980 assert_eq!(*payer.attempts.borrow(), 1);
982 let event = Event::PaymentPathFailed {
985 network_update: None,
986 payment_failed_permanently: false,
987 all_paths_failed: false,
988 path: TestRouter::path_for_value(final_value_msat),
989 short_channel_id: None,
990 retry: Some(TestRouter::retry_for_invoice(&invoice)),
992 invoice_payer.handle_event(&event);
993 assert_eq!(*event_handled.borrow(), false);
994 assert_eq!(*payer.attempts.borrow(), 2);
996 invoice_payer.handle_event(&Event::PaymentSent {
997 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
999 assert_eq!(*event_handled.borrow(), true);
1000 assert_eq!(*payer.attempts.borrow(), 2);
1004 fn pays_invoice_on_partial_failure() {
1005 let event_handler = |_: &_| { panic!() };
1007 let payment_preimage = PaymentPreimage([1; 32]);
1008 let invoice = invoice(payment_preimage);
1009 let retry = TestRouter::retry_for_invoice(&invoice);
1010 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1012 let payer = TestPayer::new()
1013 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
1014 .fails_with_partial_failure(retry, OnAttempt(2), None)
1015 .expect_send(Amount::ForInvoice(final_value_msat))
1016 .expect_send(Amount::OnRetry(final_value_msat / 2))
1017 .expect_send(Amount::OnRetry(final_value_msat / 2));
1018 let router = TestRouter::new(TestScorer::new());
1019 let logger = TestLogger::new();
1021 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1023 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1027 fn retries_payment_path_for_unknown_payment() {
1028 let event_handled = core::cell::RefCell::new(false);
1029 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1031 let payment_preimage = PaymentPreimage([1; 32]);
1032 let invoice = invoice(payment_preimage);
1033 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1034 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1036 let payer = TestPayer::new()
1037 .expect_send(Amount::OnRetry(final_value_msat / 2))
1038 .expect_send(Amount::OnRetry(final_value_msat / 2));
1039 let router = TestRouter::new(TestScorer::new());
1040 let logger = TestLogger::new();
1042 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1044 let payment_id = Some(PaymentId([1; 32]));
1045 let event = Event::PaymentPathFailed {
1048 network_update: None,
1049 payment_failed_permanently: false,
1050 all_paths_failed: false,
1051 path: TestRouter::path_for_value(final_value_msat),
1052 short_channel_id: None,
1053 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1055 invoice_payer.handle_event(&event);
1056 assert_eq!(*event_handled.borrow(), false);
1057 assert_eq!(*payer.attempts.borrow(), 1);
1059 invoice_payer.handle_event(&event);
1060 assert_eq!(*event_handled.borrow(), false);
1061 assert_eq!(*payer.attempts.borrow(), 2);
1063 invoice_payer.handle_event(&Event::PaymentSent {
1064 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1066 assert_eq!(*event_handled.borrow(), true);
1067 assert_eq!(*payer.attempts.borrow(), 2);
1071 fn fails_paying_invoice_after_max_retry_counts() {
1072 let event_handled = core::cell::RefCell::new(false);
1073 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1075 let payment_preimage = PaymentPreimage([1; 32]);
1076 let invoice = invoice(payment_preimage);
1077 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1079 let payer = TestPayer::new()
1080 .expect_send(Amount::ForInvoice(final_value_msat))
1081 .expect_send(Amount::OnRetry(final_value_msat / 2))
1082 .expect_send(Amount::OnRetry(final_value_msat / 2));
1083 let router = TestRouter::new(TestScorer::new());
1084 let logger = TestLogger::new();
1086 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1088 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1089 assert_eq!(*payer.attempts.borrow(), 1);
1091 let event = Event::PaymentPathFailed {
1093 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1094 network_update: None,
1095 payment_failed_permanently: false,
1096 all_paths_failed: true,
1097 path: TestRouter::path_for_value(final_value_msat),
1098 short_channel_id: None,
1099 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1101 invoice_payer.handle_event(&event);
1102 assert_eq!(*event_handled.borrow(), false);
1103 assert_eq!(*payer.attempts.borrow(), 2);
1105 let event = Event::PaymentPathFailed {
1107 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1108 network_update: None,
1109 payment_failed_permanently: false,
1110 all_paths_failed: false,
1111 path: TestRouter::path_for_value(final_value_msat / 2),
1112 short_channel_id: None,
1113 retry: Some(RouteParameters {
1114 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1117 invoice_payer.handle_event(&event);
1118 assert_eq!(*event_handled.borrow(), false);
1119 assert_eq!(*payer.attempts.borrow(), 3);
1121 invoice_payer.handle_event(&event);
1122 assert_eq!(*event_handled.borrow(), true);
1123 assert_eq!(*payer.attempts.borrow(), 3);
1126 #[cfg(feature = "std")]
1128 fn fails_paying_invoice_after_max_retry_timeout() {
1129 let event_handled = core::cell::RefCell::new(false);
1130 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1132 let payment_preimage = PaymentPreimage([1; 32]);
1133 let invoice = invoice(payment_preimage);
1134 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1136 let payer = TestPayer::new()
1137 .expect_send(Amount::ForInvoice(final_value_msat))
1138 .expect_send(Amount::OnRetry(final_value_msat / 2));
1140 let router = TestRouter::new(TestScorer::new());
1141 let logger = TestLogger::new();
1142 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1145 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1147 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1148 assert_eq!(*payer.attempts.borrow(), 1);
1150 let event = Event::PaymentPathFailed {
1152 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1153 network_update: None,
1154 payment_failed_permanently: false,
1155 all_paths_failed: true,
1156 path: TestRouter::path_for_value(final_value_msat),
1157 short_channel_id: None,
1158 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1160 invoice_payer.handle_event(&event);
1161 assert_eq!(*event_handled.borrow(), false);
1162 assert_eq!(*payer.attempts.borrow(), 2);
1164 SinceEpoch::advance(Duration::from_secs(121));
1166 invoice_payer.handle_event(&event);
1167 assert_eq!(*event_handled.borrow(), true);
1168 assert_eq!(*payer.attempts.borrow(), 2);
1172 fn fails_paying_invoice_with_missing_retry_params() {
1173 let event_handled = core::cell::RefCell::new(false);
1174 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1176 let payment_preimage = PaymentPreimage([1; 32]);
1177 let invoice = invoice(payment_preimage);
1178 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1180 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1181 let router = TestRouter::new(TestScorer::new());
1182 let logger = TestLogger::new();
1184 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1186 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1187 assert_eq!(*payer.attempts.borrow(), 1);
1189 let event = Event::PaymentPathFailed {
1191 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1192 network_update: None,
1193 payment_failed_permanently: false,
1194 all_paths_failed: false,
1196 short_channel_id: None,
1199 invoice_payer.handle_event(&event);
1200 assert_eq!(*event_handled.borrow(), true);
1201 assert_eq!(*payer.attempts.borrow(), 1);
1204 // Expiration is checked only in an std environment
1205 #[cfg(feature = "std")]
1207 fn fails_paying_invoice_after_expiration() {
1208 let event_handled = core::cell::RefCell::new(false);
1209 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1211 let payer = TestPayer::new();
1212 let router = TestRouter::new(TestScorer::new());
1213 let logger = TestLogger::new();
1215 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1217 let payment_preimage = PaymentPreimage([1; 32]);
1218 let invoice = expired_invoice(payment_preimage);
1219 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1220 assert_eq!(msg, "Invoice expired prior to send");
1221 } else { panic!("Expected Invoice Error"); }
1224 // Expiration is checked only in an std environment
1225 #[cfg(feature = "std")]
1227 fn fails_retrying_invoice_after_expiration() {
1228 let event_handled = core::cell::RefCell::new(false);
1229 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1231 let payment_preimage = PaymentPreimage([1; 32]);
1232 let invoice = invoice(payment_preimage);
1233 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1235 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1236 let router = TestRouter::new(TestScorer::new());
1237 let logger = TestLogger::new();
1239 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1241 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1242 assert_eq!(*payer.attempts.borrow(), 1);
1244 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1245 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1246 .checked_sub(Duration::from_secs(2)).unwrap()
1247 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1248 let event = Event::PaymentPathFailed {
1250 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1251 network_update: None,
1252 payment_failed_permanently: false,
1253 all_paths_failed: false,
1255 short_channel_id: None,
1256 retry: Some(retry_data),
1258 invoice_payer.handle_event(&event);
1259 assert_eq!(*event_handled.borrow(), true);
1260 assert_eq!(*payer.attempts.borrow(), 1);
1264 fn fails_paying_invoice_after_retry_error() {
1265 let event_handled = core::cell::RefCell::new(false);
1266 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1268 let payment_preimage = PaymentPreimage([1; 32]);
1269 let invoice = invoice(payment_preimage);
1270 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1272 let payer = TestPayer::new()
1273 .fails_on_attempt(2)
1274 .expect_send(Amount::ForInvoice(final_value_msat))
1275 .expect_send(Amount::OnRetry(final_value_msat / 2));
1276 let router = TestRouter::new(TestScorer::new());
1277 let logger = TestLogger::new();
1279 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1281 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1282 assert_eq!(*payer.attempts.borrow(), 1);
1284 let event = Event::PaymentPathFailed {
1286 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1287 network_update: None,
1288 payment_failed_permanently: false,
1289 all_paths_failed: false,
1290 path: TestRouter::path_for_value(final_value_msat / 2),
1291 short_channel_id: None,
1292 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1294 invoice_payer.handle_event(&event);
1295 assert_eq!(*event_handled.borrow(), true);
1296 assert_eq!(*payer.attempts.borrow(), 2);
1300 fn fails_paying_invoice_after_rejected_by_payee() {
1301 let event_handled = core::cell::RefCell::new(false);
1302 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1304 let payment_preimage = PaymentPreimage([1; 32]);
1305 let invoice = invoice(payment_preimage);
1306 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1308 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1309 let router = TestRouter::new(TestScorer::new());
1310 let logger = TestLogger::new();
1312 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1314 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1315 assert_eq!(*payer.attempts.borrow(), 1);
1317 let event = Event::PaymentPathFailed {
1319 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1320 network_update: None,
1321 payment_failed_permanently: true,
1322 all_paths_failed: false,
1324 short_channel_id: None,
1325 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1327 invoice_payer.handle_event(&event);
1328 assert_eq!(*event_handled.borrow(), true);
1329 assert_eq!(*payer.attempts.borrow(), 1);
1333 fn fails_repaying_invoice_with_pending_payment() {
1334 let event_handled = core::cell::RefCell::new(false);
1335 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1337 let payment_preimage = PaymentPreimage([1; 32]);
1338 let invoice = invoice(payment_preimage);
1339 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1341 let payer = TestPayer::new()
1342 .expect_send(Amount::ForInvoice(final_value_msat))
1343 .expect_send(Amount::ForInvoice(final_value_msat));
1344 let router = TestRouter::new(TestScorer::new());
1345 let logger = TestLogger::new();
1347 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1349 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1351 // Cannot repay an invoice pending payment.
1352 match invoice_payer.pay_invoice(&invoice) {
1353 Err(PaymentError::Invoice("payment pending")) => {},
1354 Err(_) => panic!("unexpected error"),
1355 Ok(_) => panic!("expected invoice error"),
1358 // Can repay an invoice once cleared from cache.
1359 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1360 invoice_payer.remove_cached_payment(&payment_hash);
1361 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1363 // Cannot retry paying an invoice if cleared from cache.
1364 invoice_payer.remove_cached_payment(&payment_hash);
1365 let event = Event::PaymentPathFailed {
1368 network_update: None,
1369 payment_failed_permanently: false,
1370 all_paths_failed: false,
1372 short_channel_id: None,
1373 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1375 invoice_payer.handle_event(&event);
1376 assert_eq!(*event_handled.borrow(), true);
1380 fn fails_paying_invoice_with_routing_errors() {
1381 let payer = TestPayer::new();
1382 let router = FailingRouter {};
1383 let logger = TestLogger::new();
1385 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1387 let payment_preimage = PaymentPreimage([1; 32]);
1388 let invoice = invoice(payment_preimage);
1389 match invoice_payer.pay_invoice(&invoice) {
1390 Err(PaymentError::Routing(_)) => {},
1391 Err(_) => panic!("unexpected error"),
1392 Ok(_) => panic!("expected routing error"),
1397 fn fails_paying_invoice_with_sending_errors() {
1398 let payment_preimage = PaymentPreimage([1; 32]);
1399 let invoice = invoice(payment_preimage);
1400 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1402 let payer = TestPayer::new()
1403 .fails_on_attempt(1)
1404 .expect_send(Amount::ForInvoice(final_value_msat));
1405 let router = TestRouter::new(TestScorer::new());
1406 let logger = TestLogger::new();
1408 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1410 match invoice_payer.pay_invoice(&invoice) {
1411 Err(PaymentError::Sending(_)) => {},
1412 Err(_) => panic!("unexpected error"),
1413 Ok(_) => panic!("expected sending error"),
1418 fn pays_zero_value_invoice_using_amount() {
1419 let event_handled = core::cell::RefCell::new(false);
1420 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1422 let payment_preimage = PaymentPreimage([1; 32]);
1423 let invoice = zero_value_invoice(payment_preimage);
1424 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1425 let final_value_msat = 100;
1427 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1428 let router = TestRouter::new(TestScorer::new());
1429 let logger = TestLogger::new();
1431 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1434 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1435 assert_eq!(*payer.attempts.borrow(), 1);
1437 invoice_payer.handle_event(&Event::PaymentSent {
1438 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1440 assert_eq!(*event_handled.borrow(), true);
1441 assert_eq!(*payer.attempts.borrow(), 1);
1445 fn fails_paying_zero_value_invoice_with_amount() {
1446 let event_handled = core::cell::RefCell::new(false);
1447 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1449 let payer = TestPayer::new();
1450 let router = TestRouter::new(TestScorer::new());
1451 let logger = TestLogger::new();
1453 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1455 let payment_preimage = PaymentPreimage([1; 32]);
1456 let invoice = invoice(payment_preimage);
1458 // Cannot repay an invoice pending payment.
1459 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1460 Err(PaymentError::Invoice("amount unexpected")) => {},
1461 Err(_) => panic!("unexpected error"),
1462 Ok(_) => panic!("expected invoice error"),
1467 fn pays_pubkey_with_amount() {
1468 let event_handled = core::cell::RefCell::new(false);
1469 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1471 let pubkey = pubkey();
1472 let payment_preimage = PaymentPreimage([1; 32]);
1473 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1474 let final_value_msat = 100;
1475 let final_cltv_expiry_delta = 42;
1477 let payer = TestPayer::new()
1478 .expect_send(Amount::Spontaneous(final_value_msat))
1479 .expect_send(Amount::OnRetry(final_value_msat));
1480 let router = TestRouter::new(TestScorer::new());
1481 let logger = TestLogger::new();
1483 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1485 let payment_id = Some(invoice_payer.pay_pubkey(
1486 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1488 assert_eq!(*payer.attempts.borrow(), 1);
1490 let retry = RouteParameters {
1491 payment_params: PaymentParameters::for_keysend(pubkey),
1493 final_cltv_expiry_delta,
1495 let event = Event::PaymentPathFailed {
1498 network_update: None,
1499 payment_failed_permanently: false,
1500 all_paths_failed: false,
1502 short_channel_id: None,
1505 invoice_payer.handle_event(&event);
1506 assert_eq!(*event_handled.borrow(), false);
1507 assert_eq!(*payer.attempts.borrow(), 2);
1509 invoice_payer.handle_event(&Event::PaymentSent {
1510 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1512 assert_eq!(*event_handled.borrow(), true);
1513 assert_eq!(*payer.attempts.borrow(), 2);
1517 fn scores_failed_channel() {
1518 let event_handled = core::cell::RefCell::new(false);
1519 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1521 let payment_preimage = PaymentPreimage([1; 32]);
1522 let invoice = invoice(payment_preimage);
1523 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1524 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1525 let path = TestRouter::path_for_value(final_value_msat);
1526 let short_channel_id = Some(path[0].short_channel_id);
1528 // Expect that scorer is given short_channel_id upon handling the event.
1529 let payer = TestPayer::new()
1530 .expect_send(Amount::ForInvoice(final_value_msat))
1531 .expect_send(Amount::OnRetry(final_value_msat / 2));
1532 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1533 path: path.clone(), short_channel_id: path[0].short_channel_id,
1535 let router = TestRouter::new(scorer);
1536 let logger = TestLogger::new();
1538 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1540 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1541 let event = Event::PaymentPathFailed {
1544 network_update: None,
1545 payment_failed_permanently: false,
1546 all_paths_failed: false,
1549 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1551 invoice_payer.handle_event(&event);
1555 fn scores_successful_channels() {
1556 let event_handled = core::cell::RefCell::new(false);
1557 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1559 let payment_preimage = PaymentPreimage([1; 32]);
1560 let invoice = invoice(payment_preimage);
1561 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1562 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1563 let route = TestRouter::route_for_value(final_value_msat);
1565 // Expect that scorer is given short_channel_id upon handling the event.
1566 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1567 let scorer = TestScorer::new()
1568 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1569 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1570 let router = TestRouter::new(scorer);
1571 let logger = TestLogger::new();
1573 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1575 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1576 let event = Event::PaymentPathSuccessful {
1577 payment_id, payment_hash, path: route.paths[0].clone()
1579 invoice_payer.handle_event(&event);
1580 let event = Event::PaymentPathSuccessful {
1581 payment_id, payment_hash, path: route.paths[1].clone()
1583 invoice_payer.handle_event(&event);
1587 fn generates_correct_inflight_map_data() {
1588 let event_handled = core::cell::RefCell::new(false);
1589 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1591 let payment_preimage = PaymentPreimage([1; 32]);
1592 let invoice = invoice(payment_preimage);
1593 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1594 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1596 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1597 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1598 let route = TestRouter::route_for_value(final_value_msat);
1599 let router = TestRouter::new(TestScorer::new());
1600 let logger = TestLogger::new();
1602 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1604 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1606 let inflight_map = invoice_payer.create_inflight_map();
1608 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1609 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1610 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1612 // Second path check
1613 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1614 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1616 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1617 payment_id, payment_hash, path: route.paths[0].clone()
1620 let inflight_map = invoice_payer.create_inflight_map();
1622 assert_eq!(inflight_map.0.get(&(0, false)), None);
1623 assert_eq!(inflight_map.0.get(&(1, true)), None);
1624 assert_eq!(inflight_map.0.get(&(2, false)), None);
1626 // Second path should still be inflight
1627 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1628 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1632 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1633 // First, let's just send a payment through, but only make sure one of the path completes
1634 let event_handled = core::cell::RefCell::new(false);
1635 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1637 let payment_preimage = PaymentPreimage([1; 32]);
1638 let payment_invoice = invoice(payment_preimage);
1639 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1640 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1642 let payer = TestPayer::new()
1643 .expect_send(Amount::ForInvoice(final_value_msat))
1644 .expect_send(Amount::ForInvoice(final_value_msat));
1645 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1646 let route = TestRouter::route_for_value(final_value_msat);
1647 let scorer = TestScorer::new()
1648 // 1st invoice, 1st path
1649 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1650 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1651 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1652 // 1st invoice, 2nd path
1653 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1654 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1655 // 2nd invoice, 1st path
1656 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1657 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1658 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1659 // 2nd invoice, 2nd path
1660 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1661 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1662 let router = TestRouter::new(scorer);
1663 let logger = TestLogger::new();
1665 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1667 // Succeed 1st path, leave 2nd path inflight
1668 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1669 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1670 payment_id, payment_hash, path: route.paths[0].clone()
1673 // Let's pay a second invoice that will be using the same path. This should trigger the
1674 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1675 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1676 // have 64 msats inflight for paths considering the channel with scid of 1.
1677 let payment_preimage_2 = PaymentPreimage([2; 32]);
1678 let payment_invoice_2 = invoice(payment_preimage_2);
1679 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1683 fn considers_inflight_htlcs_between_retries() {
1684 // First, let's just send a payment through, but only make sure one of the path completes
1685 let event_handled = core::cell::RefCell::new(false);
1686 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1688 let payment_preimage = PaymentPreimage([1; 32]);
1689 let payment_invoice = invoice(payment_preimage);
1690 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1691 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1693 let payer = TestPayer::new()
1694 .expect_send(Amount::ForInvoice(final_value_msat))
1695 .expect_send(Amount::OnRetry(final_value_msat / 2))
1696 .expect_send(Amount::OnRetry(final_value_msat / 4));
1697 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1698 let scorer = TestScorer::new()
1699 // 1st invoice, 1st path
1700 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1701 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1702 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1703 // 1st invoice, 2nd path
1704 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1705 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1706 // Retry 1, 1st path
1707 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1708 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1709 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1710 // Retry 1, 2nd path
1711 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1712 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1713 // Retry 2, 1st path
1714 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1715 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1716 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1717 // Retry 2, 2nd path
1718 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1719 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1720 let router = TestRouter::new(scorer);
1721 let logger = TestLogger::new();
1723 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1725 // Fail 1st path, leave 2nd path inflight
1726 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1727 invoice_payer.handle_event(&Event::PaymentPathFailed {
1730 network_update: None,
1731 payment_failed_permanently: false,
1732 all_paths_failed: false,
1733 path: TestRouter::path_for_value(final_value_msat),
1734 short_channel_id: None,
1735 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1738 // Fails again the 1st path of our retry
1739 invoice_payer.handle_event(&Event::PaymentPathFailed {
1742 network_update: None,
1743 payment_failed_permanently: false,
1744 all_paths_failed: false,
1745 path: TestRouter::path_for_value(final_value_msat / 2),
1746 short_channel_id: None,
1747 retry: Some(RouteParameters {
1748 final_value_msat: final_value_msat / 4,
1749 ..TestRouter::retry_for_invoice(&payment_invoice)
1755 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1756 let event_handled = core::cell::RefCell::new(false);
1757 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1759 let payment_preimage = PaymentPreimage([1; 32]);
1760 let invoice_to_pay = invoice(payment_preimage);
1761 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1763 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1764 let payer = TestPayer::new()
1765 .fails_with_partial_failure(
1766 retry.clone(), OnAttempt(1),
1768 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1770 .expect_send(Amount::ForInvoice(final_value_msat));
1772 let router = TestRouter::new(TestScorer::new());
1773 let logger = TestLogger::new();
1775 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1777 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1778 let inflight_map = invoice_payer.create_inflight_map();
1780 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1781 // inflight map because retries are disabled.
1782 assert_eq!(inflight_map.0.len(), 2);
1786 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1787 let event_handled = core::cell::RefCell::new(false);
1788 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1790 let payment_preimage = PaymentPreimage([1; 32]);
1791 let invoice_to_pay = invoice(payment_preimage);
1792 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1794 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1795 let payer = TestPayer::new()
1796 .fails_with_partial_failure(
1797 retry.clone(), OnAttempt(1),
1799 Ok(()), Err(MonitorUpdateInProgress)
1801 .expect_send(Amount::ForInvoice(final_value_msat));
1803 let router = TestRouter::new(TestScorer::new());
1804 let logger = TestLogger::new();
1806 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1808 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1809 let inflight_map = invoice_payer.create_inflight_map();
1811 // All paths successful, hence we check of the existence of all 5 hops.
1812 assert_eq!(inflight_map.0.len(), 5);
1816 scorer: RefCell<TestScorer>,
1820 fn new(scorer: TestScorer) -> Self {
1821 TestRouter { scorer: RefCell::new(scorer) }
1824 fn route_for_value(final_value_msat: u64) -> Route {
1829 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1830 channel_features: ChannelFeatures::empty(),
1831 node_features: NodeFeatures::empty(),
1832 short_channel_id: 0,
1834 cltv_expiry_delta: 0
1837 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1838 channel_features: ChannelFeatures::empty(),
1839 node_features: NodeFeatures::empty(),
1840 short_channel_id: 1,
1842 cltv_expiry_delta: 0
1845 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1846 channel_features: ChannelFeatures::empty(),
1847 node_features: NodeFeatures::empty(),
1848 short_channel_id: 2,
1849 fee_msat: final_value_msat / 2,
1850 cltv_expiry_delta: 0
1855 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1856 channel_features: ChannelFeatures::empty(),
1857 node_features: NodeFeatures::empty(),
1858 short_channel_id: 3,
1860 cltv_expiry_delta: 144
1863 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1864 channel_features: ChannelFeatures::empty(),
1865 node_features: NodeFeatures::empty(),
1866 short_channel_id: 4,
1867 fee_msat: final_value_msat / 2,
1868 cltv_expiry_delta: 144
1872 payment_params: None,
1876 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1877 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1880 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1881 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1882 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1883 .with_route_hints(invoice.route_hints());
1884 if let Some(features) = invoice.features() {
1885 payment_params = payment_params.with_features(features.clone());
1887 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1891 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1896 impl Router for TestRouter {
1898 &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1899 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1900 ) -> Result<Route, LightningError> {
1901 // Simulate calling the Scorer just as you would in find_route
1902 let route = Self::route_for_value(route_params.final_value_msat);
1903 let mut locked_scorer = self.scorer.lock();
1904 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1905 for path in route.paths {
1906 let mut aggregate_msat = 0u64;
1907 for (idx, hop) in path.iter().rev().enumerate() {
1908 aggregate_msat += hop.fee_msat;
1909 let usage = ChannelUsage {
1910 amount_msat: aggregate_msat,
1911 inflight_htlc_msat: 0,
1912 effective_capacity: EffectiveCapacity::Unknown,
1915 // Since the path is reversed, the last element in our iteration is the first
1917 if idx == path.len() - 1 {
1918 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1920 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1926 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1930 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1931 self.scorer.lock().payment_path_failed(path, short_channel_id);
1934 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1935 self.scorer.lock().payment_path_successful(path);
1938 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1939 self.scorer.lock().probe_successful(path);
1942 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1943 self.scorer.lock().probe_failed(path, short_channel_id);
1947 struct FailingRouter;
1949 impl Router for FailingRouter {
1951 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1952 _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
1953 ) -> Result<Route, LightningError> {
1954 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1957 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1959 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1961 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1963 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1967 event_expectations: Option<VecDeque<TestResult>>,
1968 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1973 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1974 PaymentSuccess { path: Vec<RouteHop> },
1980 event_expectations: None,
1981 scorer_expectations: RefCell::new(None),
1985 fn expect(mut self, expectation: TestResult) -> Self {
1986 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1990 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1991 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1997 impl lightning::util::ser::Writeable for TestScorer {
1998 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
2001 impl Score for TestScorer {
2002 fn channel_penalty_msat(
2003 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
2005 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
2006 match scorer_expectations.pop_front() {
2007 Some(expectation) => {
2008 assert_eq!(expectation.amount_msat, usage.amount_msat);
2009 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
2017 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
2018 if let Some(expectations) = &mut self.event_expectations {
2019 match expectations.pop_front() {
2020 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
2021 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2022 assert_eq!(actual_short_channel_id, short_channel_id);
2024 Some(TestResult::PaymentSuccess { path }) => {
2025 panic!("Unexpected successful payment path: {:?}", path)
2027 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2032 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
2033 if let Some(expectations) = &mut self.event_expectations {
2034 match expectations.pop_front() {
2035 Some(TestResult::PaymentFailure { path, .. }) => {
2036 panic!("Unexpected payment path failure: {:?}", path)
2038 Some(TestResult::PaymentSuccess { path }) => {
2039 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
2041 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2046 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
2047 if let Some(expectations) = &mut self.event_expectations {
2048 match expectations.pop_front() {
2049 Some(TestResult::PaymentFailure { path, .. }) => {
2050 panic!("Unexpected failed payment path: {:?}", path)
2052 Some(TestResult::PaymentSuccess { path }) => {
2053 panic!("Unexpected successful payment path: {:?}", path)
2055 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
2059 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
2060 if let Some(expectations) = &mut self.event_expectations {
2061 match expectations.pop_front() {
2062 Some(TestResult::PaymentFailure { path, .. }) => {
2063 panic!("Unexpected payment path failure: {:?}", path)
2065 Some(TestResult::PaymentSuccess { path }) => {
2066 panic!("Unexpected successful payment path: {:?}", path)
2068 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
2074 impl Drop for TestScorer {
2075 fn drop(&mut self) {
2076 if std::thread::panicking() {
2080 if let Some(event_expectations) = &self.event_expectations {
2081 if !event_expectations.is_empty() {
2082 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2086 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2087 if !scorer_expectations.is_empty() {
2088 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2095 expectations: core::cell::RefCell<VecDeque<Amount>>,
2096 attempts: core::cell::RefCell<usize>,
2097 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2100 #[derive(Clone, Debug, PartialEq, Eq)]
2107 struct OnAttempt(usize);
2112 expectations: core::cell::RefCell::new(VecDeque::new()),
2113 attempts: core::cell::RefCell::new(0),
2114 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2118 fn expect_send(self, value_msat: Amount) -> Self {
2119 self.expectations.borrow_mut().push_back(value_msat);
2123 fn fails_on_attempt(self, attempt: usize) -> Self {
2124 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2125 self.fails_with(failure, OnAttempt(attempt))
2128 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2129 self.fails_with(PaymentSendFailure::PartialFailure {
2130 results: results.unwrap_or(vec![]),
2131 failed_paths_retry: Some(retry),
2132 payment_id: PaymentId([1; 32]),
2136 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2137 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2141 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
2142 let mut attempts = self.attempts.borrow_mut();
2145 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2146 Some(failure) => Err(failure),
2151 fn check_value_msats(&self, actual_value_msats: Amount) {
2152 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2153 if let Some(expected_value_msats) = expected_value_msats {
2154 assert_eq!(actual_value_msats, expected_value_msats);
2156 panic!("Unexpected amount: {:?}", actual_value_msats);
2161 impl Drop for TestPayer {
2162 fn drop(&mut self) {
2163 if std::thread::panicking() {
2167 if !self.expectations.borrow().is_empty() {
2168 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2173 impl Payer for TestPayer {
2174 fn node_id(&self) -> PublicKey {
2175 let secp_ctx = Secp256k1::new();
2176 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2179 fn first_hops(&self) -> Vec<ChannelDetails> {
2184 &self, route: &Route, _payment_hash: PaymentHash,
2185 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2186 ) -> Result<(), PaymentSendFailure> {
2187 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2188 self.check_attempts()
2191 fn send_spontaneous_payment(
2192 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2193 ) -> Result<(), PaymentSendFailure> {
2194 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2195 self.check_attempts()
2199 &self, route: &Route, _payment_id: PaymentId
2200 ) -> Result<(), PaymentSendFailure> {
2201 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2202 self.check_attempts()
2205 fn abandon_payment(&self, _payment_id: PaymentId) { }
2208 // *** Full Featured Functional Tests with a Real ChannelManager ***
2209 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2211 impl Router for ManualRouter {
2213 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
2214 _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
2215 ) -> Result<Route, LightningError> {
2216 self.0.borrow_mut().pop_front().unwrap()
2219 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2221 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2223 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2225 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2228 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2229 self.0.borrow_mut().push_back(result);
2232 impl Drop for ManualRouter {
2233 fn drop(&mut self) {
2234 if std::thread::panicking() {
2237 assert!(self.0.borrow_mut().is_empty());
2242 fn retry_multi_path_single_failed_payment() {
2243 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2244 let chanmon_cfgs = create_chanmon_cfgs(2);
2245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2249 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2250 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2251 let chans = nodes[0].node.list_usable_channels();
2252 let mut route = Route {
2255 pubkey: nodes[1].node.get_our_node_id(),
2256 node_features: channelmanager::provided_node_features(),
2257 short_channel_id: chans[0].short_channel_id.unwrap(),
2258 channel_features: channelmanager::provided_channel_features(),
2260 cltv_expiry_delta: 100,
2263 pubkey: nodes[1].node.get_our_node_id(),
2264 node_features: channelmanager::provided_node_features(),
2265 short_channel_id: chans[1].short_channel_id.unwrap(),
2266 channel_features: channelmanager::provided_channel_features(),
2267 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2268 cltv_expiry_delta: 100,
2271 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2273 let router = ManualRouter(RefCell::new(VecDeque::new()));
2274 router.expect_find_route(Ok(route.clone()));
2275 // On retry, split the payment across both channels.
2276 route.paths[0][0].fee_msat = 50_000_001;
2277 route.paths[1][0].fee_msat = 50_000_000;
2278 router.expect_find_route(Ok(route.clone()));
2280 let event_handler = |_: &_| { panic!(); };
2281 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2283 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2284 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2285 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2287 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2288 assert_eq!(htlc_msgs.len(), 2);
2289 check_added_monitors!(nodes[0], 2);
2293 fn immediate_retry_on_failure() {
2294 // Tests that we can/will retry immediately after a failure
2295 let chanmon_cfgs = create_chanmon_cfgs(2);
2296 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2297 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2298 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2300 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2301 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2302 let chans = nodes[0].node.list_usable_channels();
2303 let mut route = Route {
2306 pubkey: nodes[1].node.get_our_node_id(),
2307 node_features: channelmanager::provided_node_features(),
2308 short_channel_id: chans[0].short_channel_id.unwrap(),
2309 channel_features: channelmanager::provided_channel_features(),
2310 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2311 cltv_expiry_delta: 100,
2314 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2316 let router = ManualRouter(RefCell::new(VecDeque::new()));
2317 router.expect_find_route(Ok(route.clone()));
2318 // On retry, split the payment across both channels.
2319 route.paths.push(route.paths[0].clone());
2320 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2321 route.paths[0][0].fee_msat = 50_000_000;
2322 route.paths[1][0].fee_msat = 50_000_001;
2323 router.expect_find_route(Ok(route.clone()));
2325 let event_handler = |_: &_| { panic!(); };
2326 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2328 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2329 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2330 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2332 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2333 assert_eq!(htlc_msgs.len(), 2);
2334 check_added_monitors!(nodes[0], 2);
2338 fn no_extra_retries_on_back_to_back_fail() {
2339 // In a previous release, we had a race where we may exceed the payment retry count if we
2340 // get two failures in a row with the second having `all_paths_failed` set.
2341 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2342 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2343 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2344 // pending which we will see later. Thus, when we previously removed the retry tracking map
2345 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2346 // retry entry even though more events for the same payment were still pending. This led to
2347 // us retrying a payment again even though we'd already given up on it.
2349 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2350 // is used to remove the payment retry counter entries instead. This tests for the specific
2351 // excess-retry case while also testing `PaymentFailed` generation.
2353 let chanmon_cfgs = create_chanmon_cfgs(3);
2354 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2355 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2356 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2358 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;
2359 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;
2361 let mut route = Route {
2364 pubkey: nodes[1].node.get_our_node_id(),
2365 node_features: channelmanager::provided_node_features(),
2366 short_channel_id: chan_1_scid,
2367 channel_features: channelmanager::provided_channel_features(),
2369 cltv_expiry_delta: 100,
2371 pubkey: nodes[2].node.get_our_node_id(),
2372 node_features: channelmanager::provided_node_features(),
2373 short_channel_id: chan_2_scid,
2374 channel_features: channelmanager::provided_channel_features(),
2375 fee_msat: 100_000_000,
2376 cltv_expiry_delta: 100,
2379 pubkey: nodes[1].node.get_our_node_id(),
2380 node_features: channelmanager::provided_node_features(),
2381 short_channel_id: chan_1_scid,
2382 channel_features: channelmanager::provided_channel_features(),
2384 cltv_expiry_delta: 100,
2386 pubkey: nodes[2].node.get_our_node_id(),
2387 node_features: channelmanager::provided_node_features(),
2388 short_channel_id: chan_2_scid,
2389 channel_features: channelmanager::provided_channel_features(),
2390 fee_msat: 100_000_000,
2391 cltv_expiry_delta: 100,
2394 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2396 let router = ManualRouter(RefCell::new(VecDeque::new()));
2397 router.expect_find_route(Ok(route.clone()));
2398 // On retry, we'll only be asked for one path
2399 route.paths.remove(1);
2400 router.expect_find_route(Ok(route.clone()));
2402 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2403 let event_handler = |event: &Event| {
2404 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2405 event_checker(event);
2407 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2409 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2410 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2411 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2413 let htlc_updates = SendEvent::from_node(&nodes[0]);
2414 check_added_monitors!(nodes[0], 1);
2415 assert_eq!(htlc_updates.msgs.len(), 1);
2417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2418 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2419 check_added_monitors!(nodes[1], 1);
2420 let (bs_first_raa, bs_first_cs) = get_revoke_commit_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_first_raa);
2423 check_added_monitors!(nodes[0], 1);
2424 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2426 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2427 check_added_monitors!(nodes[0], 1);
2428 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2430 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2431 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2432 check_added_monitors!(nodes[1], 1);
2433 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2435 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2436 check_added_monitors!(nodes[1], 1);
2437 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2439 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2440 check_added_monitors!(nodes[0], 1);
2442 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2443 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2444 check_added_monitors!(nodes[0], 1);
2445 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2447 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2448 check_added_monitors!(nodes[1], 1);
2449 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2451 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2452 check_added_monitors!(nodes[1], 1);
2453 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2455 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2456 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2457 check_added_monitors!(nodes[0], 1);
2459 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2460 check_added_monitors!(nodes[0], 1);
2461 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2464 check_added_monitors!(nodes[1], 1);
2465 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2466 check_added_monitors!(nodes[1], 1);
2467 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2469 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2470 check_added_monitors!(nodes[0], 1);
2472 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2473 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2474 // with it set. The first event will use up the only retry we are allowed, with the second
2475 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2476 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2477 // if the final HTLC failed.
2478 expected_events.borrow_mut().push_back(&|ev: &Event| {
2479 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2480 assert!(!payment_failed_permanently);
2481 assert!(all_paths_failed);
2482 } else { panic!("Unexpected event"); }
2484 nodes[0].node.process_pending_events(&invoice_payer);
2485 assert!(expected_events.borrow().is_empty());
2487 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2488 check_added_monitors!(nodes[0], 1);
2490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2491 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2492 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2493 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2494 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2496 expected_events.borrow_mut().push_back(&|ev: &Event| {
2497 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2498 assert!(!payment_failed_permanently);
2499 assert!(all_paths_failed);
2500 } else { panic!("Unexpected event"); }
2502 expected_events.borrow_mut().push_back(&|ev: &Event| {
2503 if let Event::PaymentFailed { .. } = ev {
2504 } else { panic!("Unexpected event"); }
2506 nodes[0].node.process_pending_events(&invoice_payer);
2507 assert!(expected_events.borrow().is_empty());