1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry};
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!() }
72 //! # fn inflight_htlcs(&self) -> InFlightHtlcs { unimplemented!() }
75 //! # struct FakeRouter {}
76 //! # impl Router for FakeRouter {
78 //! # &self, payer: &PublicKey, params: &RouteParameters,
79 //! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: &InFlightHtlcs
80 //! # ) -> 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::*;
144 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
145 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
146 use lightning::ln::msgs::LightningError;
147 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters, Router};
148 use lightning::util::events::{Event, EventHandler};
149 use lightning::util::logger::Logger;
150 use crate::time_utils::Time;
151 use crate::sync::Mutex;
153 use secp256k1::PublicKey;
156 use core::fmt::{Debug, Display, Formatter};
157 use core::future::Future;
158 use core::ops::Deref;
159 use core::time::Duration;
160 #[cfg(feature = "std")]
161 use std::time::SystemTime;
163 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
165 /// See [module-level documentation] for details.
167 /// [module-level documentation]: crate::payment
168 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
170 #[cfg(not(feature = "no-std"))]
171 type ConfiguredTime = std::time::Instant;
172 #[cfg(feature = "no-std")]
173 use crate::time_utils;
174 #[cfg(feature = "no-std")]
175 type ConfiguredTime = time_utils::Eternity;
177 /// Sealed trait with a blanket implementation to allow both sync and async implementations of event
178 /// handling to exist within the InvoicePayer.
180 pub trait BaseEventHandler {}
181 impl<T> BaseEventHandler for T {}
184 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
185 pub struct InvoicePayerUsingTime<
189 E: sealed::BaseEventHandler,
199 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
200 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
204 /// Storing minimal payment attempts information required for determining if a outbound payment can
206 #[derive(Clone, Copy)]
207 struct PaymentAttempts<T: Time> {
208 /// This count will be incremented only after the result of the attempt is known. When it's 0,
209 /// it means the result of the first attempt is now known yet.
211 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
212 first_attempted_at: T
215 impl<T: Time> PaymentAttempts<T> {
219 first_attempted_at: T::now()
224 impl<T: Time> Display for PaymentAttempts<T> {
225 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
226 #[cfg(feature = "no-std")]
227 return write!( f, "attempts: {}", self.count);
228 #[cfg(not(feature = "no-std"))]
231 "attempts: {}, duration: {}s",
233 T::now().duration_since(self.first_attempted_at).as_secs()
238 /// A trait defining behavior of an [`Invoice`] payer.
240 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
241 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
243 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
245 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
246 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
247 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
248 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
250 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
252 /// Returns the payer's node id.
253 fn node_id(&self) -> PublicKey;
255 /// Returns the payer's channels.
256 fn first_hops(&self) -> Vec<ChannelDetails>;
258 /// Sends a payment over the Lightning Network using the given [`Route`].
260 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
261 payment_id: PaymentId
262 ) -> Result<(), PaymentSendFailure>;
264 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
265 fn send_spontaneous_payment(
266 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
267 ) -> Result<(), PaymentSendFailure>;
269 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
270 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
272 /// Signals that no further retries for the given payment will occur.
273 fn abandon_payment(&self, payment_id: PaymentId);
275 /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
277 fn inflight_htlcs(&self) -> InFlightHtlcs;
280 /// Strategies available to retry payment path failures for an [`Invoice`].
282 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
284 /// Max number of attempts to retry payment.
286 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
287 /// payments, if this is less than the total number of paths, we will never even retry all of the
290 #[cfg(feature = "std")]
291 /// Time elapsed before abandoning retries for a payment.
296 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
297 match (self, attempts) {
298 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
299 max_retry_count >= &count
301 #[cfg(feature = "std")]
302 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
303 *max_duration >= T::now().duration_since(*first_attempted_at),
308 /// An error that may occur when making a payment.
309 #[derive(Clone, Debug)]
310 pub enum PaymentError {
311 /// An error resulting from the provided [`Invoice`] or payment hash.
312 Invoice(&'static str),
313 /// An error occurring when finding a route.
314 Routing(LightningError),
315 /// An error occurring when sending a payment.
316 Sending(PaymentSendFailure),
319 impl<P: Deref, R: Router, L: Deref, E: sealed::BaseEventHandler, T: Time>
320 InvoicePayerUsingTime<P, R, L, E, T>
325 /// Creates an invoice payer that retries failed payment paths.
327 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
328 /// `retry` has been exceeded for a given [`Invoice`].
330 payer: P, router: R, logger: L, event_handler: E, retry: Retry
337 payment_cache: Mutex::new(HashMap::new()),
342 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
344 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
345 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
346 /// a second payment with the same [`PaymentHash`] is never sent.
348 /// If you wish to use a different payment idempotency token, see
349 /// [`Self::pay_invoice_with_id`].
350 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
351 let payment_id = PaymentId(invoice.payment_hash().into_inner());
352 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
355 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
356 /// in case a retry is needed.
358 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
359 /// payment completes or fails, no idempotency guarantees are made.
361 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
362 /// has never been paid before.
364 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
366 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
367 if invoice.amount_milli_satoshis().is_none() {
368 Err(PaymentError::Invoice("amount missing"))
370 self.pay_invoice_using_amount(invoice, None, payment_id)
374 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
375 /// case a retry is needed.
377 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
378 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
379 /// a second payment with the same [`PaymentHash`] is never sent.
381 /// If you wish to use a different payment idempotency token, see
382 /// [`Self::pay_zero_value_invoice_with_id`].
383 pub fn pay_zero_value_invoice(
384 &self, invoice: &Invoice, amount_msats: u64
385 ) -> Result<PaymentId, PaymentError> {
386 let payment_id = PaymentId(invoice.payment_hash().into_inner());
387 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
390 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
391 /// caching the invoice for later use in case a retry is needed.
393 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
394 /// payment completes or fails, no idempotency guarantees are made.
396 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
397 /// has never been paid before.
399 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
400 /// idempotency token.
401 pub fn pay_zero_value_invoice_with_id(
402 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
403 ) -> Result<(), PaymentError> {
404 if invoice.amount_milli_satoshis().is_some() {
405 Err(PaymentError::Invoice("amount unexpected"))
407 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
411 fn pay_invoice_using_amount(
412 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
413 ) -> Result<(), PaymentError> {
414 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
416 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
417 match self.payment_cache.lock().unwrap().entry(payment_hash) {
418 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
419 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
422 let payment_secret = Some(invoice.payment_secret().clone());
423 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
424 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
425 .with_route_hints(invoice.route_hints());
426 if let Some(features) = invoice.features() {
427 payment_params = payment_params.with_features(features.clone());
429 let route_params = RouteParameters {
431 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
432 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
435 let send_payment = |route: &Route| {
436 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
439 self.pay_internal(&route_params, payment_hash, send_payment)
440 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
443 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
444 /// case a retry is needed.
446 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
447 /// as long as the payment is still pending. Once the payment completes or fails, you must
448 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
450 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
451 final_cltv_expiry_delta: u32
452 ) -> Result<PaymentId, PaymentError> {
453 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
454 let payment_id = PaymentId(payment_hash.0);
455 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
456 final_cltv_expiry_delta)
457 .map(|()| payment_id)
460 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
461 /// caching the invoice for later use in case a retry is needed.
463 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
464 /// payment completes or fails, no idempotency guarantees are made.
466 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
467 /// [`PaymentHash`] has never been paid before.
468 pub fn pay_pubkey_with_id(
469 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
470 amount_msats: u64, final_cltv_expiry_delta: u32
471 ) -> Result<(), PaymentError> {
472 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
473 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
474 final_cltv_expiry_delta)
478 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
479 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
480 ) -> Result<(), PaymentError> {
481 match self.payment_cache.lock().unwrap().entry(payment_hash) {
482 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
483 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
486 let route_params = RouteParameters {
487 payment_params: PaymentParameters::for_keysend(pubkey),
488 final_value_msat: amount_msats,
489 final_cltv_expiry_delta,
492 let send_payment = |route: &Route| {
493 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
495 self.pay_internal(&route_params, payment_hash, send_payment)
496 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
499 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
500 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
501 ) -> Result<(), PaymentError> {
502 #[cfg(feature = "std")] {
503 if has_expired(params) {
504 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
505 return Err(PaymentError::Invoice("Invoice expired prior to send"));
509 let payer = self.payer.node_id();
510 let first_hops = self.payer.first_hops();
511 let inflight_htlcs = self.payer.inflight_htlcs();
512 let route = self.router.find_route(
513 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
514 ).map_err(|e| PaymentError::Routing(e))?;
516 match send_payment(&route) {
519 PaymentSendFailure::ParameterError(_) => Err(e),
520 PaymentSendFailure::PathParameterError(_) => Err(e),
521 PaymentSendFailure::DuplicatePayment => Err(e),
522 PaymentSendFailure::AllFailedResendSafe(_) => {
523 let mut payment_cache = self.payment_cache.lock().unwrap();
524 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
525 payment_attempts.count += 1;
526 if self.retry.is_retryable_now(payment_attempts) {
527 core::mem::drop(payment_cache);
528 Ok(self.pay_internal(params, payment_hash, send_payment)?)
533 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
534 if let Some(retry_data) = failed_paths_retry {
535 // Some paths were sent, even if we failed to send the full MPP value our
536 // recipient may misbehave and claim the funds, at which point we have to
537 // consider the payment sent, so return `Ok()` here, ignoring any retry
539 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
542 // This may happen if we send a payment and some paths fail, but
543 // only due to a temporary monitor failure or the like, implying
544 // they're really in-flight, but we haven't sent the initial
545 // HTLC-Add messages yet.
550 }.map_err(|e| PaymentError::Sending(e))
554 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
555 ) -> Result<(), ()> {
557 *self.payment_cache.lock().unwrap().entry(payment_hash)
558 .and_modify(|attempts| attempts.count += 1)
559 .or_insert(PaymentAttempts {
561 first_attempted_at: T::now()
564 if !self.retry.is_retryable_now(&attempts) {
565 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
569 #[cfg(feature = "std")] {
570 if has_expired(params) {
571 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
576 let payer = self.payer.node_id();
577 let first_hops = self.payer.first_hops();
578 let inflight_htlcs = self.payer.inflight_htlcs();
580 let route = self.router.find_route(
581 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
585 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
589 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
591 Err(PaymentSendFailure::ParameterError(_)) |
592 Err(PaymentSendFailure::PathParameterError(_)) => {
593 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
596 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
597 self.retry_payment(payment_id, payment_hash, params)
599 Err(PaymentSendFailure::DuplicatePayment) => {
600 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
603 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
604 if let Some(retry) = failed_paths_retry {
605 // Always return Ok for the same reason as noted in pay_internal.
606 let _ = self.retry_payment(payment_id, payment_hash, &retry);
613 /// Removes the payment cached by the given payment hash.
615 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
616 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
617 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
618 self.payment_cache.lock().unwrap().remove(payment_hash);
622 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
623 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
626 #[cfg(feature = "std")]
627 fn has_expired(route_params: &RouteParameters) -> bool {
628 if let Some(expiry_time) = route_params.payment_params.expiry_time {
629 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
633 impl<P: Deref, R: Router, L: Deref, E: sealed::BaseEventHandler, T: Time>
634 InvoicePayerUsingTime<P, R, L, E, T>
639 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
641 fn handle_event_internal(&self, event: &Event) -> bool {
643 Event::PaymentPathFailed {
644 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
646 if let Some(short_channel_id) = short_channel_id {
647 let path = path.iter().collect::<Vec<_>>();
648 self.router.notify_payment_path_failed(&path, *short_channel_id)
651 if payment_id.is_none() {
652 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
653 } else if *payment_failed_permanently {
654 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
655 self.payer.abandon_payment(payment_id.unwrap());
656 } else if retry.is_none() {
657 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
658 self.payer.abandon_payment(payment_id.unwrap());
659 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
660 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
663 self.payer.abandon_payment(payment_id.unwrap());
666 Event::PaymentFailed { payment_hash, .. } => {
667 self.remove_cached_payment(&payment_hash);
669 Event::PaymentPathSuccessful { path, .. } => {
670 let path = path.iter().collect::<Vec<_>>();
671 self.router.notify_payment_path_successful(&path);
673 Event::PaymentSent { payment_hash, .. } => {
674 let mut payment_cache = self.payment_cache.lock().unwrap();
675 let attempts = payment_cache
676 .remove(payment_hash)
677 .map_or(1, |attempts| attempts.count + 1);
678 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
680 Event::ProbeSuccessful { payment_hash, path, .. } => {
681 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
682 let path = path.iter().collect::<Vec<_>>();
683 self.router.notify_payment_probe_successful(&path);
685 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
686 if let Some(short_channel_id) = short_channel_id {
687 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
688 let path = path.iter().collect::<Vec<_>>();
689 self.router.notify_payment_probe_failed(&path, *short_channel_id);
695 // Delegate to the decorated event handler unless the payment is retried.
700 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time>
701 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
706 fn handle_event(&self, event: Event) {
707 let should_forward = self.handle_event_internal(&event);
709 self.event_handler.handle_event(event)
714 impl<P: Deref, R: Router, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
715 InvoicePayerUsingTime<P, R, L, H, T>
720 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
721 /// handler, if necessary, to handle them asynchronously.
722 pub async fn handle_event_async(&self, event: Event) {
723 let should_forward = self.handle_event_internal(&event);
725 (self.event_handler)(event).await;
733 use crate::{InvoiceBuilder, Currency};
734 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
735 use bitcoin_hashes::sha256::Hash as Sha256;
736 use lightning::ln::PaymentPreimage;
737 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
738 use lightning::ln::functional_test_utils::*;
739 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
740 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
741 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router, ScorerAccountingForInFlightHtlcs};
742 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
743 use lightning::util::test_utils::TestLogger;
744 use lightning::util::errors::APIError;
745 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
746 use secp256k1::{SecretKey, PublicKey, Secp256k1};
747 use std::cell::RefCell;
748 use std::collections::VecDeque;
749 use std::ops::DerefMut;
750 use std::time::{SystemTime, Duration};
751 use crate::time_utils::tests::SinceEpoch;
752 use crate::DEFAULT_EXPIRY_TIME;
754 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
755 let payment_hash = Sha256::hash(&payment_preimage.0);
756 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
758 InvoiceBuilder::new(Currency::Bitcoin)
759 .description("test".into())
760 .payment_hash(payment_hash)
761 .payment_secret(PaymentSecret([0; 32]))
762 .duration_since_epoch(duration_since_epoch())
763 .min_final_cltv_expiry(144)
764 .amount_milli_satoshis(128)
765 .build_signed(|hash| {
766 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
771 fn duration_since_epoch() -> Duration {
772 #[cfg(feature = "std")]
773 let duration_since_epoch =
774 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
775 #[cfg(not(feature = "std"))]
776 let duration_since_epoch = Duration::from_secs(1234567);
780 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
781 let payment_hash = Sha256::hash(&payment_preimage.0);
782 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
784 InvoiceBuilder::new(Currency::Bitcoin)
785 .description("test".into())
786 .payment_hash(payment_hash)
787 .payment_secret(PaymentSecret([0; 32]))
788 .duration_since_epoch(duration_since_epoch())
789 .min_final_cltv_expiry(144)
790 .build_signed(|hash| {
791 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
796 #[cfg(feature = "std")]
797 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
798 let payment_hash = Sha256::hash(&payment_preimage.0);
799 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
800 let duration = duration_since_epoch()
801 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
803 InvoiceBuilder::new(Currency::Bitcoin)
804 .description("test".into())
805 .payment_hash(payment_hash)
806 .payment_secret(PaymentSecret([0; 32]))
807 .duration_since_epoch(duration)
808 .min_final_cltv_expiry(144)
809 .amount_milli_satoshis(128)
810 .build_signed(|hash| {
811 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
816 fn pubkey() -> PublicKey {
817 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
821 fn pays_invoice_on_first_attempt() {
822 let event_handled = core::cell::RefCell::new(false);
823 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
825 let payment_preimage = PaymentPreimage([1; 32]);
826 let invoice = invoice(payment_preimage);
827 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
828 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
830 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
831 let router = TestRouter::new(TestScorer::new());
832 let logger = TestLogger::new();
834 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
836 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
837 assert_eq!(*payer.attempts.borrow(), 1);
839 invoice_payer.handle_event(Event::PaymentSent {
840 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
842 assert_eq!(*event_handled.borrow(), true);
843 assert_eq!(*payer.attempts.borrow(), 1);
847 fn pays_invoice_on_retry() {
848 let event_handled = core::cell::RefCell::new(false);
849 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
851 let payment_preimage = PaymentPreimage([1; 32]);
852 let invoice = invoice(payment_preimage);
853 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
854 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
856 let payer = TestPayer::new()
857 .expect_send(Amount::ForInvoice(final_value_msat))
858 .expect_send(Amount::OnRetry(final_value_msat / 2));
859 let router = TestRouter::new(TestScorer::new());
860 let logger = TestLogger::new();
862 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
864 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
865 assert_eq!(*payer.attempts.borrow(), 1);
867 let event = Event::PaymentPathFailed {
870 network_update: None,
871 payment_failed_permanently: false,
872 all_paths_failed: false,
873 path: TestRouter::path_for_value(final_value_msat),
874 short_channel_id: None,
875 retry: Some(TestRouter::retry_for_invoice(&invoice)),
877 invoice_payer.handle_event(event);
878 assert_eq!(*event_handled.borrow(), false);
879 assert_eq!(*payer.attempts.borrow(), 2);
881 invoice_payer.handle_event(Event::PaymentSent {
882 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
884 assert_eq!(*event_handled.borrow(), true);
885 assert_eq!(*payer.attempts.borrow(), 2);
889 fn pays_invoice_on_partial_failure() {
890 let event_handler = |_: Event| { panic!() };
892 let payment_preimage = PaymentPreimage([1; 32]);
893 let invoice = invoice(payment_preimage);
894 let retry = TestRouter::retry_for_invoice(&invoice);
895 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
897 let payer = TestPayer::new()
898 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
899 .fails_with_partial_failure(retry, OnAttempt(2), None)
900 .expect_send(Amount::ForInvoice(final_value_msat))
901 .expect_send(Amount::OnRetry(final_value_msat / 2))
902 .expect_send(Amount::OnRetry(final_value_msat / 2));
903 let router = TestRouter::new(TestScorer::new());
904 let logger = TestLogger::new();
906 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
908 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
912 fn retries_payment_path_for_unknown_payment() {
913 let event_handled = core::cell::RefCell::new(false);
914 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
916 let payment_preimage = PaymentPreimage([1; 32]);
917 let invoice = invoice(payment_preimage);
918 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
919 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
921 let payer = TestPayer::new()
922 .expect_send(Amount::OnRetry(final_value_msat / 2))
923 .expect_send(Amount::OnRetry(final_value_msat / 2));
924 let router = TestRouter::new(TestScorer::new());
925 let logger = TestLogger::new();
927 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
929 let payment_id = Some(PaymentId([1; 32]));
930 let event = Event::PaymentPathFailed {
933 network_update: None,
934 payment_failed_permanently: false,
935 all_paths_failed: false,
936 path: TestRouter::path_for_value(final_value_msat),
937 short_channel_id: None,
938 retry: Some(TestRouter::retry_for_invoice(&invoice)),
940 invoice_payer.handle_event(event.clone());
941 assert_eq!(*event_handled.borrow(), false);
942 assert_eq!(*payer.attempts.borrow(), 1);
944 invoice_payer.handle_event(event.clone());
945 assert_eq!(*event_handled.borrow(), false);
946 assert_eq!(*payer.attempts.borrow(), 2);
948 invoice_payer.handle_event(Event::PaymentSent {
949 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
951 assert_eq!(*event_handled.borrow(), true);
952 assert_eq!(*payer.attempts.borrow(), 2);
956 fn fails_paying_invoice_after_max_retry_counts() {
957 let event_handled = core::cell::RefCell::new(false);
958 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
960 let payment_preimage = PaymentPreimage([1; 32]);
961 let invoice = invoice(payment_preimage);
962 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
964 let payer = TestPayer::new()
965 .expect_send(Amount::ForInvoice(final_value_msat))
966 .expect_send(Amount::OnRetry(final_value_msat / 2))
967 .expect_send(Amount::OnRetry(final_value_msat / 2));
968 let router = TestRouter::new(TestScorer::new());
969 let logger = TestLogger::new();
971 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
973 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
974 assert_eq!(*payer.attempts.borrow(), 1);
976 let event = Event::PaymentPathFailed {
978 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
979 network_update: None,
980 payment_failed_permanently: false,
981 all_paths_failed: true,
982 path: TestRouter::path_for_value(final_value_msat),
983 short_channel_id: None,
984 retry: Some(TestRouter::retry_for_invoice(&invoice)),
986 invoice_payer.handle_event(event);
987 assert_eq!(*event_handled.borrow(), false);
988 assert_eq!(*payer.attempts.borrow(), 2);
990 let event = Event::PaymentPathFailed {
992 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
993 network_update: None,
994 payment_failed_permanently: false,
995 all_paths_failed: false,
996 path: TestRouter::path_for_value(final_value_msat / 2),
997 short_channel_id: None,
998 retry: Some(RouteParameters {
999 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1002 invoice_payer.handle_event(event.clone());
1003 assert_eq!(*event_handled.borrow(), false);
1004 assert_eq!(*payer.attempts.borrow(), 3);
1006 invoice_payer.handle_event(event.clone());
1007 assert_eq!(*event_handled.borrow(), true);
1008 assert_eq!(*payer.attempts.borrow(), 3);
1011 #[cfg(feature = "std")]
1013 fn fails_paying_invoice_after_max_retry_timeout() {
1014 let event_handled = core::cell::RefCell::new(false);
1015 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1017 let payment_preimage = PaymentPreimage([1; 32]);
1018 let invoice = invoice(payment_preimage);
1019 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1021 let payer = TestPayer::new()
1022 .expect_send(Amount::ForInvoice(final_value_msat))
1023 .expect_send(Amount::OnRetry(final_value_msat / 2));
1025 let router = TestRouter::new(TestScorer::new());
1026 let logger = TestLogger::new();
1027 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1030 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1032 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1033 assert_eq!(*payer.attempts.borrow(), 1);
1035 let event = Event::PaymentPathFailed {
1037 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1038 network_update: None,
1039 payment_failed_permanently: false,
1040 all_paths_failed: true,
1041 path: TestRouter::path_for_value(final_value_msat),
1042 short_channel_id: None,
1043 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1045 invoice_payer.handle_event(event.clone());
1046 assert_eq!(*event_handled.borrow(), false);
1047 assert_eq!(*payer.attempts.borrow(), 2);
1049 SinceEpoch::advance(Duration::from_secs(121));
1051 invoice_payer.handle_event(event.clone());
1052 assert_eq!(*event_handled.borrow(), true);
1053 assert_eq!(*payer.attempts.borrow(), 2);
1057 fn fails_paying_invoice_with_missing_retry_params() {
1058 let event_handled = core::cell::RefCell::new(false);
1059 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1061 let payment_preimage = PaymentPreimage([1; 32]);
1062 let invoice = invoice(payment_preimage);
1063 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1065 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1066 let router = TestRouter::new(TestScorer::new());
1067 let logger = TestLogger::new();
1069 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1071 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1072 assert_eq!(*payer.attempts.borrow(), 1);
1074 let event = Event::PaymentPathFailed {
1076 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1077 network_update: None,
1078 payment_failed_permanently: false,
1079 all_paths_failed: false,
1081 short_channel_id: None,
1084 invoice_payer.handle_event(event);
1085 assert_eq!(*event_handled.borrow(), true);
1086 assert_eq!(*payer.attempts.borrow(), 1);
1089 // Expiration is checked only in an std environment
1090 #[cfg(feature = "std")]
1092 fn fails_paying_invoice_after_expiration() {
1093 let event_handled = core::cell::RefCell::new(false);
1094 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1096 let payer = TestPayer::new();
1097 let router = TestRouter::new(TestScorer::new());
1098 let logger = TestLogger::new();
1100 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1102 let payment_preimage = PaymentPreimage([1; 32]);
1103 let invoice = expired_invoice(payment_preimage);
1104 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1105 assert_eq!(msg, "Invoice expired prior to send");
1106 } else { panic!("Expected Invoice Error"); }
1109 // Expiration is checked only in an std environment
1110 #[cfg(feature = "std")]
1112 fn fails_retrying_invoice_after_expiration() {
1113 let event_handled = core::cell::RefCell::new(false);
1114 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1116 let payment_preimage = PaymentPreimage([1; 32]);
1117 let invoice = invoice(payment_preimage);
1118 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1120 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1121 let router = TestRouter::new(TestScorer::new());
1122 let logger = TestLogger::new();
1124 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1126 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1127 assert_eq!(*payer.attempts.borrow(), 1);
1129 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1130 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1131 .checked_sub(Duration::from_secs(2)).unwrap()
1132 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1133 let event = Event::PaymentPathFailed {
1135 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1136 network_update: None,
1137 payment_failed_permanently: false,
1138 all_paths_failed: false,
1140 short_channel_id: None,
1141 retry: Some(retry_data),
1143 invoice_payer.handle_event(event);
1144 assert_eq!(*event_handled.borrow(), true);
1145 assert_eq!(*payer.attempts.borrow(), 1);
1149 fn fails_paying_invoice_after_retry_error() {
1150 let event_handled = core::cell::RefCell::new(false);
1151 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1153 let payment_preimage = PaymentPreimage([1; 32]);
1154 let invoice = invoice(payment_preimage);
1155 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1157 let payer = TestPayer::new()
1158 .fails_on_attempt(2)
1159 .expect_send(Amount::ForInvoice(final_value_msat))
1160 .expect_send(Amount::OnRetry(final_value_msat / 2));
1161 let router = TestRouter::new(TestScorer::new());
1162 let logger = TestLogger::new();
1164 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1166 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1167 assert_eq!(*payer.attempts.borrow(), 1);
1169 let event = Event::PaymentPathFailed {
1171 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1172 network_update: None,
1173 payment_failed_permanently: false,
1174 all_paths_failed: false,
1175 path: TestRouter::path_for_value(final_value_msat / 2),
1176 short_channel_id: None,
1177 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1179 invoice_payer.handle_event(event);
1180 assert_eq!(*event_handled.borrow(), true);
1181 assert_eq!(*payer.attempts.borrow(), 2);
1185 fn fails_paying_invoice_after_rejected_by_payee() {
1186 let event_handled = core::cell::RefCell::new(false);
1187 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1189 let payment_preimage = PaymentPreimage([1; 32]);
1190 let invoice = invoice(payment_preimage);
1191 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1193 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1194 let router = TestRouter::new(TestScorer::new());
1195 let logger = TestLogger::new();
1197 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1199 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1200 assert_eq!(*payer.attempts.borrow(), 1);
1202 let event = Event::PaymentPathFailed {
1204 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1205 network_update: None,
1206 payment_failed_permanently: true,
1207 all_paths_failed: false,
1209 short_channel_id: None,
1210 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1212 invoice_payer.handle_event(event);
1213 assert_eq!(*event_handled.borrow(), true);
1214 assert_eq!(*payer.attempts.borrow(), 1);
1218 fn fails_repaying_invoice_with_pending_payment() {
1219 let event_handled = core::cell::RefCell::new(false);
1220 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1222 let payment_preimage = PaymentPreimage([1; 32]);
1223 let invoice = invoice(payment_preimage);
1224 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1226 let payer = TestPayer::new()
1227 .expect_send(Amount::ForInvoice(final_value_msat))
1228 .expect_send(Amount::ForInvoice(final_value_msat));
1229 let router = TestRouter::new(TestScorer::new());
1230 let logger = TestLogger::new();
1232 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1234 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1236 // Cannot repay an invoice pending payment.
1237 match invoice_payer.pay_invoice(&invoice) {
1238 Err(PaymentError::Invoice("payment pending")) => {},
1239 Err(_) => panic!("unexpected error"),
1240 Ok(_) => panic!("expected invoice error"),
1243 // Can repay an invoice once cleared from cache.
1244 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1245 invoice_payer.remove_cached_payment(&payment_hash);
1246 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1248 // Cannot retry paying an invoice if cleared from cache.
1249 invoice_payer.remove_cached_payment(&payment_hash);
1250 let event = Event::PaymentPathFailed {
1253 network_update: None,
1254 payment_failed_permanently: false,
1255 all_paths_failed: false,
1257 short_channel_id: None,
1258 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1260 invoice_payer.handle_event(event);
1261 assert_eq!(*event_handled.borrow(), true);
1265 fn fails_paying_invoice_with_routing_errors() {
1266 let payer = TestPayer::new();
1267 let router = FailingRouter {};
1268 let logger = TestLogger::new();
1270 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1272 let payment_preimage = PaymentPreimage([1; 32]);
1273 let invoice = invoice(payment_preimage);
1274 match invoice_payer.pay_invoice(&invoice) {
1275 Err(PaymentError::Routing(_)) => {},
1276 Err(_) => panic!("unexpected error"),
1277 Ok(_) => panic!("expected routing error"),
1282 fn fails_paying_invoice_with_sending_errors() {
1283 let payment_preimage = PaymentPreimage([1; 32]);
1284 let invoice = invoice(payment_preimage);
1285 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1287 let payer = TestPayer::new()
1288 .fails_on_attempt(1)
1289 .expect_send(Amount::ForInvoice(final_value_msat));
1290 let router = TestRouter::new(TestScorer::new());
1291 let logger = TestLogger::new();
1293 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1295 match invoice_payer.pay_invoice(&invoice) {
1296 Err(PaymentError::Sending(_)) => {},
1297 Err(_) => panic!("unexpected error"),
1298 Ok(_) => panic!("expected sending error"),
1303 fn pays_zero_value_invoice_using_amount() {
1304 let event_handled = core::cell::RefCell::new(false);
1305 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1307 let payment_preimage = PaymentPreimage([1; 32]);
1308 let invoice = zero_value_invoice(payment_preimage);
1309 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1310 let final_value_msat = 100;
1312 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1313 let router = TestRouter::new(TestScorer::new());
1314 let logger = TestLogger::new();
1316 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1319 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1320 assert_eq!(*payer.attempts.borrow(), 1);
1322 invoice_payer.handle_event(Event::PaymentSent {
1323 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1325 assert_eq!(*event_handled.borrow(), true);
1326 assert_eq!(*payer.attempts.borrow(), 1);
1330 fn fails_paying_zero_value_invoice_with_amount() {
1331 let event_handled = core::cell::RefCell::new(false);
1332 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1334 let payer = TestPayer::new();
1335 let router = TestRouter::new(TestScorer::new());
1336 let logger = TestLogger::new();
1338 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1340 let payment_preimage = PaymentPreimage([1; 32]);
1341 let invoice = invoice(payment_preimage);
1343 // Cannot repay an invoice pending payment.
1344 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1345 Err(PaymentError::Invoice("amount unexpected")) => {},
1346 Err(_) => panic!("unexpected error"),
1347 Ok(_) => panic!("expected invoice error"),
1352 fn pays_pubkey_with_amount() {
1353 let event_handled = core::cell::RefCell::new(false);
1354 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1356 let pubkey = pubkey();
1357 let payment_preimage = PaymentPreimage([1; 32]);
1358 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1359 let final_value_msat = 100;
1360 let final_cltv_expiry_delta = 42;
1362 let payer = TestPayer::new()
1363 .expect_send(Amount::Spontaneous(final_value_msat))
1364 .expect_send(Amount::OnRetry(final_value_msat));
1365 let router = TestRouter::new(TestScorer::new());
1366 let logger = TestLogger::new();
1368 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1370 let payment_id = Some(invoice_payer.pay_pubkey(
1371 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1373 assert_eq!(*payer.attempts.borrow(), 1);
1375 let retry = RouteParameters {
1376 payment_params: PaymentParameters::for_keysend(pubkey),
1378 final_cltv_expiry_delta,
1380 let event = Event::PaymentPathFailed {
1383 network_update: None,
1384 payment_failed_permanently: false,
1385 all_paths_failed: false,
1387 short_channel_id: None,
1390 invoice_payer.handle_event(event);
1391 assert_eq!(*event_handled.borrow(), false);
1392 assert_eq!(*payer.attempts.borrow(), 2);
1394 invoice_payer.handle_event(Event::PaymentSent {
1395 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1397 assert_eq!(*event_handled.borrow(), true);
1398 assert_eq!(*payer.attempts.borrow(), 2);
1402 fn scores_failed_channel() {
1403 let event_handled = core::cell::RefCell::new(false);
1404 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1406 let payment_preimage = PaymentPreimage([1; 32]);
1407 let invoice = invoice(payment_preimage);
1408 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1409 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1410 let path = TestRouter::path_for_value(final_value_msat);
1411 let short_channel_id = Some(path[0].short_channel_id);
1413 // Expect that scorer is given short_channel_id upon handling the event.
1414 let payer = TestPayer::new()
1415 .expect_send(Amount::ForInvoice(final_value_msat))
1416 .expect_send(Amount::OnRetry(final_value_msat / 2));
1417 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1418 path: path.clone(), short_channel_id: path[0].short_channel_id,
1420 let router = TestRouter::new(scorer);
1421 let logger = TestLogger::new();
1423 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1425 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1426 let event = Event::PaymentPathFailed {
1429 network_update: None,
1430 payment_failed_permanently: false,
1431 all_paths_failed: false,
1434 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1436 invoice_payer.handle_event(event);
1440 fn scores_successful_channels() {
1441 let event_handled = core::cell::RefCell::new(false);
1442 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1444 let payment_preimage = PaymentPreimage([1; 32]);
1445 let invoice = invoice(payment_preimage);
1446 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1447 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1448 let route = TestRouter::route_for_value(final_value_msat);
1450 // Expect that scorer is given short_channel_id upon handling the event.
1451 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1452 let scorer = TestScorer::new()
1453 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1454 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1455 let router = TestRouter::new(scorer);
1456 let logger = TestLogger::new();
1458 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1460 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1461 let event = Event::PaymentPathSuccessful {
1462 payment_id, payment_hash, path: route.paths[0].clone()
1464 invoice_payer.handle_event(event);
1465 let event = Event::PaymentPathSuccessful {
1466 payment_id, payment_hash, path: route.paths[1].clone()
1468 invoice_payer.handle_event(event);
1472 fn considers_inflight_htlcs_between_invoice_payments() {
1473 let event_handled = core::cell::RefCell::new(false);
1474 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1476 let payment_preimage = PaymentPreimage([1; 32]);
1477 let payment_invoice = invoice(payment_preimage);
1478 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1480 let payer = TestPayer::new()
1481 .expect_send(Amount::ForInvoice(final_value_msat))
1482 .expect_send(Amount::ForInvoice(final_value_msat));
1483 let scorer = TestScorer::new()
1484 // 1st invoice, 1st path
1485 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1486 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1487 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1488 // 1st invoice, 2nd path
1489 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1490 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1491 // 2nd invoice, 1st path
1492 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1493 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1494 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1495 // 2nd invoice, 2nd path
1496 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1497 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1498 let router = TestRouter::new(scorer);
1499 let logger = TestLogger::new();
1501 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1503 // Make first invoice payment.
1504 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1506 // Let's pay a second invoice that will be using the same path. This should trigger the
1507 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1509 let payment_preimage_2 = PaymentPreimage([2; 32]);
1510 let payment_invoice_2 = invoice(payment_preimage_2);
1511 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1515 fn considers_inflight_htlcs_between_retries() {
1516 // First, let's just send a payment through, but only make sure one of the path completes
1517 let event_handled = core::cell::RefCell::new(false);
1518 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1520 let payment_preimage = PaymentPreimage([1; 32]);
1521 let payment_invoice = invoice(payment_preimage);
1522 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1523 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1525 let payer = TestPayer::new()
1526 .expect_send(Amount::ForInvoice(final_value_msat))
1527 .expect_send(Amount::OnRetry(final_value_msat / 2))
1528 .expect_send(Amount::OnRetry(final_value_msat / 4));
1529 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1530 let scorer = TestScorer::new()
1531 // 1st invoice, 1st path
1532 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1533 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1534 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1535 // 1st invoice, 2nd path
1536 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1537 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1538 // Retry 1, 1st path
1539 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1540 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1541 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1542 // Retry 1, 2nd path
1543 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1544 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1545 // Retry 2, 1st path
1546 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1547 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1548 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1549 // Retry 2, 2nd path
1550 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1551 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1552 let router = TestRouter::new(scorer);
1553 let logger = TestLogger::new();
1555 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1557 // Fail 1st path, leave 2nd path inflight
1558 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1559 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1560 invoice_payer.handle_event(Event::PaymentPathFailed {
1563 network_update: None,
1564 payment_failed_permanently: false,
1565 all_paths_failed: false,
1566 path: TestRouter::path_for_value(final_value_msat),
1567 short_channel_id: None,
1568 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1571 // Fails again the 1st path of our retry
1572 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1573 invoice_payer.handle_event(Event::PaymentPathFailed {
1576 network_update: None,
1577 payment_failed_permanently: false,
1578 all_paths_failed: false,
1579 path: TestRouter::path_for_value(final_value_msat / 2),
1580 short_channel_id: None,
1581 retry: Some(RouteParameters {
1582 final_value_msat: final_value_msat / 4,
1583 ..TestRouter::retry_for_invoice(&payment_invoice)
1589 scorer: RefCell<TestScorer>,
1593 fn new(scorer: TestScorer) -> Self {
1594 TestRouter { scorer: RefCell::new(scorer) }
1597 fn route_for_value(final_value_msat: u64) -> Route {
1602 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1603 channel_features: ChannelFeatures::empty(),
1604 node_features: NodeFeatures::empty(),
1605 short_channel_id: 0,
1607 cltv_expiry_delta: 0
1610 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1611 channel_features: ChannelFeatures::empty(),
1612 node_features: NodeFeatures::empty(),
1613 short_channel_id: 1,
1615 cltv_expiry_delta: 0
1618 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1619 channel_features: ChannelFeatures::empty(),
1620 node_features: NodeFeatures::empty(),
1621 short_channel_id: 2,
1622 fee_msat: final_value_msat / 2,
1623 cltv_expiry_delta: 0
1628 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1629 channel_features: ChannelFeatures::empty(),
1630 node_features: NodeFeatures::empty(),
1631 short_channel_id: 3,
1633 cltv_expiry_delta: 144
1636 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1637 channel_features: ChannelFeatures::empty(),
1638 node_features: NodeFeatures::empty(),
1639 short_channel_id: 4,
1640 fee_msat: final_value_msat / 2,
1641 cltv_expiry_delta: 144
1645 payment_params: None,
1649 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1650 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1653 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1654 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1655 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1656 .with_route_hints(invoice.route_hints());
1657 if let Some(features) = invoice.features() {
1658 payment_params = payment_params.with_features(features.clone());
1660 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1664 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1669 impl Router for TestRouter {
1671 &self, payer: &PublicKey, route_params: &RouteParameters,
1672 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
1673 ) -> Result<Route, LightningError> {
1674 // Simulate calling the Scorer just as you would in find_route
1675 let route = Self::route_for_value(route_params.final_value_msat);
1676 let locked_scorer = self.scorer.lock();
1677 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer, inflight_htlcs);
1678 for path in route.paths {
1679 let mut aggregate_msat = 0u64;
1680 for (idx, hop) in path.iter().rev().enumerate() {
1681 aggregate_msat += hop.fee_msat;
1682 let usage = ChannelUsage {
1683 amount_msat: aggregate_msat,
1684 inflight_htlc_msat: 0,
1685 effective_capacity: EffectiveCapacity::Unknown,
1688 // Since the path is reversed, the last element in our iteration is the first
1690 if idx == path.len() - 1 {
1691 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1693 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1699 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1703 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1704 self.scorer.lock().payment_path_failed(path, short_channel_id);
1707 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1708 self.scorer.lock().payment_path_successful(path);
1711 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1712 self.scorer.lock().probe_successful(path);
1715 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1716 self.scorer.lock().probe_failed(path, short_channel_id);
1720 struct FailingRouter;
1722 impl Router for FailingRouter {
1724 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1725 _inflight_htlcs: &InFlightHtlcs,
1726 ) -> Result<Route, LightningError> {
1727 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1730 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1732 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1734 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1736 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1740 event_expectations: Option<VecDeque<TestResult>>,
1741 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1746 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1747 PaymentSuccess { path: Vec<RouteHop> },
1753 event_expectations: None,
1754 scorer_expectations: RefCell::new(None),
1758 fn expect(mut self, expectation: TestResult) -> Self {
1759 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1763 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1764 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1770 impl lightning::util::ser::Writeable for TestScorer {
1771 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1774 impl Score for TestScorer {
1775 fn channel_penalty_msat(
1776 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1778 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1779 match scorer_expectations.pop_front() {
1780 Some(expectation) => {
1781 assert_eq!(expectation.amount_msat, usage.amount_msat);
1782 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1790 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1791 if let Some(expectations) = &mut self.event_expectations {
1792 match expectations.pop_front() {
1793 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1794 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1795 assert_eq!(actual_short_channel_id, short_channel_id);
1797 Some(TestResult::PaymentSuccess { path }) => {
1798 panic!("Unexpected successful payment path: {:?}", path)
1800 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1805 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1806 if let Some(expectations) = &mut self.event_expectations {
1807 match expectations.pop_front() {
1808 Some(TestResult::PaymentFailure { path, .. }) => {
1809 panic!("Unexpected payment path failure: {:?}", path)
1811 Some(TestResult::PaymentSuccess { path }) => {
1812 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1814 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1819 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1820 if let Some(expectations) = &mut self.event_expectations {
1821 match expectations.pop_front() {
1822 Some(TestResult::PaymentFailure { path, .. }) => {
1823 panic!("Unexpected failed payment path: {:?}", path)
1825 Some(TestResult::PaymentSuccess { path }) => {
1826 panic!("Unexpected successful payment path: {:?}", path)
1828 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1832 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1833 if let Some(expectations) = &mut self.event_expectations {
1834 match expectations.pop_front() {
1835 Some(TestResult::PaymentFailure { path, .. }) => {
1836 panic!("Unexpected payment path failure: {:?}", path)
1838 Some(TestResult::PaymentSuccess { path }) => {
1839 panic!("Unexpected successful payment path: {:?}", path)
1841 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1847 impl Drop for TestScorer {
1848 fn drop(&mut self) {
1849 if std::thread::panicking() {
1853 if let Some(event_expectations) = &self.event_expectations {
1854 if !event_expectations.is_empty() {
1855 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1859 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1860 if !scorer_expectations.is_empty() {
1861 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1868 expectations: core::cell::RefCell<VecDeque<Amount>>,
1869 attempts: core::cell::RefCell<usize>,
1870 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1871 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1874 #[derive(Clone, Debug, PartialEq, Eq)]
1881 struct OnAttempt(usize);
1886 expectations: core::cell::RefCell::new(VecDeque::new()),
1887 attempts: core::cell::RefCell::new(0),
1888 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1889 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
1893 fn expect_send(self, value_msat: Amount) -> Self {
1894 self.expectations.borrow_mut().push_back(value_msat);
1898 fn fails_on_attempt(self, attempt: usize) -> Self {
1899 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
1900 self.fails_with(failure, OnAttempt(attempt))
1903 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
1904 self.fails_with(PaymentSendFailure::PartialFailure {
1905 results: results.unwrap_or(vec![]),
1906 failed_paths_retry: Some(retry),
1907 payment_id: PaymentId([1; 32]),
1911 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1912 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1916 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
1917 let mut attempts = self.attempts.borrow_mut();
1920 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1921 Some(failure) => Err(failure),
1926 fn check_value_msats(&self, actual_value_msats: Amount) {
1927 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1928 if let Some(expected_value_msats) = expected_value_msats {
1929 assert_eq!(actual_value_msats, expected_value_msats);
1931 panic!("Unexpected amount: {:?}", actual_value_msats);
1935 fn track_inflight_htlcs(&self, route: &Route) {
1936 for path in &route.paths {
1937 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
1941 fn fail_path(&self, path: &Vec<RouteHop>) {
1942 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
1944 if let Some(idx) = path_idx {
1945 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
1950 impl Drop for TestPayer {
1951 fn drop(&mut self) {
1952 if std::thread::panicking() {
1956 if !self.expectations.borrow().is_empty() {
1957 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1962 impl Payer for TestPayer {
1963 fn node_id(&self) -> PublicKey {
1964 let secp_ctx = Secp256k1::new();
1965 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1968 fn first_hops(&self) -> Vec<ChannelDetails> {
1973 &self, route: &Route, _payment_hash: PaymentHash,
1974 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
1975 ) -> Result<(), PaymentSendFailure> {
1976 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1977 self.track_inflight_htlcs(route);
1978 self.check_attempts()
1981 fn send_spontaneous_payment(
1982 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
1983 ) -> Result<(), PaymentSendFailure> {
1984 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1985 self.check_attempts()
1989 &self, route: &Route, _payment_id: PaymentId
1990 ) -> Result<(), PaymentSendFailure> {
1991 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1992 self.track_inflight_htlcs(route);
1993 self.check_attempts()
1996 fn abandon_payment(&self, _payment_id: PaymentId) { }
1998 fn inflight_htlcs(&self) -> InFlightHtlcs {
1999 let mut inflight_htlcs = InFlightHtlcs::new();
2000 for path in self.inflight_htlcs_paths.clone().into_inner() {
2001 inflight_htlcs.process_path(&path, self.node_id());
2007 // *** Full Featured Functional Tests with a Real ChannelManager ***
2008 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2010 impl Router for ManualRouter {
2012 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2013 _inflight_htlcs: &InFlightHtlcs
2014 ) -> Result<Route, LightningError> {
2015 self.0.borrow_mut().pop_front().unwrap()
2018 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2020 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2022 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2024 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2027 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2028 self.0.borrow_mut().push_back(result);
2031 impl Drop for ManualRouter {
2032 fn drop(&mut self) {
2033 if std::thread::panicking() {
2036 assert!(self.0.borrow_mut().is_empty());
2041 fn retry_multi_path_single_failed_payment() {
2042 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2043 let chanmon_cfgs = create_chanmon_cfgs(2);
2044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2045 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2046 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2048 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2049 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2050 let chans = nodes[0].node.list_usable_channels();
2051 let mut route = Route {
2054 pubkey: nodes[1].node.get_our_node_id(),
2055 node_features: nodes[1].node.node_features(),
2056 short_channel_id: chans[0].short_channel_id.unwrap(),
2057 channel_features: nodes[1].node.channel_features(),
2059 cltv_expiry_delta: 100,
2062 pubkey: nodes[1].node.get_our_node_id(),
2063 node_features: nodes[1].node.node_features(),
2064 short_channel_id: chans[1].short_channel_id.unwrap(),
2065 channel_features: nodes[1].node.channel_features(),
2066 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2067 cltv_expiry_delta: 100,
2070 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2072 let router = ManualRouter(RefCell::new(VecDeque::new()));
2073 router.expect_find_route(Ok(route.clone()));
2074 // On retry, split the payment across both channels.
2075 route.paths[0][0].fee_msat = 50_000_001;
2076 route.paths[1][0].fee_msat = 50_000_000;
2077 router.expect_find_route(Ok(route.clone()));
2079 let event_handler = |_: Event| { panic!(); };
2080 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2082 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2083 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2084 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2086 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2087 assert_eq!(htlc_msgs.len(), 2);
2088 check_added_monitors!(nodes[0], 2);
2092 fn immediate_retry_on_failure() {
2093 // Tests that we can/will retry immediately after a failure
2094 let chanmon_cfgs = create_chanmon_cfgs(2);
2095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2097 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2099 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2100 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2101 let chans = nodes[0].node.list_usable_channels();
2102 let mut route = Route {
2105 pubkey: nodes[1].node.get_our_node_id(),
2106 node_features: nodes[1].node.node_features(),
2107 short_channel_id: chans[0].short_channel_id.unwrap(),
2108 channel_features: nodes[1].node.channel_features(),
2109 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2110 cltv_expiry_delta: 100,
2113 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2115 let router = ManualRouter(RefCell::new(VecDeque::new()));
2116 router.expect_find_route(Ok(route.clone()));
2117 // On retry, split the payment across both channels.
2118 route.paths.push(route.paths[0].clone());
2119 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2120 route.paths[0][0].fee_msat = 50_000_000;
2121 route.paths[1][0].fee_msat = 50_000_001;
2122 router.expect_find_route(Ok(route.clone()));
2124 let event_handler = |_: Event| { panic!(); };
2125 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2127 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2128 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2129 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2131 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2132 assert_eq!(htlc_msgs.len(), 2);
2133 check_added_monitors!(nodes[0], 2);
2137 fn no_extra_retries_on_back_to_back_fail() {
2138 // In a previous release, we had a race where we may exceed the payment retry count if we
2139 // get two failures in a row with the second having `all_paths_failed` set.
2140 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2141 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2142 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2143 // pending which we will see later. Thus, when we previously removed the retry tracking map
2144 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2145 // retry entry even though more events for the same payment were still pending. This led to
2146 // us retrying a payment again even though we'd already given up on it.
2148 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2149 // is used to remove the payment retry counter entries instead. This tests for the specific
2150 // excess-retry case while also testing `PaymentFailed` generation.
2152 let chanmon_cfgs = create_chanmon_cfgs(3);
2153 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2154 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2155 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2157 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2158 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2160 let mut route = Route {
2163 pubkey: nodes[1].node.get_our_node_id(),
2164 node_features: nodes[1].node.node_features(),
2165 short_channel_id: chan_1_scid,
2166 channel_features: nodes[1].node.channel_features(),
2168 cltv_expiry_delta: 100,
2170 pubkey: nodes[2].node.get_our_node_id(),
2171 node_features: nodes[2].node.node_features(),
2172 short_channel_id: chan_2_scid,
2173 channel_features: nodes[2].node.channel_features(),
2174 fee_msat: 100_000_000,
2175 cltv_expiry_delta: 100,
2178 pubkey: nodes[1].node.get_our_node_id(),
2179 node_features: nodes[1].node.node_features(),
2180 short_channel_id: chan_1_scid,
2181 channel_features: nodes[2].node.channel_features(),
2183 cltv_expiry_delta: 100,
2185 pubkey: nodes[2].node.get_our_node_id(),
2186 node_features: nodes[2].node.node_features(),
2187 short_channel_id: chan_2_scid,
2188 channel_features: nodes[2].node.channel_features(),
2189 fee_msat: 100_000_000,
2190 cltv_expiry_delta: 100,
2193 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2195 let router = ManualRouter(RefCell::new(VecDeque::new()));
2196 router.expect_find_route(Ok(route.clone()));
2197 // On retry, we'll only be asked for one path
2198 route.paths.remove(1);
2199 router.expect_find_route(Ok(route.clone()));
2201 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2202 let event_handler = |event: Event| {
2203 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2204 event_checker(event);
2206 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2208 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2209 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2210 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2212 let htlc_updates = SendEvent::from_node(&nodes[0]);
2213 check_added_monitors!(nodes[0], 1);
2214 assert_eq!(htlc_updates.msgs.len(), 1);
2216 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2217 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2218 check_added_monitors!(nodes[1], 1);
2219 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2222 check_added_monitors!(nodes[0], 1);
2223 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2225 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2226 check_added_monitors!(nodes[0], 1);
2227 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2230 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2231 check_added_monitors!(nodes[1], 1);
2232 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2234 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2235 check_added_monitors!(nodes[1], 1);
2236 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2238 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2239 check_added_monitors!(nodes[0], 1);
2241 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2242 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2243 check_added_monitors!(nodes[0], 1);
2244 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2246 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2247 check_added_monitors!(nodes[1], 1);
2248 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2250 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2251 check_added_monitors!(nodes[1], 1);
2252 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2254 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2255 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2256 check_added_monitors!(nodes[0], 1);
2258 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2259 check_added_monitors!(nodes[0], 1);
2260 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2262 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2263 check_added_monitors!(nodes[1], 1);
2264 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2265 check_added_monitors!(nodes[1], 1);
2266 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2268 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2269 check_added_monitors!(nodes[0], 1);
2271 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2272 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2273 // with it set. The first event will use up the only retry we are allowed, with the second
2274 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2275 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2276 // if the final HTLC failed.
2277 expected_events.borrow_mut().push_back(&|ev: Event| {
2278 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2279 assert!(!payment_failed_permanently);
2280 assert!(all_paths_failed);
2281 } else { panic!("Unexpected event"); }
2283 nodes[0].node.process_pending_events(&invoice_payer);
2284 assert!(expected_events.borrow().is_empty());
2286 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2287 check_added_monitors!(nodes[0], 1);
2289 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2290 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2291 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2292 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2293 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2295 expected_events.borrow_mut().push_back(&|ev: Event| {
2296 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2297 assert!(!payment_failed_permanently);
2298 assert!(all_paths_failed);
2299 } else { panic!("Unexpected event"); }
2301 expected_events.borrow_mut().push_back(&|ev: Event| {
2302 if let Event::PaymentFailed { .. } = ev {
2303 } else { panic!("Unexpected event"); }
2305 nodes[0].node.process_pending_events(&invoice_payer);
2306 assert!(expected_events.borrow().is_empty());