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::channelmanager;
738 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
739 use lightning::ln::functional_test_utils::*;
740 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
741 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
742 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router, ScorerAccountingForInFlightHtlcs};
743 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
744 use lightning::util::test_utils::TestLogger;
745 use lightning::util::errors::APIError;
746 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
747 use secp256k1::{SecretKey, PublicKey, Secp256k1};
748 use std::cell::RefCell;
749 use std::collections::VecDeque;
750 use std::ops::DerefMut;
751 use std::time::{SystemTime, Duration};
752 use crate::time_utils::tests::SinceEpoch;
753 use crate::DEFAULT_EXPIRY_TIME;
755 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
756 let payment_hash = Sha256::hash(&payment_preimage.0);
757 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
759 InvoiceBuilder::new(Currency::Bitcoin)
760 .description("test".into())
761 .payment_hash(payment_hash)
762 .payment_secret(PaymentSecret([0; 32]))
763 .duration_since_epoch(duration_since_epoch())
764 .min_final_cltv_expiry(144)
765 .amount_milli_satoshis(128)
766 .build_signed(|hash| {
767 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
772 fn duration_since_epoch() -> Duration {
773 #[cfg(feature = "std")]
774 let duration_since_epoch =
775 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
776 #[cfg(not(feature = "std"))]
777 let duration_since_epoch = Duration::from_secs(1234567);
781 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
782 let payment_hash = Sha256::hash(&payment_preimage.0);
783 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
785 InvoiceBuilder::new(Currency::Bitcoin)
786 .description("test".into())
787 .payment_hash(payment_hash)
788 .payment_secret(PaymentSecret([0; 32]))
789 .duration_since_epoch(duration_since_epoch())
790 .min_final_cltv_expiry(144)
791 .build_signed(|hash| {
792 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
797 #[cfg(feature = "std")]
798 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
799 let payment_hash = Sha256::hash(&payment_preimage.0);
800 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
801 let duration = duration_since_epoch()
802 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
804 InvoiceBuilder::new(Currency::Bitcoin)
805 .description("test".into())
806 .payment_hash(payment_hash)
807 .payment_secret(PaymentSecret([0; 32]))
808 .duration_since_epoch(duration)
809 .min_final_cltv_expiry(144)
810 .amount_milli_satoshis(128)
811 .build_signed(|hash| {
812 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
817 fn pubkey() -> PublicKey {
818 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
822 fn pays_invoice_on_first_attempt() {
823 let event_handled = core::cell::RefCell::new(false);
824 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
826 let payment_preimage = PaymentPreimage([1; 32]);
827 let invoice = invoice(payment_preimage);
828 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
829 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
831 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
832 let router = TestRouter::new(TestScorer::new());
833 let logger = TestLogger::new();
835 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
837 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
838 assert_eq!(*payer.attempts.borrow(), 1);
840 invoice_payer.handle_event(Event::PaymentSent {
841 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
843 assert_eq!(*event_handled.borrow(), true);
844 assert_eq!(*payer.attempts.borrow(), 1);
848 fn pays_invoice_on_retry() {
849 let event_handled = core::cell::RefCell::new(false);
850 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
852 let payment_preimage = PaymentPreimage([1; 32]);
853 let invoice = invoice(payment_preimage);
854 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
855 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
857 let payer = TestPayer::new()
858 .expect_send(Amount::ForInvoice(final_value_msat))
859 .expect_send(Amount::OnRetry(final_value_msat / 2));
860 let router = TestRouter::new(TestScorer::new());
861 let logger = TestLogger::new();
863 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
865 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
866 assert_eq!(*payer.attempts.borrow(), 1);
868 let event = Event::PaymentPathFailed {
871 network_update: None,
872 payment_failed_permanently: false,
873 all_paths_failed: false,
874 path: TestRouter::path_for_value(final_value_msat),
875 short_channel_id: None,
876 retry: Some(TestRouter::retry_for_invoice(&invoice)),
878 invoice_payer.handle_event(event);
879 assert_eq!(*event_handled.borrow(), false);
880 assert_eq!(*payer.attempts.borrow(), 2);
882 invoice_payer.handle_event(Event::PaymentSent {
883 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
885 assert_eq!(*event_handled.borrow(), true);
886 assert_eq!(*payer.attempts.borrow(), 2);
890 fn pays_invoice_on_partial_failure() {
891 let event_handler = |_: Event| { panic!() };
893 let payment_preimage = PaymentPreimage([1; 32]);
894 let invoice = invoice(payment_preimage);
895 let retry = TestRouter::retry_for_invoice(&invoice);
896 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
898 let payer = TestPayer::new()
899 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
900 .fails_with_partial_failure(retry, OnAttempt(2), None)
901 .expect_send(Amount::ForInvoice(final_value_msat))
902 .expect_send(Amount::OnRetry(final_value_msat / 2))
903 .expect_send(Amount::OnRetry(final_value_msat / 2));
904 let router = TestRouter::new(TestScorer::new());
905 let logger = TestLogger::new();
907 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
909 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
913 fn retries_payment_path_for_unknown_payment() {
914 let event_handled = core::cell::RefCell::new(false);
915 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
917 let payment_preimage = PaymentPreimage([1; 32]);
918 let invoice = invoice(payment_preimage);
919 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
920 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
922 let payer = TestPayer::new()
923 .expect_send(Amount::OnRetry(final_value_msat / 2))
924 .expect_send(Amount::OnRetry(final_value_msat / 2));
925 let router = TestRouter::new(TestScorer::new());
926 let logger = TestLogger::new();
928 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
930 let payment_id = Some(PaymentId([1; 32]));
931 let event = Event::PaymentPathFailed {
934 network_update: None,
935 payment_failed_permanently: false,
936 all_paths_failed: false,
937 path: TestRouter::path_for_value(final_value_msat),
938 short_channel_id: None,
939 retry: Some(TestRouter::retry_for_invoice(&invoice)),
941 invoice_payer.handle_event(event.clone());
942 assert_eq!(*event_handled.borrow(), false);
943 assert_eq!(*payer.attempts.borrow(), 1);
945 invoice_payer.handle_event(event.clone());
946 assert_eq!(*event_handled.borrow(), false);
947 assert_eq!(*payer.attempts.borrow(), 2);
949 invoice_payer.handle_event(Event::PaymentSent {
950 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
952 assert_eq!(*event_handled.borrow(), true);
953 assert_eq!(*payer.attempts.borrow(), 2);
957 fn fails_paying_invoice_after_max_retry_counts() {
958 let event_handled = core::cell::RefCell::new(false);
959 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
961 let payment_preimage = PaymentPreimage([1; 32]);
962 let invoice = invoice(payment_preimage);
963 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
965 let payer = TestPayer::new()
966 .expect_send(Amount::ForInvoice(final_value_msat))
967 .expect_send(Amount::OnRetry(final_value_msat / 2))
968 .expect_send(Amount::OnRetry(final_value_msat / 2));
969 let router = TestRouter::new(TestScorer::new());
970 let logger = TestLogger::new();
972 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
974 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
975 assert_eq!(*payer.attempts.borrow(), 1);
977 let event = Event::PaymentPathFailed {
979 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
980 network_update: None,
981 payment_failed_permanently: false,
982 all_paths_failed: true,
983 path: TestRouter::path_for_value(final_value_msat),
984 short_channel_id: None,
985 retry: Some(TestRouter::retry_for_invoice(&invoice)),
987 invoice_payer.handle_event(event);
988 assert_eq!(*event_handled.borrow(), false);
989 assert_eq!(*payer.attempts.borrow(), 2);
991 let event = Event::PaymentPathFailed {
993 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
994 network_update: None,
995 payment_failed_permanently: false,
996 all_paths_failed: false,
997 path: TestRouter::path_for_value(final_value_msat / 2),
998 short_channel_id: None,
999 retry: Some(RouteParameters {
1000 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1003 invoice_payer.handle_event(event.clone());
1004 assert_eq!(*event_handled.borrow(), false);
1005 assert_eq!(*payer.attempts.borrow(), 3);
1007 invoice_payer.handle_event(event.clone());
1008 assert_eq!(*event_handled.borrow(), true);
1009 assert_eq!(*payer.attempts.borrow(), 3);
1012 #[cfg(feature = "std")]
1014 fn fails_paying_invoice_after_max_retry_timeout() {
1015 let event_handled = core::cell::RefCell::new(false);
1016 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1018 let payment_preimage = PaymentPreimage([1; 32]);
1019 let invoice = invoice(payment_preimage);
1020 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1022 let payer = TestPayer::new()
1023 .expect_send(Amount::ForInvoice(final_value_msat))
1024 .expect_send(Amount::OnRetry(final_value_msat / 2));
1026 let router = TestRouter::new(TestScorer::new());
1027 let logger = TestLogger::new();
1028 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1031 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1033 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1034 assert_eq!(*payer.attempts.borrow(), 1);
1036 let event = Event::PaymentPathFailed {
1038 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1039 network_update: None,
1040 payment_failed_permanently: false,
1041 all_paths_failed: true,
1042 path: TestRouter::path_for_value(final_value_msat),
1043 short_channel_id: None,
1044 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1046 invoice_payer.handle_event(event.clone());
1047 assert_eq!(*event_handled.borrow(), false);
1048 assert_eq!(*payer.attempts.borrow(), 2);
1050 SinceEpoch::advance(Duration::from_secs(121));
1052 invoice_payer.handle_event(event.clone());
1053 assert_eq!(*event_handled.borrow(), true);
1054 assert_eq!(*payer.attempts.borrow(), 2);
1058 fn fails_paying_invoice_with_missing_retry_params() {
1059 let event_handled = core::cell::RefCell::new(false);
1060 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1062 let payment_preimage = PaymentPreimage([1; 32]);
1063 let invoice = invoice(payment_preimage);
1064 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1066 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1067 let router = TestRouter::new(TestScorer::new());
1068 let logger = TestLogger::new();
1070 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1072 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1073 assert_eq!(*payer.attempts.borrow(), 1);
1075 let event = Event::PaymentPathFailed {
1077 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1078 network_update: None,
1079 payment_failed_permanently: false,
1080 all_paths_failed: false,
1082 short_channel_id: None,
1085 invoice_payer.handle_event(event);
1086 assert_eq!(*event_handled.borrow(), true);
1087 assert_eq!(*payer.attempts.borrow(), 1);
1090 // Expiration is checked only in an std environment
1091 #[cfg(feature = "std")]
1093 fn fails_paying_invoice_after_expiration() {
1094 let event_handled = core::cell::RefCell::new(false);
1095 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1097 let payer = TestPayer::new();
1098 let router = TestRouter::new(TestScorer::new());
1099 let logger = TestLogger::new();
1101 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1103 let payment_preimage = PaymentPreimage([1; 32]);
1104 let invoice = expired_invoice(payment_preimage);
1105 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1106 assert_eq!(msg, "Invoice expired prior to send");
1107 } else { panic!("Expected Invoice Error"); }
1110 // Expiration is checked only in an std environment
1111 #[cfg(feature = "std")]
1113 fn fails_retrying_invoice_after_expiration() {
1114 let event_handled = core::cell::RefCell::new(false);
1115 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1117 let payment_preimage = PaymentPreimage([1; 32]);
1118 let invoice = invoice(payment_preimage);
1119 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1121 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1122 let router = TestRouter::new(TestScorer::new());
1123 let logger = TestLogger::new();
1125 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1127 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1128 assert_eq!(*payer.attempts.borrow(), 1);
1130 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1131 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1132 .checked_sub(Duration::from_secs(2)).unwrap()
1133 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1134 let event = Event::PaymentPathFailed {
1136 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1137 network_update: None,
1138 payment_failed_permanently: false,
1139 all_paths_failed: false,
1141 short_channel_id: None,
1142 retry: Some(retry_data),
1144 invoice_payer.handle_event(event);
1145 assert_eq!(*event_handled.borrow(), true);
1146 assert_eq!(*payer.attempts.borrow(), 1);
1150 fn fails_paying_invoice_after_retry_error() {
1151 let event_handled = core::cell::RefCell::new(false);
1152 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1154 let payment_preimage = PaymentPreimage([1; 32]);
1155 let invoice = invoice(payment_preimage);
1156 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1158 let payer = TestPayer::new()
1159 .fails_on_attempt(2)
1160 .expect_send(Amount::ForInvoice(final_value_msat))
1161 .expect_send(Amount::OnRetry(final_value_msat / 2));
1162 let router = TestRouter::new(TestScorer::new());
1163 let logger = TestLogger::new();
1165 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1167 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1168 assert_eq!(*payer.attempts.borrow(), 1);
1170 let event = Event::PaymentPathFailed {
1172 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1173 network_update: None,
1174 payment_failed_permanently: false,
1175 all_paths_failed: false,
1176 path: TestRouter::path_for_value(final_value_msat / 2),
1177 short_channel_id: None,
1178 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1180 invoice_payer.handle_event(event);
1181 assert_eq!(*event_handled.borrow(), true);
1182 assert_eq!(*payer.attempts.borrow(), 2);
1186 fn fails_paying_invoice_after_rejected_by_payee() {
1187 let event_handled = core::cell::RefCell::new(false);
1188 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1190 let payment_preimage = PaymentPreimage([1; 32]);
1191 let invoice = invoice(payment_preimage);
1192 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1194 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1195 let router = TestRouter::new(TestScorer::new());
1196 let logger = TestLogger::new();
1198 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1200 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1201 assert_eq!(*payer.attempts.borrow(), 1);
1203 let event = Event::PaymentPathFailed {
1205 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1206 network_update: None,
1207 payment_failed_permanently: true,
1208 all_paths_failed: false,
1210 short_channel_id: None,
1211 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1213 invoice_payer.handle_event(event);
1214 assert_eq!(*event_handled.borrow(), true);
1215 assert_eq!(*payer.attempts.borrow(), 1);
1219 fn fails_repaying_invoice_with_pending_payment() {
1220 let event_handled = core::cell::RefCell::new(false);
1221 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1223 let payment_preimage = PaymentPreimage([1; 32]);
1224 let invoice = invoice(payment_preimage);
1225 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1227 let payer = TestPayer::new()
1228 .expect_send(Amount::ForInvoice(final_value_msat))
1229 .expect_send(Amount::ForInvoice(final_value_msat));
1230 let router = TestRouter::new(TestScorer::new());
1231 let logger = TestLogger::new();
1233 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1235 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1237 // Cannot repay an invoice pending payment.
1238 match invoice_payer.pay_invoice(&invoice) {
1239 Err(PaymentError::Invoice("payment pending")) => {},
1240 Err(_) => panic!("unexpected error"),
1241 Ok(_) => panic!("expected invoice error"),
1244 // Can repay an invoice once cleared from cache.
1245 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1246 invoice_payer.remove_cached_payment(&payment_hash);
1247 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1249 // Cannot retry paying an invoice if cleared from cache.
1250 invoice_payer.remove_cached_payment(&payment_hash);
1251 let event = Event::PaymentPathFailed {
1254 network_update: None,
1255 payment_failed_permanently: false,
1256 all_paths_failed: false,
1258 short_channel_id: None,
1259 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1261 invoice_payer.handle_event(event);
1262 assert_eq!(*event_handled.borrow(), true);
1266 fn fails_paying_invoice_with_routing_errors() {
1267 let payer = TestPayer::new();
1268 let router = FailingRouter {};
1269 let logger = TestLogger::new();
1271 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1273 let payment_preimage = PaymentPreimage([1; 32]);
1274 let invoice = invoice(payment_preimage);
1275 match invoice_payer.pay_invoice(&invoice) {
1276 Err(PaymentError::Routing(_)) => {},
1277 Err(_) => panic!("unexpected error"),
1278 Ok(_) => panic!("expected routing error"),
1283 fn fails_paying_invoice_with_sending_errors() {
1284 let payment_preimage = PaymentPreimage([1; 32]);
1285 let invoice = invoice(payment_preimage);
1286 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1288 let payer = TestPayer::new()
1289 .fails_on_attempt(1)
1290 .expect_send(Amount::ForInvoice(final_value_msat));
1291 let router = TestRouter::new(TestScorer::new());
1292 let logger = TestLogger::new();
1294 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1296 match invoice_payer.pay_invoice(&invoice) {
1297 Err(PaymentError::Sending(_)) => {},
1298 Err(_) => panic!("unexpected error"),
1299 Ok(_) => panic!("expected sending error"),
1304 fn pays_zero_value_invoice_using_amount() {
1305 let event_handled = core::cell::RefCell::new(false);
1306 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1308 let payment_preimage = PaymentPreimage([1; 32]);
1309 let invoice = zero_value_invoice(payment_preimage);
1310 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1311 let final_value_msat = 100;
1313 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1314 let router = TestRouter::new(TestScorer::new());
1315 let logger = TestLogger::new();
1317 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1320 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1321 assert_eq!(*payer.attempts.borrow(), 1);
1323 invoice_payer.handle_event(Event::PaymentSent {
1324 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1326 assert_eq!(*event_handled.borrow(), true);
1327 assert_eq!(*payer.attempts.borrow(), 1);
1331 fn fails_paying_zero_value_invoice_with_amount() {
1332 let event_handled = core::cell::RefCell::new(false);
1333 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1335 let payer = TestPayer::new();
1336 let router = TestRouter::new(TestScorer::new());
1337 let logger = TestLogger::new();
1339 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1341 let payment_preimage = PaymentPreimage([1; 32]);
1342 let invoice = invoice(payment_preimage);
1344 // Cannot repay an invoice pending payment.
1345 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1346 Err(PaymentError::Invoice("amount unexpected")) => {},
1347 Err(_) => panic!("unexpected error"),
1348 Ok(_) => panic!("expected invoice error"),
1353 fn pays_pubkey_with_amount() {
1354 let event_handled = core::cell::RefCell::new(false);
1355 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1357 let pubkey = pubkey();
1358 let payment_preimage = PaymentPreimage([1; 32]);
1359 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1360 let final_value_msat = 100;
1361 let final_cltv_expiry_delta = 42;
1363 let payer = TestPayer::new()
1364 .expect_send(Amount::Spontaneous(final_value_msat))
1365 .expect_send(Amount::OnRetry(final_value_msat));
1366 let router = TestRouter::new(TestScorer::new());
1367 let logger = TestLogger::new();
1369 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1371 let payment_id = Some(invoice_payer.pay_pubkey(
1372 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1374 assert_eq!(*payer.attempts.borrow(), 1);
1376 let retry = RouteParameters {
1377 payment_params: PaymentParameters::for_keysend(pubkey),
1379 final_cltv_expiry_delta,
1381 let event = Event::PaymentPathFailed {
1384 network_update: None,
1385 payment_failed_permanently: false,
1386 all_paths_failed: false,
1388 short_channel_id: None,
1391 invoice_payer.handle_event(event);
1392 assert_eq!(*event_handled.borrow(), false);
1393 assert_eq!(*payer.attempts.borrow(), 2);
1395 invoice_payer.handle_event(Event::PaymentSent {
1396 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1398 assert_eq!(*event_handled.borrow(), true);
1399 assert_eq!(*payer.attempts.borrow(), 2);
1403 fn scores_failed_channel() {
1404 let event_handled = core::cell::RefCell::new(false);
1405 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1407 let payment_preimage = PaymentPreimage([1; 32]);
1408 let invoice = invoice(payment_preimage);
1409 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1410 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1411 let path = TestRouter::path_for_value(final_value_msat);
1412 let short_channel_id = Some(path[0].short_channel_id);
1414 // Expect that scorer is given short_channel_id upon handling the event.
1415 let payer = TestPayer::new()
1416 .expect_send(Amount::ForInvoice(final_value_msat))
1417 .expect_send(Amount::OnRetry(final_value_msat / 2));
1418 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1419 path: path.clone(), short_channel_id: path[0].short_channel_id,
1421 let router = TestRouter::new(scorer);
1422 let logger = TestLogger::new();
1424 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1426 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1427 let event = Event::PaymentPathFailed {
1430 network_update: None,
1431 payment_failed_permanently: false,
1432 all_paths_failed: false,
1435 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1437 invoice_payer.handle_event(event);
1441 fn scores_successful_channels() {
1442 let event_handled = core::cell::RefCell::new(false);
1443 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1445 let payment_preimage = PaymentPreimage([1; 32]);
1446 let invoice = invoice(payment_preimage);
1447 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1448 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1449 let route = TestRouter::route_for_value(final_value_msat);
1451 // Expect that scorer is given short_channel_id upon handling the event.
1452 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1453 let scorer = TestScorer::new()
1454 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1455 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1456 let router = TestRouter::new(scorer);
1457 let logger = TestLogger::new();
1459 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1461 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1462 let event = Event::PaymentPathSuccessful {
1463 payment_id, payment_hash, path: route.paths[0].clone()
1465 invoice_payer.handle_event(event);
1466 let event = Event::PaymentPathSuccessful {
1467 payment_id, payment_hash, path: route.paths[1].clone()
1469 invoice_payer.handle_event(event);
1473 fn considers_inflight_htlcs_between_invoice_payments() {
1474 let event_handled = core::cell::RefCell::new(false);
1475 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1477 let payment_preimage = PaymentPreimage([1; 32]);
1478 let payment_invoice = invoice(payment_preimage);
1479 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1481 let payer = TestPayer::new()
1482 .expect_send(Amount::ForInvoice(final_value_msat))
1483 .expect_send(Amount::ForInvoice(final_value_msat));
1484 let scorer = TestScorer::new()
1485 // 1st invoice, 1st path
1486 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1487 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1488 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1489 // 1st invoice, 2nd path
1490 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1491 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1492 // 2nd invoice, 1st path
1493 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1494 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1495 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1496 // 2nd invoice, 2nd path
1497 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1498 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1499 let router = TestRouter::new(scorer);
1500 let logger = TestLogger::new();
1502 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1504 // Make first invoice payment.
1505 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1507 // Let's pay a second invoice that will be using the same path. This should trigger the
1508 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1510 let payment_preimage_2 = PaymentPreimage([2; 32]);
1511 let payment_invoice_2 = invoice(payment_preimage_2);
1512 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1516 fn considers_inflight_htlcs_between_retries() {
1517 // First, let's just send a payment through, but only make sure one of the path completes
1518 let event_handled = core::cell::RefCell::new(false);
1519 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1521 let payment_preimage = PaymentPreimage([1; 32]);
1522 let payment_invoice = invoice(payment_preimage);
1523 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1524 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1526 let payer = TestPayer::new()
1527 .expect_send(Amount::ForInvoice(final_value_msat))
1528 .expect_send(Amount::OnRetry(final_value_msat / 2))
1529 .expect_send(Amount::OnRetry(final_value_msat / 4));
1530 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1531 let scorer = TestScorer::new()
1532 // 1st invoice, 1st path
1533 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1534 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1535 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1536 // 1st invoice, 2nd path
1537 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1538 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1539 // Retry 1, 1st path
1540 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1541 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1542 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1543 // Retry 1, 2nd path
1544 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1545 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1546 // Retry 2, 1st path
1547 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1548 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1549 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1550 // Retry 2, 2nd path
1551 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1552 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1553 let router = TestRouter::new(scorer);
1554 let logger = TestLogger::new();
1556 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1558 // Fail 1st path, leave 2nd path inflight
1559 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1560 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1561 invoice_payer.handle_event(Event::PaymentPathFailed {
1564 network_update: None,
1565 payment_failed_permanently: false,
1566 all_paths_failed: false,
1567 path: TestRouter::path_for_value(final_value_msat),
1568 short_channel_id: None,
1569 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1572 // Fails again the 1st path of our retry
1573 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1574 invoice_payer.handle_event(Event::PaymentPathFailed {
1577 network_update: None,
1578 payment_failed_permanently: false,
1579 all_paths_failed: false,
1580 path: TestRouter::path_for_value(final_value_msat / 2),
1581 short_channel_id: None,
1582 retry: Some(RouteParameters {
1583 final_value_msat: final_value_msat / 4,
1584 ..TestRouter::retry_for_invoice(&payment_invoice)
1590 scorer: RefCell<TestScorer>,
1594 fn new(scorer: TestScorer) -> Self {
1595 TestRouter { scorer: RefCell::new(scorer) }
1598 fn route_for_value(final_value_msat: u64) -> Route {
1603 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1604 channel_features: ChannelFeatures::empty(),
1605 node_features: NodeFeatures::empty(),
1606 short_channel_id: 0,
1608 cltv_expiry_delta: 0
1611 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1612 channel_features: ChannelFeatures::empty(),
1613 node_features: NodeFeatures::empty(),
1614 short_channel_id: 1,
1616 cltv_expiry_delta: 0
1619 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1620 channel_features: ChannelFeatures::empty(),
1621 node_features: NodeFeatures::empty(),
1622 short_channel_id: 2,
1623 fee_msat: final_value_msat / 2,
1624 cltv_expiry_delta: 0
1629 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1630 channel_features: ChannelFeatures::empty(),
1631 node_features: NodeFeatures::empty(),
1632 short_channel_id: 3,
1634 cltv_expiry_delta: 144
1637 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1638 channel_features: ChannelFeatures::empty(),
1639 node_features: NodeFeatures::empty(),
1640 short_channel_id: 4,
1641 fee_msat: final_value_msat / 2,
1642 cltv_expiry_delta: 144
1646 payment_params: None,
1650 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1651 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1654 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1655 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1656 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1657 .with_route_hints(invoice.route_hints());
1658 if let Some(features) = invoice.features() {
1659 payment_params = payment_params.with_features(features.clone());
1661 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1665 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1670 impl Router for TestRouter {
1672 &self, payer: &PublicKey, route_params: &RouteParameters,
1673 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1674 ) -> Result<Route, LightningError> {
1675 // Simulate calling the Scorer just as you would in find_route
1676 let route = Self::route_for_value(route_params.final_value_msat);
1677 let mut locked_scorer = self.scorer.lock();
1678 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1679 for path in route.paths {
1680 let mut aggregate_msat = 0u64;
1681 for (idx, hop) in path.iter().rev().enumerate() {
1682 aggregate_msat += hop.fee_msat;
1683 let usage = ChannelUsage {
1684 amount_msat: aggregate_msat,
1685 inflight_htlc_msat: 0,
1686 effective_capacity: EffectiveCapacity::Unknown,
1689 // Since the path is reversed, the last element in our iteration is the first
1691 if idx == path.len() - 1 {
1692 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1694 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1700 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1704 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1705 self.scorer.lock().payment_path_failed(path, short_channel_id);
1708 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1709 self.scorer.lock().payment_path_successful(path);
1712 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1713 self.scorer.lock().probe_successful(path);
1716 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1717 self.scorer.lock().probe_failed(path, short_channel_id);
1721 struct FailingRouter;
1723 impl Router for FailingRouter {
1725 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1726 _inflight_htlcs: InFlightHtlcs,
1727 ) -> Result<Route, LightningError> {
1728 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1731 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1733 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1735 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1737 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1741 event_expectations: Option<VecDeque<TestResult>>,
1742 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1747 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1748 PaymentSuccess { path: Vec<RouteHop> },
1754 event_expectations: None,
1755 scorer_expectations: RefCell::new(None),
1759 fn expect(mut self, expectation: TestResult) -> Self {
1760 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1764 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1765 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1771 impl lightning::util::ser::Writeable for TestScorer {
1772 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1775 impl Score for TestScorer {
1776 fn channel_penalty_msat(
1777 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1779 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1780 match scorer_expectations.pop_front() {
1781 Some(expectation) => {
1782 assert_eq!(expectation.amount_msat, usage.amount_msat);
1783 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1791 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1792 if let Some(expectations) = &mut self.event_expectations {
1793 match expectations.pop_front() {
1794 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1795 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1796 assert_eq!(actual_short_channel_id, short_channel_id);
1798 Some(TestResult::PaymentSuccess { path }) => {
1799 panic!("Unexpected successful payment path: {:?}", path)
1801 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1806 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1807 if let Some(expectations) = &mut self.event_expectations {
1808 match expectations.pop_front() {
1809 Some(TestResult::PaymentFailure { path, .. }) => {
1810 panic!("Unexpected payment path failure: {:?}", path)
1812 Some(TestResult::PaymentSuccess { path }) => {
1813 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1815 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1820 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1821 if let Some(expectations) = &mut self.event_expectations {
1822 match expectations.pop_front() {
1823 Some(TestResult::PaymentFailure { path, .. }) => {
1824 panic!("Unexpected failed payment path: {:?}", path)
1826 Some(TestResult::PaymentSuccess { path }) => {
1827 panic!("Unexpected successful payment path: {:?}", path)
1829 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1833 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1834 if let Some(expectations) = &mut self.event_expectations {
1835 match expectations.pop_front() {
1836 Some(TestResult::PaymentFailure { path, .. }) => {
1837 panic!("Unexpected payment path failure: {:?}", path)
1839 Some(TestResult::PaymentSuccess { path }) => {
1840 panic!("Unexpected successful payment path: {:?}", path)
1842 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1848 impl Drop for TestScorer {
1849 fn drop(&mut self) {
1850 if std::thread::panicking() {
1854 if let Some(event_expectations) = &self.event_expectations {
1855 if !event_expectations.is_empty() {
1856 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1860 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1861 if !scorer_expectations.is_empty() {
1862 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1869 expectations: core::cell::RefCell<VecDeque<Amount>>,
1870 attempts: core::cell::RefCell<usize>,
1871 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1872 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1875 #[derive(Clone, Debug, PartialEq, Eq)]
1882 struct OnAttempt(usize);
1887 expectations: core::cell::RefCell::new(VecDeque::new()),
1888 attempts: core::cell::RefCell::new(0),
1889 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1890 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
1894 fn expect_send(self, value_msat: Amount) -> Self {
1895 self.expectations.borrow_mut().push_back(value_msat);
1899 fn fails_on_attempt(self, attempt: usize) -> Self {
1900 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
1901 self.fails_with(failure, OnAttempt(attempt))
1904 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
1905 self.fails_with(PaymentSendFailure::PartialFailure {
1906 results: results.unwrap_or(vec![]),
1907 failed_paths_retry: Some(retry),
1908 payment_id: PaymentId([1; 32]),
1912 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1913 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1917 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
1918 let mut attempts = self.attempts.borrow_mut();
1921 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1922 Some(failure) => Err(failure),
1927 fn check_value_msats(&self, actual_value_msats: Amount) {
1928 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1929 if let Some(expected_value_msats) = expected_value_msats {
1930 assert_eq!(actual_value_msats, expected_value_msats);
1932 panic!("Unexpected amount: {:?}", actual_value_msats);
1936 fn track_inflight_htlcs(&self, route: &Route) {
1937 for path in &route.paths {
1938 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
1942 fn fail_path(&self, path: &Vec<RouteHop>) {
1943 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
1945 if let Some(idx) = path_idx {
1946 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
1951 impl Drop for TestPayer {
1952 fn drop(&mut self) {
1953 if std::thread::panicking() {
1957 if !self.expectations.borrow().is_empty() {
1958 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1963 impl Payer for TestPayer {
1964 fn node_id(&self) -> PublicKey {
1965 let secp_ctx = Secp256k1::new();
1966 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1969 fn first_hops(&self) -> Vec<ChannelDetails> {
1974 &self, route: &Route, _payment_hash: PaymentHash,
1975 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
1976 ) -> Result<(), PaymentSendFailure> {
1977 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1978 self.track_inflight_htlcs(route);
1979 self.check_attempts()
1982 fn send_spontaneous_payment(
1983 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
1984 ) -> Result<(), PaymentSendFailure> {
1985 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1986 self.check_attempts()
1990 &self, route: &Route, _payment_id: PaymentId
1991 ) -> Result<(), PaymentSendFailure> {
1992 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1993 self.track_inflight_htlcs(route);
1994 self.check_attempts()
1997 fn abandon_payment(&self, _payment_id: PaymentId) { }
1999 fn inflight_htlcs(&self) -> InFlightHtlcs {
2000 let mut inflight_htlcs = InFlightHtlcs::new();
2001 for path in self.inflight_htlcs_paths.clone().into_inner() {
2002 inflight_htlcs.process_path(&path, self.node_id());
2008 // *** Full Featured Functional Tests with a Real ChannelManager ***
2009 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2011 impl Router for ManualRouter {
2013 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2014 _inflight_htlcs: InFlightHtlcs
2015 ) -> Result<Route, LightningError> {
2016 self.0.borrow_mut().pop_front().unwrap()
2019 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2021 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2023 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2025 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2028 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2029 self.0.borrow_mut().push_back(result);
2032 impl Drop for ManualRouter {
2033 fn drop(&mut self) {
2034 if std::thread::panicking() {
2037 assert!(self.0.borrow_mut().is_empty());
2042 fn retry_multi_path_single_failed_payment() {
2043 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2044 let chanmon_cfgs = create_chanmon_cfgs(2);
2045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2047 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2049 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2050 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2051 let chans = nodes[0].node.list_usable_channels();
2052 let mut route = Route {
2055 pubkey: nodes[1].node.get_our_node_id(),
2056 node_features: channelmanager::provided_node_features(),
2057 short_channel_id: chans[0].short_channel_id.unwrap(),
2058 channel_features: channelmanager::provided_channel_features(),
2060 cltv_expiry_delta: 100,
2063 pubkey: nodes[1].node.get_our_node_id(),
2064 node_features: channelmanager::provided_node_features(),
2065 short_channel_id: chans[1].short_channel_id.unwrap(),
2066 channel_features: channelmanager::provided_channel_features(),
2067 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2068 cltv_expiry_delta: 100,
2071 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2073 let router = ManualRouter(RefCell::new(VecDeque::new()));
2074 router.expect_find_route(Ok(route.clone()));
2075 // On retry, split the payment across both channels.
2076 route.paths[0][0].fee_msat = 50_000_001;
2077 route.paths[1][0].fee_msat = 50_000_000;
2078 router.expect_find_route(Ok(route.clone()));
2080 let event_handler = |_: Event| { panic!(); };
2081 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2083 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2084 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2085 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2087 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2088 assert_eq!(htlc_msgs.len(), 2);
2089 check_added_monitors!(nodes[0], 2);
2093 fn immediate_retry_on_failure() {
2094 // Tests that we can/will retry immediately after a failure
2095 let chanmon_cfgs = create_chanmon_cfgs(2);
2096 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2097 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2098 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2100 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2101 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2102 let chans = nodes[0].node.list_usable_channels();
2103 let mut route = Route {
2106 pubkey: nodes[1].node.get_our_node_id(),
2107 node_features: channelmanager::provided_node_features(),
2108 short_channel_id: chans[0].short_channel_id.unwrap(),
2109 channel_features: channelmanager::provided_channel_features(),
2110 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2111 cltv_expiry_delta: 100,
2114 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2116 let router = ManualRouter(RefCell::new(VecDeque::new()));
2117 router.expect_find_route(Ok(route.clone()));
2118 // On retry, split the payment across both channels.
2119 route.paths.push(route.paths[0].clone());
2120 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2121 route.paths[0][0].fee_msat = 50_000_000;
2122 route.paths[1][0].fee_msat = 50_000_001;
2123 router.expect_find_route(Ok(route.clone()));
2125 let event_handler = |_: Event| { panic!(); };
2126 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2128 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2129 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2130 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2132 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2133 assert_eq!(htlc_msgs.len(), 2);
2134 check_added_monitors!(nodes[0], 2);
2138 fn no_extra_retries_on_back_to_back_fail() {
2139 // In a previous release, we had a race where we may exceed the payment retry count if we
2140 // get two failures in a row with the second having `all_paths_failed` set.
2141 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2142 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2143 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2144 // pending which we will see later. Thus, when we previously removed the retry tracking map
2145 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2146 // retry entry even though more events for the same payment were still pending. This led to
2147 // us retrying a payment again even though we'd already given up on it.
2149 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2150 // is used to remove the payment retry counter entries instead. This tests for the specific
2151 // excess-retry case while also testing `PaymentFailed` generation.
2153 let chanmon_cfgs = create_chanmon_cfgs(3);
2154 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2155 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2156 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2158 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2159 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features()).0.contents.short_channel_id;
2161 let mut route = Route {
2164 pubkey: nodes[1].node.get_our_node_id(),
2165 node_features: channelmanager::provided_node_features(),
2166 short_channel_id: chan_1_scid,
2167 channel_features: channelmanager::provided_channel_features(),
2169 cltv_expiry_delta: 100,
2171 pubkey: nodes[2].node.get_our_node_id(),
2172 node_features: channelmanager::provided_node_features(),
2173 short_channel_id: chan_2_scid,
2174 channel_features: channelmanager::provided_channel_features(),
2175 fee_msat: 100_000_000,
2176 cltv_expiry_delta: 100,
2179 pubkey: nodes[1].node.get_our_node_id(),
2180 node_features: channelmanager::provided_node_features(),
2181 short_channel_id: chan_1_scid,
2182 channel_features: channelmanager::provided_channel_features(),
2184 cltv_expiry_delta: 100,
2186 pubkey: nodes[2].node.get_our_node_id(),
2187 node_features: channelmanager::provided_node_features(),
2188 short_channel_id: chan_2_scid,
2189 channel_features: channelmanager::provided_channel_features(),
2190 fee_msat: 100_000_000,
2191 cltv_expiry_delta: 100,
2194 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2196 let router = ManualRouter(RefCell::new(VecDeque::new()));
2197 router.expect_find_route(Ok(route.clone()));
2198 // On retry, we'll only be asked for one path
2199 route.paths.remove(1);
2200 router.expect_find_route(Ok(route.clone()));
2202 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2203 let event_handler = |event: Event| {
2204 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2205 event_checker(event);
2207 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2209 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2210 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2211 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2213 let htlc_updates = SendEvent::from_node(&nodes[0]);
2214 check_added_monitors!(nodes[0], 1);
2215 assert_eq!(htlc_updates.msgs.len(), 1);
2217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2219 check_added_monitors!(nodes[1], 1);
2220 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2222 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2223 check_added_monitors!(nodes[0], 1);
2224 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2226 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2227 check_added_monitors!(nodes[0], 1);
2228 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2230 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2231 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2232 check_added_monitors!(nodes[1], 1);
2233 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2236 check_added_monitors!(nodes[1], 1);
2237 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2239 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2240 check_added_monitors!(nodes[0], 1);
2242 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2243 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2244 check_added_monitors!(nodes[0], 1);
2245 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2247 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2248 check_added_monitors!(nodes[1], 1);
2249 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2251 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2252 check_added_monitors!(nodes[1], 1);
2253 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2255 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2256 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2257 check_added_monitors!(nodes[0], 1);
2259 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2260 check_added_monitors!(nodes[0], 1);
2261 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2263 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2264 check_added_monitors!(nodes[1], 1);
2265 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2266 check_added_monitors!(nodes[1], 1);
2267 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2269 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2270 check_added_monitors!(nodes[0], 1);
2272 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2273 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2274 // with it set. The first event will use up the only retry we are allowed, with the second
2275 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2276 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2277 // if the final HTLC failed.
2278 expected_events.borrow_mut().push_back(&|ev: Event| {
2279 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2280 assert!(!payment_failed_permanently);
2281 assert!(all_paths_failed);
2282 } else { panic!("Unexpected event"); }
2284 nodes[0].node.process_pending_events(&invoice_payer);
2285 assert!(expected_events.borrow().is_empty());
2287 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2288 check_added_monitors!(nodes[0], 1);
2290 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2291 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2292 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2293 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2294 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2296 expected_events.borrow_mut().push_back(&|ev: Event| {
2297 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2298 assert!(!payment_failed_permanently);
2299 assert!(all_paths_failed);
2300 } else { panic!("Unexpected event"); }
2302 expected_events.borrow_mut().push_back(&|ev: Event| {
2303 if let Event::PaymentFailed { .. } = ev {
2304 } else { panic!("Unexpected event"); }
2306 nodes[0].node.process_pending_events(&invoice_payer);
2307 assert!(expected_events.borrow().is_empty());