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,
200 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
201 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
205 /// Storing minimal payment attempts information required for determining if a outbound payment can
207 #[derive(Clone, Copy)]
208 struct PaymentAttempts<T: Time> {
209 /// This count will be incremented only after the result of the attempt is known. When it's 0,
210 /// it means the result of the first attempt is now known yet.
212 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
213 first_attempted_at: T
216 impl<T: Time> PaymentAttempts<T> {
220 first_attempted_at: T::now()
225 impl<T: Time> Display for PaymentAttempts<T> {
226 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
227 #[cfg(feature = "no-std")]
228 return write!( f, "attempts: {}", self.count);
229 #[cfg(not(feature = "no-std"))]
232 "attempts: {}, duration: {}s",
234 T::now().duration_since(self.first_attempted_at).as_secs()
239 /// A trait defining behavior of an [`Invoice`] payer.
241 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
242 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
244 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
246 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
247 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
248 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
249 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
251 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
253 /// Returns the payer's node id.
254 fn node_id(&self) -> PublicKey;
256 /// Returns the payer's channels.
257 fn first_hops(&self) -> Vec<ChannelDetails>;
259 /// Sends a payment over the Lightning Network using the given [`Route`].
261 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
262 payment_id: PaymentId
263 ) -> Result<(), PaymentSendFailure>;
265 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
266 fn send_spontaneous_payment(
267 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
268 ) -> Result<(), PaymentSendFailure>;
270 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
271 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
273 /// Signals that no further retries for the given payment will occur.
274 fn abandon_payment(&self, payment_id: PaymentId);
276 /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
278 fn inflight_htlcs(&self) -> InFlightHtlcs;
281 /// Strategies available to retry payment path failures for an [`Invoice`].
283 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
285 /// Max number of attempts to retry payment.
287 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
288 /// payments, if this is less than the total number of paths, we will never even retry all of the
291 #[cfg(feature = "std")]
292 /// Time elapsed before abandoning retries for a payment.
297 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
298 match (self, attempts) {
299 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
300 max_retry_count >= &count
302 #[cfg(feature = "std")]
303 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
304 *max_duration >= T::now().duration_since(*first_attempted_at),
309 /// An error that may occur when making a payment.
310 #[derive(Clone, Debug)]
311 pub enum PaymentError {
312 /// An error resulting from the provided [`Invoice`] or payment hash.
313 Invoice(&'static str),
314 /// An error occurring when finding a route.
315 Routing(LightningError),
316 /// An error occurring when sending a payment.
317 Sending(PaymentSendFailure),
320 impl<P: Deref, R: Deref, L: Deref, E: sealed::BaseEventHandler, T: Time>
321 InvoicePayerUsingTime<P, R, L, E, T>
327 /// Creates an invoice payer that retries failed payment paths.
329 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
330 /// `retry` has been exceeded for a given [`Invoice`].
332 payer: P, router: R, logger: L, event_handler: E, retry: Retry
339 payment_cache: Mutex::new(HashMap::new()),
344 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
346 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
347 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
348 /// a second payment with the same [`PaymentHash`] is never sent.
350 /// If you wish to use a different payment idempotency token, see
351 /// [`Self::pay_invoice_with_id`].
352 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
353 let payment_id = PaymentId(invoice.payment_hash().into_inner());
354 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
357 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
358 /// in case a retry is needed.
360 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
361 /// payment completes or fails, no idempotency guarantees are made.
363 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
364 /// has never been paid before.
366 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
368 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
369 if invoice.amount_milli_satoshis().is_none() {
370 Err(PaymentError::Invoice("amount missing"))
372 self.pay_invoice_using_amount(invoice, None, payment_id)
376 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
377 /// case a retry is needed.
379 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
380 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
381 /// a second payment with the same [`PaymentHash`] is never sent.
383 /// If you wish to use a different payment idempotency token, see
384 /// [`Self::pay_zero_value_invoice_with_id`].
385 pub fn pay_zero_value_invoice(
386 &self, invoice: &Invoice, amount_msats: u64
387 ) -> Result<PaymentId, PaymentError> {
388 let payment_id = PaymentId(invoice.payment_hash().into_inner());
389 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
392 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
393 /// caching the invoice for later use in case a retry is needed.
395 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
396 /// payment completes or fails, no idempotency guarantees are made.
398 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
399 /// has never been paid before.
401 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
402 /// idempotency token.
403 pub fn pay_zero_value_invoice_with_id(
404 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
405 ) -> Result<(), PaymentError> {
406 if invoice.amount_milli_satoshis().is_some() {
407 Err(PaymentError::Invoice("amount unexpected"))
409 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
413 fn pay_invoice_using_amount(
414 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
415 ) -> Result<(), PaymentError> {
416 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
418 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
419 match self.payment_cache.lock().unwrap().entry(payment_hash) {
420 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
421 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
424 let payment_secret = Some(invoice.payment_secret().clone());
425 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
426 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
427 .with_route_hints(invoice.route_hints());
428 if let Some(features) = invoice.features() {
429 payment_params = payment_params.with_features(features.clone());
431 let route_params = RouteParameters {
433 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
434 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
437 let send_payment = |route: &Route| {
438 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
441 self.pay_internal(&route_params, payment_hash, send_payment)
442 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
445 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
446 /// case a retry is needed.
448 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
449 /// as long as the payment is still pending. Once the payment completes or fails, you must
450 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
452 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
453 final_cltv_expiry_delta: u32
454 ) -> Result<PaymentId, PaymentError> {
455 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
456 let payment_id = PaymentId(payment_hash.0);
457 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
458 final_cltv_expiry_delta)
459 .map(|()| payment_id)
462 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
463 /// caching the invoice for later use in case a retry is needed.
465 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
466 /// payment completes or fails, no idempotency guarantees are made.
468 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
469 /// [`PaymentHash`] has never been paid before.
470 pub fn pay_pubkey_with_id(
471 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
472 amount_msats: u64, final_cltv_expiry_delta: u32
473 ) -> Result<(), PaymentError> {
474 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
475 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
476 final_cltv_expiry_delta)
480 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
481 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
482 ) -> Result<(), PaymentError> {
483 match self.payment_cache.lock().unwrap().entry(payment_hash) {
484 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
485 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
488 let route_params = RouteParameters {
489 payment_params: PaymentParameters::for_keysend(pubkey),
490 final_value_msat: amount_msats,
491 final_cltv_expiry_delta,
494 let send_payment = |route: &Route| {
495 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
497 self.pay_internal(&route_params, payment_hash, send_payment)
498 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
501 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
502 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
503 ) -> Result<(), PaymentError> {
504 #[cfg(feature = "std")] {
505 if has_expired(params) {
506 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
507 return Err(PaymentError::Invoice("Invoice expired prior to send"));
511 let payer = self.payer.node_id();
512 let first_hops = self.payer.first_hops();
513 let inflight_htlcs = self.payer.inflight_htlcs();
514 let route = self.router.find_route(
515 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
516 ).map_err(|e| PaymentError::Routing(e))?;
518 match send_payment(&route) {
521 PaymentSendFailure::ParameterError(_) => Err(e),
522 PaymentSendFailure::PathParameterError(_) => Err(e),
523 PaymentSendFailure::DuplicatePayment => Err(e),
524 PaymentSendFailure::AllFailedResendSafe(_) => {
525 let mut payment_cache = self.payment_cache.lock().unwrap();
526 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
527 payment_attempts.count += 1;
528 if self.retry.is_retryable_now(payment_attempts) {
529 core::mem::drop(payment_cache);
530 Ok(self.pay_internal(params, payment_hash, send_payment)?)
535 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
536 if let Some(retry_data) = failed_paths_retry {
537 // Some paths were sent, even if we failed to send the full MPP value our
538 // recipient may misbehave and claim the funds, at which point we have to
539 // consider the payment sent, so return `Ok()` here, ignoring any retry
541 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
544 // This may happen if we send a payment and some paths fail, but
545 // only due to a temporary monitor failure or the like, implying
546 // they're really in-flight, but we haven't sent the initial
547 // HTLC-Add messages yet.
552 }.map_err(|e| PaymentError::Sending(e))
556 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
557 ) -> Result<(), ()> {
559 *self.payment_cache.lock().unwrap().entry(payment_hash)
560 .and_modify(|attempts| attempts.count += 1)
561 .or_insert(PaymentAttempts {
563 first_attempted_at: T::now()
566 if !self.retry.is_retryable_now(&attempts) {
567 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
571 #[cfg(feature = "std")] {
572 if has_expired(params) {
573 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
578 let payer = self.payer.node_id();
579 let first_hops = self.payer.first_hops();
580 let inflight_htlcs = self.payer.inflight_htlcs();
582 let route = self.router.find_route(
583 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
587 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
591 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
593 Err(PaymentSendFailure::ParameterError(_)) |
594 Err(PaymentSendFailure::PathParameterError(_)) => {
595 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
598 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
599 self.retry_payment(payment_id, payment_hash, params)
601 Err(PaymentSendFailure::DuplicatePayment) => {
602 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
605 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
606 if let Some(retry) = failed_paths_retry {
607 // Always return Ok for the same reason as noted in pay_internal.
608 let _ = self.retry_payment(payment_id, payment_hash, &retry);
615 /// Removes the payment cached by the given payment hash.
617 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
618 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
619 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
620 self.payment_cache.lock().unwrap().remove(payment_hash);
624 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
625 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
628 #[cfg(feature = "std")]
629 fn has_expired(route_params: &RouteParameters) -> bool {
630 if let Some(expiry_time) = route_params.payment_params.expiry_time {
631 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
635 impl<P: Deref, R: Deref, L: Deref, E: sealed::BaseEventHandler, T: Time>
636 InvoicePayerUsingTime<P, R, L, E, T>
642 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
644 fn handle_event_internal(&self, event: &Event) -> bool {
646 Event::PaymentPathFailed {
647 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
649 if let Some(short_channel_id) = short_channel_id {
650 let path = path.iter().collect::<Vec<_>>();
651 self.router.notify_payment_path_failed(&path, *short_channel_id)
654 if payment_id.is_none() {
655 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
656 } else if *payment_failed_permanently {
657 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
658 self.payer.abandon_payment(payment_id.unwrap());
659 } else if retry.is_none() {
660 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
661 self.payer.abandon_payment(payment_id.unwrap());
662 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
663 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
666 self.payer.abandon_payment(payment_id.unwrap());
669 Event::PaymentFailed { payment_hash, .. } => {
670 self.remove_cached_payment(&payment_hash);
672 Event::PaymentPathSuccessful { path, .. } => {
673 let path = path.iter().collect::<Vec<_>>();
674 self.router.notify_payment_path_successful(&path);
676 Event::PaymentSent { payment_hash, .. } => {
677 let mut payment_cache = self.payment_cache.lock().unwrap();
678 let attempts = payment_cache
679 .remove(payment_hash)
680 .map_or(1, |attempts| attempts.count + 1);
681 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
683 Event::ProbeSuccessful { payment_hash, path, .. } => {
684 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
685 let path = path.iter().collect::<Vec<_>>();
686 self.router.notify_payment_probe_successful(&path);
688 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
689 if let Some(short_channel_id) = short_channel_id {
690 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
691 let path = path.iter().collect::<Vec<_>>();
692 self.router.notify_payment_probe_failed(&path, *short_channel_id);
698 // Delegate to the decorated event handler unless the payment is retried.
703 impl<P: Deref, R: Deref, L: Deref, E: EventHandler, T: Time>
704 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
710 fn handle_event(&self, event: Event) {
711 let should_forward = self.handle_event_internal(&event);
713 self.event_handler.handle_event(event)
718 impl<P: Deref, R: Deref, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
719 InvoicePayerUsingTime<P, R, L, H, T>
725 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
726 /// handler, if necessary, to handle them asynchronously.
727 pub async fn handle_event_async(&self, event: Event) {
728 let should_forward = self.handle_event_internal(&event);
730 (self.event_handler)(event).await;
738 use crate::{InvoiceBuilder, Currency};
739 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
740 use bitcoin_hashes::sha256::Hash as Sha256;
741 use lightning::ln::PaymentPreimage;
742 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
743 use lightning::ln::functional_test_utils::*;
744 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
745 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
746 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router, ScorerAccountingForInFlightHtlcs};
747 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
748 use lightning::util::test_utils::TestLogger;
749 use lightning::util::errors::APIError;
750 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
751 use secp256k1::{SecretKey, PublicKey, Secp256k1};
752 use std::cell::RefCell;
753 use std::collections::VecDeque;
754 use std::time::{SystemTime, Duration};
755 use crate::time_utils::tests::SinceEpoch;
756 use crate::DEFAULT_EXPIRY_TIME;
758 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
759 let payment_hash = Sha256::hash(&payment_preimage.0);
760 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
762 InvoiceBuilder::new(Currency::Bitcoin)
763 .description("test".into())
764 .payment_hash(payment_hash)
765 .payment_secret(PaymentSecret([0; 32]))
766 .duration_since_epoch(duration_since_epoch())
767 .min_final_cltv_expiry_delta(144)
768 .amount_milli_satoshis(128)
769 .build_signed(|hash| {
770 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
775 fn duration_since_epoch() -> Duration {
776 #[cfg(feature = "std")]
777 let duration_since_epoch =
778 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
779 #[cfg(not(feature = "std"))]
780 let duration_since_epoch = Duration::from_secs(1234567);
784 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
785 let payment_hash = Sha256::hash(&payment_preimage.0);
786 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
788 InvoiceBuilder::new(Currency::Bitcoin)
789 .description("test".into())
790 .payment_hash(payment_hash)
791 .payment_secret(PaymentSecret([0; 32]))
792 .duration_since_epoch(duration_since_epoch())
793 .min_final_cltv_expiry_delta(144)
794 .build_signed(|hash| {
795 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
800 #[cfg(feature = "std")]
801 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
802 let payment_hash = Sha256::hash(&payment_preimage.0);
803 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
804 let duration = duration_since_epoch()
805 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
807 InvoiceBuilder::new(Currency::Bitcoin)
808 .description("test".into())
809 .payment_hash(payment_hash)
810 .payment_secret(PaymentSecret([0; 32]))
811 .duration_since_epoch(duration)
812 .min_final_cltv_expiry_delta(144)
813 .amount_milli_satoshis(128)
814 .build_signed(|hash| {
815 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
820 fn pubkey() -> PublicKey {
821 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
825 fn pays_invoice_on_first_attempt() {
826 let event_handled = core::cell::RefCell::new(false);
827 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
829 let payment_preimage = PaymentPreimage([1; 32]);
830 let invoice = invoice(payment_preimage);
831 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
832 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
834 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
835 let router = TestRouter::new(TestScorer::new());
836 let logger = TestLogger::new();
838 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
840 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
841 assert_eq!(*payer.attempts.borrow(), 1);
843 invoice_payer.handle_event(Event::PaymentSent {
844 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
846 assert_eq!(*event_handled.borrow(), true);
847 assert_eq!(*payer.attempts.borrow(), 1);
851 fn pays_invoice_on_retry() {
852 let event_handled = core::cell::RefCell::new(false);
853 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
855 let payment_preimage = PaymentPreimage([1; 32]);
856 let invoice = invoice(payment_preimage);
857 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
858 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
860 let payer = TestPayer::new()
861 .expect_send(Amount::ForInvoice(final_value_msat))
862 .expect_send(Amount::OnRetry(final_value_msat / 2));
863 let router = TestRouter::new(TestScorer::new());
864 let logger = TestLogger::new();
866 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
868 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
869 assert_eq!(*payer.attempts.borrow(), 1);
871 let event = Event::PaymentPathFailed {
874 network_update: None,
875 payment_failed_permanently: false,
876 all_paths_failed: false,
877 path: TestRouter::path_for_value(final_value_msat),
878 short_channel_id: None,
879 retry: Some(TestRouter::retry_for_invoice(&invoice)),
881 invoice_payer.handle_event(event);
882 assert_eq!(*event_handled.borrow(), false);
883 assert_eq!(*payer.attempts.borrow(), 2);
885 invoice_payer.handle_event(Event::PaymentSent {
886 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
888 assert_eq!(*event_handled.borrow(), true);
889 assert_eq!(*payer.attempts.borrow(), 2);
893 fn pays_invoice_on_partial_failure() {
894 let event_handler = |_: Event| { panic!() };
896 let payment_preimage = PaymentPreimage([1; 32]);
897 let invoice = invoice(payment_preimage);
898 let retry = TestRouter::retry_for_invoice(&invoice);
899 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
901 let payer = TestPayer::new()
902 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
903 .fails_with_partial_failure(retry, OnAttempt(2), None)
904 .expect_send(Amount::ForInvoice(final_value_msat))
905 .expect_send(Amount::OnRetry(final_value_msat / 2))
906 .expect_send(Amount::OnRetry(final_value_msat / 2));
907 let router = TestRouter::new(TestScorer::new());
908 let logger = TestLogger::new();
910 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
912 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
916 fn retries_payment_path_for_unknown_payment() {
917 let event_handled = core::cell::RefCell::new(false);
918 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
920 let payment_preimage = PaymentPreimage([1; 32]);
921 let invoice = invoice(payment_preimage);
922 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
923 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
925 let payer = TestPayer::new()
926 .expect_send(Amount::OnRetry(final_value_msat / 2))
927 .expect_send(Amount::OnRetry(final_value_msat / 2));
928 let router = TestRouter::new(TestScorer::new());
929 let logger = TestLogger::new();
931 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
933 let payment_id = Some(PaymentId([1; 32]));
934 let event = Event::PaymentPathFailed {
937 network_update: None,
938 payment_failed_permanently: false,
939 all_paths_failed: false,
940 path: TestRouter::path_for_value(final_value_msat),
941 short_channel_id: None,
942 retry: Some(TestRouter::retry_for_invoice(&invoice)),
944 invoice_payer.handle_event(event.clone());
945 assert_eq!(*event_handled.borrow(), false);
946 assert_eq!(*payer.attempts.borrow(), 1);
948 invoice_payer.handle_event(event.clone());
949 assert_eq!(*event_handled.borrow(), false);
950 assert_eq!(*payer.attempts.borrow(), 2);
952 invoice_payer.handle_event(Event::PaymentSent {
953 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
955 assert_eq!(*event_handled.borrow(), true);
956 assert_eq!(*payer.attempts.borrow(), 2);
960 fn fails_paying_invoice_after_max_retry_counts() {
961 let event_handled = core::cell::RefCell::new(false);
962 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
964 let payment_preimage = PaymentPreimage([1; 32]);
965 let invoice = invoice(payment_preimage);
966 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
968 let payer = TestPayer::new()
969 .expect_send(Amount::ForInvoice(final_value_msat))
970 .expect_send(Amount::OnRetry(final_value_msat / 2))
971 .expect_send(Amount::OnRetry(final_value_msat / 2));
972 let router = TestRouter::new(TestScorer::new());
973 let logger = TestLogger::new();
975 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
977 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
978 assert_eq!(*payer.attempts.borrow(), 1);
980 let event = Event::PaymentPathFailed {
982 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
983 network_update: None,
984 payment_failed_permanently: false,
985 all_paths_failed: true,
986 path: TestRouter::path_for_value(final_value_msat),
987 short_channel_id: None,
988 retry: Some(TestRouter::retry_for_invoice(&invoice)),
990 invoice_payer.handle_event(event);
991 assert_eq!(*event_handled.borrow(), false);
992 assert_eq!(*payer.attempts.borrow(), 2);
994 let event = Event::PaymentPathFailed {
996 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
997 network_update: None,
998 payment_failed_permanently: false,
999 all_paths_failed: false,
1000 path: TestRouter::path_for_value(final_value_msat / 2),
1001 short_channel_id: None,
1002 retry: Some(RouteParameters {
1003 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1006 invoice_payer.handle_event(event.clone());
1007 assert_eq!(*event_handled.borrow(), false);
1008 assert_eq!(*payer.attempts.borrow(), 3);
1010 invoice_payer.handle_event(event.clone());
1011 assert_eq!(*event_handled.borrow(), true);
1012 assert_eq!(*payer.attempts.borrow(), 3);
1015 #[cfg(feature = "std")]
1017 fn fails_paying_invoice_after_max_retry_timeout() {
1018 let event_handled = core::cell::RefCell::new(false);
1019 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1021 let payment_preimage = PaymentPreimage([1; 32]);
1022 let invoice = invoice(payment_preimage);
1023 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1025 let payer = TestPayer::new()
1026 .expect_send(Amount::ForInvoice(final_value_msat))
1027 .expect_send(Amount::OnRetry(final_value_msat / 2));
1029 let router = TestRouter::new(TestScorer::new());
1030 let logger = TestLogger::new();
1031 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1034 InvoicePayerUsingSinceEpoch::new(&payer, &router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1036 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1037 assert_eq!(*payer.attempts.borrow(), 1);
1039 let event = Event::PaymentPathFailed {
1041 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1042 network_update: None,
1043 payment_failed_permanently: false,
1044 all_paths_failed: true,
1045 path: TestRouter::path_for_value(final_value_msat),
1046 short_channel_id: None,
1047 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1049 invoice_payer.handle_event(event.clone());
1050 assert_eq!(*event_handled.borrow(), false);
1051 assert_eq!(*payer.attempts.borrow(), 2);
1053 SinceEpoch::advance(Duration::from_secs(121));
1055 invoice_payer.handle_event(event.clone());
1056 assert_eq!(*event_handled.borrow(), true);
1057 assert_eq!(*payer.attempts.borrow(), 2);
1061 fn fails_paying_invoice_with_missing_retry_params() {
1062 let event_handled = core::cell::RefCell::new(false);
1063 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1065 let payment_preimage = PaymentPreimage([1; 32]);
1066 let invoice = invoice(payment_preimage);
1067 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1069 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1070 let router = TestRouter::new(TestScorer::new());
1071 let logger = TestLogger::new();
1073 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1075 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1076 assert_eq!(*payer.attempts.borrow(), 1);
1078 let event = Event::PaymentPathFailed {
1080 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1081 network_update: None,
1082 payment_failed_permanently: false,
1083 all_paths_failed: false,
1085 short_channel_id: None,
1088 invoice_payer.handle_event(event);
1089 assert_eq!(*event_handled.borrow(), true);
1090 assert_eq!(*payer.attempts.borrow(), 1);
1093 // Expiration is checked only in an std environment
1094 #[cfg(feature = "std")]
1096 fn fails_paying_invoice_after_expiration() {
1097 let event_handled = core::cell::RefCell::new(false);
1098 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1100 let payer = TestPayer::new();
1101 let router = TestRouter::new(TestScorer::new());
1102 let logger = TestLogger::new();
1104 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1106 let payment_preimage = PaymentPreimage([1; 32]);
1107 let invoice = expired_invoice(payment_preimage);
1108 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1109 assert_eq!(msg, "Invoice expired prior to send");
1110 } else { panic!("Expected Invoice Error"); }
1113 // Expiration is checked only in an std environment
1114 #[cfg(feature = "std")]
1116 fn fails_retrying_invoice_after_expiration() {
1117 let event_handled = core::cell::RefCell::new(false);
1118 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1120 let payment_preimage = PaymentPreimage([1; 32]);
1121 let invoice = invoice(payment_preimage);
1122 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1124 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1125 let router = TestRouter::new(TestScorer::new());
1126 let logger = TestLogger::new();
1128 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1130 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1131 assert_eq!(*payer.attempts.borrow(), 1);
1133 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1134 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1135 .checked_sub(Duration::from_secs(2)).unwrap()
1136 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1137 let event = Event::PaymentPathFailed {
1139 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1140 network_update: None,
1141 payment_failed_permanently: false,
1142 all_paths_failed: false,
1144 short_channel_id: None,
1145 retry: Some(retry_data),
1147 invoice_payer.handle_event(event);
1148 assert_eq!(*event_handled.borrow(), true);
1149 assert_eq!(*payer.attempts.borrow(), 1);
1153 fn fails_paying_invoice_after_retry_error() {
1154 let event_handled = core::cell::RefCell::new(false);
1155 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1157 let payment_preimage = PaymentPreimage([1; 32]);
1158 let invoice = invoice(payment_preimage);
1159 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1161 let payer = TestPayer::new()
1162 .fails_on_attempt(2)
1163 .expect_send(Amount::ForInvoice(final_value_msat))
1164 .expect_send(Amount::OnRetry(final_value_msat / 2));
1165 let router = TestRouter::new(TestScorer::new());
1166 let logger = TestLogger::new();
1168 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1170 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1171 assert_eq!(*payer.attempts.borrow(), 1);
1173 let event = Event::PaymentPathFailed {
1175 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1176 network_update: None,
1177 payment_failed_permanently: false,
1178 all_paths_failed: false,
1179 path: TestRouter::path_for_value(final_value_msat / 2),
1180 short_channel_id: None,
1181 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1183 invoice_payer.handle_event(event);
1184 assert_eq!(*event_handled.borrow(), true);
1185 assert_eq!(*payer.attempts.borrow(), 2);
1189 fn fails_paying_invoice_after_rejected_by_payee() {
1190 let event_handled = core::cell::RefCell::new(false);
1191 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1193 let payment_preimage = PaymentPreimage([1; 32]);
1194 let invoice = invoice(payment_preimage);
1195 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1197 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1198 let router = TestRouter::new(TestScorer::new());
1199 let logger = TestLogger::new();
1201 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1203 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1204 assert_eq!(*payer.attempts.borrow(), 1);
1206 let event = Event::PaymentPathFailed {
1208 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1209 network_update: None,
1210 payment_failed_permanently: true,
1211 all_paths_failed: false,
1213 short_channel_id: None,
1214 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1216 invoice_payer.handle_event(event);
1217 assert_eq!(*event_handled.borrow(), true);
1218 assert_eq!(*payer.attempts.borrow(), 1);
1222 fn fails_repaying_invoice_with_pending_payment() {
1223 let event_handled = core::cell::RefCell::new(false);
1224 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1226 let payment_preimage = PaymentPreimage([1; 32]);
1227 let invoice = invoice(payment_preimage);
1228 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1230 let payer = TestPayer::new()
1231 .expect_send(Amount::ForInvoice(final_value_msat))
1232 .expect_send(Amount::ForInvoice(final_value_msat));
1233 let router = TestRouter::new(TestScorer::new());
1234 let logger = TestLogger::new();
1236 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1238 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1240 // Cannot repay an invoice pending payment.
1241 match invoice_payer.pay_invoice(&invoice) {
1242 Err(PaymentError::Invoice("payment pending")) => {},
1243 Err(_) => panic!("unexpected error"),
1244 Ok(_) => panic!("expected invoice error"),
1247 // Can repay an invoice once cleared from cache.
1248 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1249 invoice_payer.remove_cached_payment(&payment_hash);
1250 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1252 // Cannot retry paying an invoice if cleared from cache.
1253 invoice_payer.remove_cached_payment(&payment_hash);
1254 let event = Event::PaymentPathFailed {
1257 network_update: None,
1258 payment_failed_permanently: false,
1259 all_paths_failed: false,
1261 short_channel_id: None,
1262 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1264 invoice_payer.handle_event(event);
1265 assert_eq!(*event_handled.borrow(), true);
1269 fn fails_paying_invoice_with_routing_errors() {
1270 let payer = TestPayer::new();
1271 let router = FailingRouter {};
1272 let logger = TestLogger::new();
1274 InvoicePayer::new(&payer, &router, &logger, |_: Event| {}, Retry::Attempts(0));
1276 let payment_preimage = PaymentPreimage([1; 32]);
1277 let invoice = invoice(payment_preimage);
1278 match invoice_payer.pay_invoice(&invoice) {
1279 Err(PaymentError::Routing(_)) => {},
1280 Err(_) => panic!("unexpected error"),
1281 Ok(_) => panic!("expected routing error"),
1286 fn fails_paying_invoice_with_sending_errors() {
1287 let payment_preimage = PaymentPreimage([1; 32]);
1288 let invoice = invoice(payment_preimage);
1289 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1291 let payer = TestPayer::new()
1292 .fails_on_attempt(1)
1293 .expect_send(Amount::ForInvoice(final_value_msat));
1294 let router = TestRouter::new(TestScorer::new());
1295 let logger = TestLogger::new();
1297 InvoicePayer::new(&payer, &router, &logger, |_: Event| {}, Retry::Attempts(0));
1299 match invoice_payer.pay_invoice(&invoice) {
1300 Err(PaymentError::Sending(_)) => {},
1301 Err(_) => panic!("unexpected error"),
1302 Ok(_) => panic!("expected sending error"),
1307 fn pays_zero_value_invoice_using_amount() {
1308 let event_handled = core::cell::RefCell::new(false);
1309 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1311 let payment_preimage = PaymentPreimage([1; 32]);
1312 let invoice = zero_value_invoice(payment_preimage);
1313 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1314 let final_value_msat = 100;
1316 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1317 let router = TestRouter::new(TestScorer::new());
1318 let logger = TestLogger::new();
1320 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1323 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1324 assert_eq!(*payer.attempts.borrow(), 1);
1326 invoice_payer.handle_event(Event::PaymentSent {
1327 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1329 assert_eq!(*event_handled.borrow(), true);
1330 assert_eq!(*payer.attempts.borrow(), 1);
1334 fn fails_paying_zero_value_invoice_with_amount() {
1335 let event_handled = core::cell::RefCell::new(false);
1336 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1338 let payer = TestPayer::new();
1339 let router = TestRouter::new(TestScorer::new());
1340 let logger = TestLogger::new();
1342 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1344 let payment_preimage = PaymentPreimage([1; 32]);
1345 let invoice = invoice(payment_preimage);
1347 // Cannot repay an invoice pending payment.
1348 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1349 Err(PaymentError::Invoice("amount unexpected")) => {},
1350 Err(_) => panic!("unexpected error"),
1351 Ok(_) => panic!("expected invoice error"),
1356 fn pays_pubkey_with_amount() {
1357 let event_handled = core::cell::RefCell::new(false);
1358 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1360 let pubkey = pubkey();
1361 let payment_preimage = PaymentPreimage([1; 32]);
1362 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1363 let final_value_msat = 100;
1364 let final_cltv_expiry_delta = 42;
1366 let payer = TestPayer::new()
1367 .expect_send(Amount::Spontaneous(final_value_msat))
1368 .expect_send(Amount::OnRetry(final_value_msat));
1369 let router = TestRouter::new(TestScorer::new());
1370 let logger = TestLogger::new();
1372 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1374 let payment_id = Some(invoice_payer.pay_pubkey(
1375 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1377 assert_eq!(*payer.attempts.borrow(), 1);
1379 let retry = RouteParameters {
1380 payment_params: PaymentParameters::for_keysend(pubkey),
1382 final_cltv_expiry_delta,
1384 let event = Event::PaymentPathFailed {
1387 network_update: None,
1388 payment_failed_permanently: false,
1389 all_paths_failed: false,
1391 short_channel_id: None,
1394 invoice_payer.handle_event(event);
1395 assert_eq!(*event_handled.borrow(), false);
1396 assert_eq!(*payer.attempts.borrow(), 2);
1398 invoice_payer.handle_event(Event::PaymentSent {
1399 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1401 assert_eq!(*event_handled.borrow(), true);
1402 assert_eq!(*payer.attempts.borrow(), 2);
1406 fn scores_failed_channel() {
1407 let event_handled = core::cell::RefCell::new(false);
1408 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1410 let payment_preimage = PaymentPreimage([1; 32]);
1411 let invoice = invoice(payment_preimage);
1412 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1413 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1414 let path = TestRouter::path_for_value(final_value_msat);
1415 let short_channel_id = Some(path[0].short_channel_id);
1417 // Expect that scorer is given short_channel_id upon handling the event.
1418 let payer = TestPayer::new()
1419 .expect_send(Amount::ForInvoice(final_value_msat))
1420 .expect_send(Amount::OnRetry(final_value_msat / 2));
1421 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1422 path: path.clone(), short_channel_id: path[0].short_channel_id,
1424 let router = TestRouter::new(scorer);
1425 let logger = TestLogger::new();
1427 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1429 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1430 let event = Event::PaymentPathFailed {
1433 network_update: None,
1434 payment_failed_permanently: false,
1435 all_paths_failed: false,
1438 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1440 invoice_payer.handle_event(event);
1444 fn scores_successful_channels() {
1445 let event_handled = core::cell::RefCell::new(false);
1446 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1448 let payment_preimage = PaymentPreimage([1; 32]);
1449 let invoice = invoice(payment_preimage);
1450 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1451 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1452 let route = TestRouter::route_for_value(final_value_msat);
1454 // Expect that scorer is given short_channel_id upon handling the event.
1455 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1456 let scorer = TestScorer::new()
1457 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1458 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1459 let router = TestRouter::new(scorer);
1460 let logger = TestLogger::new();
1462 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1464 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1465 let event = Event::PaymentPathSuccessful {
1466 payment_id, payment_hash, path: route.paths[0].clone()
1468 invoice_payer.handle_event(event);
1469 let event = Event::PaymentPathSuccessful {
1470 payment_id, payment_hash, path: route.paths[1].clone()
1472 invoice_payer.handle_event(event);
1476 fn considers_inflight_htlcs_between_invoice_payments() {
1477 let event_handled = core::cell::RefCell::new(false);
1478 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1480 let payment_preimage = PaymentPreimage([1; 32]);
1481 let payment_invoice = invoice(payment_preimage);
1482 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1484 let payer = TestPayer::new()
1485 .expect_send(Amount::ForInvoice(final_value_msat))
1486 .expect_send(Amount::ForInvoice(final_value_msat));
1487 let scorer = TestScorer::new()
1488 // 1st invoice, 1st path
1489 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1490 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1491 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1492 // 1st invoice, 2nd path
1493 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1494 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1495 // 2nd invoice, 1st path
1496 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1497 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1498 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1499 // 2nd invoice, 2nd path
1500 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1501 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1502 let router = TestRouter::new(scorer);
1503 let logger = TestLogger::new();
1505 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1507 // Make first invoice payment.
1508 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1510 // Let's pay a second invoice that will be using the same path. This should trigger the
1511 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1513 let payment_preimage_2 = PaymentPreimage([2; 32]);
1514 let payment_invoice_2 = invoice(payment_preimage_2);
1515 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1519 fn considers_inflight_htlcs_between_retries() {
1520 // First, let's just send a payment through, but only make sure one of the path completes
1521 let event_handled = core::cell::RefCell::new(false);
1522 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1524 let payment_preimage = PaymentPreimage([1; 32]);
1525 let payment_invoice = invoice(payment_preimage);
1526 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1527 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1529 let payer = TestPayer::new()
1530 .expect_send(Amount::ForInvoice(final_value_msat))
1531 .expect_send(Amount::OnRetry(final_value_msat / 2))
1532 .expect_send(Amount::OnRetry(final_value_msat / 4));
1533 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1534 let scorer = TestScorer::new()
1535 // 1st invoice, 1st path
1536 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1537 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1538 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1539 // 1st invoice, 2nd path
1540 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1541 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1542 // Retry 1, 1st path
1543 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1544 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1545 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1546 // Retry 1, 2nd path
1547 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1548 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1549 // Retry 2, 1st path
1550 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1551 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1552 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1553 // Retry 2, 2nd path
1554 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1555 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1556 let router = TestRouter::new(scorer);
1557 let logger = TestLogger::new();
1559 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1561 // Fail 1st path, leave 2nd path inflight
1562 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1563 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1564 invoice_payer.handle_event(Event::PaymentPathFailed {
1567 network_update: None,
1568 payment_failed_permanently: false,
1569 all_paths_failed: false,
1570 path: TestRouter::path_for_value(final_value_msat),
1571 short_channel_id: None,
1572 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1575 // Fails again the 1st path of our retry
1576 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1577 invoice_payer.handle_event(Event::PaymentPathFailed {
1580 network_update: None,
1581 payment_failed_permanently: false,
1582 all_paths_failed: false,
1583 path: TestRouter::path_for_value(final_value_msat / 2),
1584 short_channel_id: None,
1585 retry: Some(RouteParameters {
1586 final_value_msat: final_value_msat / 4,
1587 ..TestRouter::retry_for_invoice(&payment_invoice)
1593 scorer: RefCell<TestScorer>,
1597 fn new(scorer: TestScorer) -> Self {
1598 TestRouter { scorer: RefCell::new(scorer) }
1601 fn route_for_value(final_value_msat: u64) -> Route {
1606 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1607 channel_features: ChannelFeatures::empty(),
1608 node_features: NodeFeatures::empty(),
1609 short_channel_id: 0,
1611 cltv_expiry_delta: 0
1614 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1615 channel_features: ChannelFeatures::empty(),
1616 node_features: NodeFeatures::empty(),
1617 short_channel_id: 1,
1619 cltv_expiry_delta: 0
1622 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1623 channel_features: ChannelFeatures::empty(),
1624 node_features: NodeFeatures::empty(),
1625 short_channel_id: 2,
1626 fee_msat: final_value_msat / 2,
1627 cltv_expiry_delta: 0
1632 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1633 channel_features: ChannelFeatures::empty(),
1634 node_features: NodeFeatures::empty(),
1635 short_channel_id: 3,
1637 cltv_expiry_delta: 144
1640 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1641 channel_features: ChannelFeatures::empty(),
1642 node_features: NodeFeatures::empty(),
1643 short_channel_id: 4,
1644 fee_msat: final_value_msat / 2,
1645 cltv_expiry_delta: 144
1649 payment_params: None,
1653 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1654 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1657 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1658 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1659 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1660 .with_route_hints(invoice.route_hints());
1661 if let Some(features) = invoice.features() {
1662 payment_params = payment_params.with_features(features.clone());
1664 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1668 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
1673 impl Router for TestRouter {
1675 &self, payer: &PublicKey, route_params: &RouteParameters,
1676 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
1677 ) -> Result<Route, LightningError> {
1678 // Simulate calling the Scorer just as you would in find_route
1679 let route = Self::route_for_value(route_params.final_value_msat);
1680 let locked_scorer = self.scorer.lock();
1681 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer, inflight_htlcs);
1682 for path in route.paths {
1683 let mut aggregate_msat = 0u64;
1684 for (idx, hop) in path.iter().rev().enumerate() {
1685 aggregate_msat += hop.fee_msat;
1686 let usage = ChannelUsage {
1687 amount_msat: aggregate_msat,
1688 inflight_htlc_msat: 0,
1689 effective_capacity: EffectiveCapacity::Unknown,
1692 // Since the path is reversed, the last element in our iteration is the first
1694 if idx == path.len() - 1 {
1695 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1697 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1703 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1707 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1708 self.scorer.lock().payment_path_failed(path, short_channel_id);
1711 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1712 self.scorer.lock().payment_path_successful(path);
1715 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1716 self.scorer.lock().probe_successful(path);
1719 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1720 self.scorer.lock().probe_failed(path, short_channel_id);
1724 struct FailingRouter;
1726 impl Router for FailingRouter {
1728 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1729 _inflight_htlcs: &InFlightHtlcs,
1730 ) -> Result<Route, LightningError> {
1731 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1734 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1736 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1738 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1740 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1744 event_expectations: Option<VecDeque<TestResult>>,
1745 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1750 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1751 PaymentSuccess { path: Vec<RouteHop> },
1757 event_expectations: None,
1758 scorer_expectations: RefCell::new(None),
1762 fn expect(mut self, expectation: TestResult) -> Self {
1763 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1767 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1768 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1774 impl lightning::util::ser::Writeable for TestScorer {
1775 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1778 impl Score for TestScorer {
1779 fn channel_penalty_msat(
1780 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1782 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1783 match scorer_expectations.pop_front() {
1784 Some(expectation) => {
1785 assert_eq!(expectation.amount_msat, usage.amount_msat);
1786 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1794 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1795 if let Some(expectations) = &mut self.event_expectations {
1796 match expectations.pop_front() {
1797 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1798 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1799 assert_eq!(actual_short_channel_id, short_channel_id);
1801 Some(TestResult::PaymentSuccess { path }) => {
1802 panic!("Unexpected successful payment path: {:?}", path)
1804 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1809 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1810 if let Some(expectations) = &mut self.event_expectations {
1811 match expectations.pop_front() {
1812 Some(TestResult::PaymentFailure { path, .. }) => {
1813 panic!("Unexpected payment path failure: {:?}", path)
1815 Some(TestResult::PaymentSuccess { path }) => {
1816 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1818 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1823 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1824 if let Some(expectations) = &mut self.event_expectations {
1825 match expectations.pop_front() {
1826 Some(TestResult::PaymentFailure { path, .. }) => {
1827 panic!("Unexpected failed payment path: {:?}", path)
1829 Some(TestResult::PaymentSuccess { path }) => {
1830 panic!("Unexpected successful payment path: {:?}", path)
1832 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1836 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1837 if let Some(expectations) = &mut self.event_expectations {
1838 match expectations.pop_front() {
1839 Some(TestResult::PaymentFailure { path, .. }) => {
1840 panic!("Unexpected payment path failure: {:?}", path)
1842 Some(TestResult::PaymentSuccess { path }) => {
1843 panic!("Unexpected successful payment path: {:?}", path)
1845 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1851 impl Drop for TestScorer {
1852 fn drop(&mut self) {
1853 if std::thread::panicking() {
1857 if let Some(event_expectations) = &self.event_expectations {
1858 if !event_expectations.is_empty() {
1859 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1863 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1864 if !scorer_expectations.is_empty() {
1865 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1872 expectations: core::cell::RefCell<VecDeque<Amount>>,
1873 attempts: core::cell::RefCell<usize>,
1874 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1875 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1878 #[derive(Clone, Debug, PartialEq, Eq)]
1885 struct OnAttempt(usize);
1890 expectations: core::cell::RefCell::new(VecDeque::new()),
1891 attempts: core::cell::RefCell::new(0),
1892 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1893 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
1897 fn expect_send(self, value_msat: Amount) -> Self {
1898 self.expectations.borrow_mut().push_back(value_msat);
1902 fn fails_on_attempt(self, attempt: usize) -> Self {
1903 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
1904 self.fails_with(failure, OnAttempt(attempt))
1907 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
1908 self.fails_with(PaymentSendFailure::PartialFailure {
1909 results: results.unwrap_or(vec![]),
1910 failed_paths_retry: Some(retry),
1911 payment_id: PaymentId([1; 32]),
1915 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1916 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1920 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
1921 let mut attempts = self.attempts.borrow_mut();
1924 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1925 Some(failure) => Err(failure),
1930 fn check_value_msats(&self, actual_value_msats: Amount) {
1931 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1932 if let Some(expected_value_msats) = expected_value_msats {
1933 assert_eq!(actual_value_msats, expected_value_msats);
1935 panic!("Unexpected amount: {:?}", actual_value_msats);
1939 fn track_inflight_htlcs(&self, route: &Route) {
1940 for path in &route.paths {
1941 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
1945 fn fail_path(&self, path: &Vec<RouteHop>) {
1946 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
1948 if let Some(idx) = path_idx {
1949 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
1954 impl Drop for TestPayer {
1955 fn drop(&mut self) {
1956 if std::thread::panicking() {
1960 if !self.expectations.borrow().is_empty() {
1961 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1966 impl Payer for TestPayer {
1967 fn node_id(&self) -> PublicKey {
1968 let secp_ctx = Secp256k1::new();
1969 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1972 fn first_hops(&self) -> Vec<ChannelDetails> {
1977 &self, route: &Route, _payment_hash: PaymentHash,
1978 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
1979 ) -> Result<(), PaymentSendFailure> {
1980 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1981 self.track_inflight_htlcs(route);
1982 self.check_attempts()
1985 fn send_spontaneous_payment(
1986 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
1987 ) -> Result<(), PaymentSendFailure> {
1988 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1989 self.check_attempts()
1993 &self, route: &Route, _payment_id: PaymentId
1994 ) -> Result<(), PaymentSendFailure> {
1995 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1996 self.track_inflight_htlcs(route);
1997 self.check_attempts()
2000 fn abandon_payment(&self, _payment_id: PaymentId) { }
2002 fn inflight_htlcs(&self) -> InFlightHtlcs {
2003 let mut inflight_htlcs = InFlightHtlcs::new();
2004 for path in self.inflight_htlcs_paths.clone().into_inner() {
2005 inflight_htlcs.process_path(&path, self.node_id());
2011 // *** Full Featured Functional Tests with a Real ChannelManager ***
2012 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2014 impl Router for ManualRouter {
2016 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2017 _inflight_htlcs: &InFlightHtlcs
2018 ) -> Result<Route, LightningError> {
2019 self.0.borrow_mut().pop_front().unwrap()
2022 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2024 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2026 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2028 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2031 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2032 self.0.borrow_mut().push_back(result);
2035 impl Drop for ManualRouter {
2036 fn drop(&mut self) {
2037 if std::thread::panicking() {
2040 assert!(self.0.borrow_mut().is_empty());
2045 fn retry_multi_path_single_failed_payment() {
2046 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2047 let chanmon_cfgs = create_chanmon_cfgs(2);
2048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2050 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2052 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2053 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2054 let chans = nodes[0].node.list_usable_channels();
2055 let mut route = Route {
2058 pubkey: nodes[1].node.get_our_node_id(),
2059 node_features: nodes[1].node.node_features(),
2060 short_channel_id: chans[0].short_channel_id.unwrap(),
2061 channel_features: nodes[1].node.channel_features(),
2063 cltv_expiry_delta: 100,
2066 pubkey: nodes[1].node.get_our_node_id(),
2067 node_features: nodes[1].node.node_features(),
2068 short_channel_id: chans[1].short_channel_id.unwrap(),
2069 channel_features: nodes[1].node.channel_features(),
2070 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2071 cltv_expiry_delta: 100,
2074 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2076 let router = ManualRouter(RefCell::new(VecDeque::new()));
2077 router.expect_find_route(Ok(route.clone()));
2078 // On retry, split the payment across both channels.
2079 route.paths[0][0].fee_msat = 50_000_001;
2080 route.paths[1][0].fee_msat = 50_000_000;
2081 router.expect_find_route(Ok(route.clone()));
2083 let event_handler = |_: Event| { panic!(); };
2084 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2086 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2087 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2088 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2090 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2091 assert_eq!(htlc_msgs.len(), 2);
2092 check_added_monitors!(nodes[0], 2);
2096 fn immediate_retry_on_failure() {
2097 // Tests that we can/will retry immediately after a failure
2098 let chanmon_cfgs = create_chanmon_cfgs(2);
2099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2103 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2104 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2105 let chans = nodes[0].node.list_usable_channels();
2106 let mut route = Route {
2109 pubkey: nodes[1].node.get_our_node_id(),
2110 node_features: nodes[1].node.node_features(),
2111 short_channel_id: chans[0].short_channel_id.unwrap(),
2112 channel_features: nodes[1].node.channel_features(),
2113 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2114 cltv_expiry_delta: 100,
2117 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2119 let router = ManualRouter(RefCell::new(VecDeque::new()));
2120 router.expect_find_route(Ok(route.clone()));
2121 // On retry, split the payment across both channels.
2122 route.paths.push(route.paths[0].clone());
2123 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2124 route.paths[0][0].fee_msat = 50_000_000;
2125 route.paths[1][0].fee_msat = 50_000_001;
2126 router.expect_find_route(Ok(route.clone()));
2128 let event_handler = |_: Event| { panic!(); };
2129 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2131 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2132 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2133 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2135 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2136 assert_eq!(htlc_msgs.len(), 2);
2137 check_added_monitors!(nodes[0], 2);
2141 fn no_extra_retries_on_back_to_back_fail() {
2142 // In a previous release, we had a race where we may exceed the payment retry count if we
2143 // get two failures in a row with the second having `all_paths_failed` set.
2144 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2145 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2146 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2147 // pending which we will see later. Thus, when we previously removed the retry tracking map
2148 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2149 // retry entry even though more events for the same payment were still pending. This led to
2150 // us retrying a payment again even though we'd already given up on it.
2152 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2153 // is used to remove the payment retry counter entries instead. This tests for the specific
2154 // excess-retry case while also testing `PaymentFailed` generation.
2156 let chanmon_cfgs = create_chanmon_cfgs(3);
2157 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2158 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2159 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2161 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2162 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2164 let mut route = Route {
2167 pubkey: nodes[1].node.get_our_node_id(),
2168 node_features: nodes[1].node.node_features(),
2169 short_channel_id: chan_1_scid,
2170 channel_features: nodes[1].node.channel_features(),
2172 cltv_expiry_delta: 100,
2174 pubkey: nodes[2].node.get_our_node_id(),
2175 node_features: nodes[2].node.node_features(),
2176 short_channel_id: chan_2_scid,
2177 channel_features: nodes[2].node.channel_features(),
2178 fee_msat: 100_000_000,
2179 cltv_expiry_delta: 100,
2182 pubkey: nodes[1].node.get_our_node_id(),
2183 node_features: nodes[1].node.node_features(),
2184 short_channel_id: chan_1_scid,
2185 channel_features: nodes[2].node.channel_features(),
2187 cltv_expiry_delta: 100,
2189 pubkey: nodes[2].node.get_our_node_id(),
2190 node_features: nodes[2].node.node_features(),
2191 short_channel_id: chan_2_scid,
2192 channel_features: nodes[2].node.channel_features(),
2193 fee_msat: 100_000_000,
2194 cltv_expiry_delta: 100,
2197 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2199 let router = ManualRouter(RefCell::new(VecDeque::new()));
2200 router.expect_find_route(Ok(route.clone()));
2201 // On retry, we'll only be asked for one path
2202 route.paths.remove(1);
2203 router.expect_find_route(Ok(route.clone()));
2205 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2206 let event_handler = |event: Event| {
2207 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2208 event_checker(event);
2210 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2212 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2213 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2214 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2216 let htlc_updates = SendEvent::from_node(&nodes[0]);
2217 check_added_monitors!(nodes[0], 1);
2218 assert_eq!(htlc_updates.msgs.len(), 1);
2220 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2221 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2222 check_added_monitors!(nodes[1], 1);
2223 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2225 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2226 check_added_monitors!(nodes[0], 1);
2227 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2229 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2230 check_added_monitors!(nodes[0], 1);
2231 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2233 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2234 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2235 check_added_monitors!(nodes[1], 1);
2236 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2238 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2239 check_added_monitors!(nodes[1], 1);
2240 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2242 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2243 check_added_monitors!(nodes[0], 1);
2245 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2246 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2247 check_added_monitors!(nodes[0], 1);
2248 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2250 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2251 check_added_monitors!(nodes[1], 1);
2252 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2254 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2255 check_added_monitors!(nodes[1], 1);
2256 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2258 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2259 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2260 check_added_monitors!(nodes[0], 1);
2262 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2263 check_added_monitors!(nodes[0], 1);
2264 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2266 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2267 check_added_monitors!(nodes[1], 1);
2268 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2269 check_added_monitors!(nodes[1], 1);
2270 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2272 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2273 check_added_monitors!(nodes[0], 1);
2275 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2276 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2277 // with it set. The first event will use up the only retry we are allowed, with the second
2278 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2279 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2280 // if the final HTLC failed.
2281 expected_events.borrow_mut().push_back(&|ev: Event| {
2282 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2283 assert!(!payment_failed_permanently);
2284 assert!(all_paths_failed);
2285 } else { panic!("Unexpected event"); }
2287 nodes[0].node.process_pending_events(&invoice_payer);
2288 assert!(expected_events.borrow().is_empty());
2290 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2291 check_added_monitors!(nodes[0], 1);
2293 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2294 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2295 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2296 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2297 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2299 expected_events.borrow_mut().push_back(&|ev: Event| {
2300 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2301 assert!(!payment_failed_permanently);
2302 assert!(all_paths_failed);
2303 } else { panic!("Unexpected event"); }
2305 expected_events.borrow_mut().push_back(&|ev: Event| {
2306 if let Event::PaymentFailed { .. } = ev {
2307 } else { panic!("Unexpected event"); }
2309 nodes[0].node.process_pending_events(&invoice_payer);
2310 assert!(expected_events.borrow().is_empty());