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 invoice.min_final_cltv_expiry_delta() as u32)
427 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
428 .with_route_hints(invoice.route_hints());
429 if let Some(features) = invoice.features() {
430 payment_params = payment_params.with_features(features.clone());
432 let route_params = RouteParameters {
434 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
435 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
438 let send_payment = |route: &Route| {
439 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
442 self.pay_internal(&route_params, payment_hash, send_payment)
443 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
446 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
447 /// case a retry is needed.
449 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
450 /// as long as the payment is still pending. Once the payment completes or fails, you must
451 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
453 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
454 final_cltv_expiry_delta: u32
455 ) -> Result<PaymentId, PaymentError> {
456 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
457 let payment_id = PaymentId(payment_hash.0);
458 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
459 final_cltv_expiry_delta)
460 .map(|()| payment_id)
463 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
464 /// caching the invoice for later use in case a retry is needed.
466 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
467 /// payment completes or fails, no idempotency guarantees are made.
469 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
470 /// [`PaymentHash`] has never been paid before.
471 pub fn pay_pubkey_with_id(
472 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
473 amount_msats: u64, final_cltv_expiry_delta: u32
474 ) -> Result<(), PaymentError> {
475 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
476 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
477 final_cltv_expiry_delta)
481 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
482 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
483 ) -> Result<(), PaymentError> {
484 match self.payment_cache.lock().unwrap().entry(payment_hash) {
485 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
486 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
489 let route_params = RouteParameters {
490 payment_params: PaymentParameters::for_keysend(pubkey, final_cltv_expiry_delta),
491 final_value_msat: amount_msats,
492 final_cltv_expiry_delta,
495 let send_payment = |route: &Route| {
496 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
498 self.pay_internal(&route_params, payment_hash, send_payment)
499 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
502 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
503 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
504 ) -> Result<(), PaymentError> {
505 #[cfg(feature = "std")] {
506 if has_expired(params) {
507 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
508 return Err(PaymentError::Invoice("Invoice expired prior to send"));
512 let payer = self.payer.node_id();
513 let first_hops = self.payer.first_hops();
514 let inflight_htlcs = self.payer.inflight_htlcs();
515 let route = self.router.find_route(
516 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
517 ).map_err(|e| PaymentError::Routing(e))?;
519 match send_payment(&route) {
522 PaymentSendFailure::ParameterError(_) => Err(e),
523 PaymentSendFailure::PathParameterError(_) => Err(e),
524 PaymentSendFailure::DuplicatePayment => Err(e),
525 PaymentSendFailure::AllFailedResendSafe(_) => {
526 let mut payment_cache = self.payment_cache.lock().unwrap();
527 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
528 payment_attempts.count += 1;
529 if self.retry.is_retryable_now(payment_attempts) {
530 core::mem::drop(payment_cache);
531 Ok(self.pay_internal(params, payment_hash, send_payment)?)
536 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
537 if let Some(retry_data) = failed_paths_retry {
538 // Some paths were sent, even if we failed to send the full MPP value our
539 // recipient may misbehave and claim the funds, at which point we have to
540 // consider the payment sent, so return `Ok()` here, ignoring any retry
542 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
545 // This may happen if we send a payment and some paths fail, but
546 // only due to a temporary monitor failure or the like, implying
547 // they're really in-flight, but we haven't sent the initial
548 // HTLC-Add messages yet.
553 }.map_err(|e| PaymentError::Sending(e))
557 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
558 ) -> Result<(), ()> {
560 *self.payment_cache.lock().unwrap().entry(payment_hash)
561 .and_modify(|attempts| attempts.count += 1)
562 .or_insert(PaymentAttempts {
564 first_attempted_at: T::now()
567 if !self.retry.is_retryable_now(&attempts) {
568 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
572 #[cfg(feature = "std")] {
573 if has_expired(params) {
574 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
579 let payer = self.payer.node_id();
580 let first_hops = self.payer.first_hops();
581 let inflight_htlcs = self.payer.inflight_htlcs();
583 let route = self.router.find_route(
584 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
588 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
592 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
594 Err(PaymentSendFailure::ParameterError(_)) |
595 Err(PaymentSendFailure::PathParameterError(_)) => {
596 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
599 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
600 self.retry_payment(payment_id, payment_hash, params)
602 Err(PaymentSendFailure::DuplicatePayment) => {
603 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
606 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
607 if let Some(retry) = failed_paths_retry {
608 // Always return Ok for the same reason as noted in pay_internal.
609 let _ = self.retry_payment(payment_id, payment_hash, &retry);
616 /// Removes the payment cached by the given payment hash.
618 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
619 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
620 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
621 self.payment_cache.lock().unwrap().remove(payment_hash);
625 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
626 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
629 #[cfg(feature = "std")]
630 fn has_expired(route_params: &RouteParameters) -> bool {
631 if let Some(expiry_time) = route_params.payment_params.expiry_time {
632 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
636 impl<P: Deref, R: Deref, L: Deref, E: sealed::BaseEventHandler, T: Time>
637 InvoicePayerUsingTime<P, R, L, E, T>
643 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
645 fn handle_event_internal(&self, event: &Event) -> bool {
647 Event::PaymentPathFailed {
648 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
650 if let Some(short_channel_id) = short_channel_id {
651 let path = path.iter().collect::<Vec<_>>();
652 self.router.notify_payment_path_failed(&path, *short_channel_id)
655 if payment_id.is_none() {
656 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
657 } else if *payment_failed_permanently {
658 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
659 self.payer.abandon_payment(payment_id.unwrap());
660 } else if retry.is_none() {
661 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
662 self.payer.abandon_payment(payment_id.unwrap());
663 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
664 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
667 self.payer.abandon_payment(payment_id.unwrap());
670 Event::PaymentFailed { payment_hash, .. } => {
671 self.remove_cached_payment(&payment_hash);
673 Event::PaymentPathSuccessful { path, .. } => {
674 let path = path.iter().collect::<Vec<_>>();
675 self.router.notify_payment_path_successful(&path);
677 Event::PaymentSent { payment_hash, .. } => {
678 let mut payment_cache = self.payment_cache.lock().unwrap();
679 let attempts = payment_cache
680 .remove(payment_hash)
681 .map_or(1, |attempts| attempts.count + 1);
682 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
684 Event::ProbeSuccessful { payment_hash, path, .. } => {
685 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
686 let path = path.iter().collect::<Vec<_>>();
687 self.router.notify_payment_probe_successful(&path);
689 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
690 if let Some(short_channel_id) = short_channel_id {
691 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
692 let path = path.iter().collect::<Vec<_>>();
693 self.router.notify_payment_probe_failed(&path, *short_channel_id);
699 // Delegate to the decorated event handler unless the payment is retried.
704 impl<P: Deref, R: Deref, L: Deref, E: EventHandler, T: Time>
705 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
711 fn handle_event(&self, event: Event) {
712 let should_forward = self.handle_event_internal(&event);
714 self.event_handler.handle_event(event)
719 impl<P: Deref, R: Deref, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
720 InvoicePayerUsingTime<P, R, L, H, T>
726 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
727 /// handler, if necessary, to handle them asynchronously.
728 pub async fn handle_event_async(&self, event: Event) {
729 let should_forward = self.handle_event_internal(&event);
731 (self.event_handler)(event).await;
739 use crate::{InvoiceBuilder, Currency};
740 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
741 use bitcoin_hashes::sha256::Hash as Sha256;
742 use lightning::ln::PaymentPreimage;
743 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
744 use lightning::ln::functional_test_utils::*;
745 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
746 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
747 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router, ScorerAccountingForInFlightHtlcs};
748 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
749 use lightning::util::test_utils::TestLogger;
750 use lightning::util::errors::APIError;
751 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
752 use secp256k1::{SecretKey, PublicKey, Secp256k1};
753 use std::cell::RefCell;
754 use std::collections::VecDeque;
755 use std::time::{SystemTime, Duration};
756 use crate::time_utils::tests::SinceEpoch;
757 use crate::DEFAULT_EXPIRY_TIME;
759 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
760 let payment_hash = Sha256::hash(&payment_preimage.0);
761 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
763 InvoiceBuilder::new(Currency::Bitcoin)
764 .description("test".into())
765 .payment_hash(payment_hash)
766 .payment_secret(PaymentSecret([0; 32]))
767 .duration_since_epoch(duration_since_epoch())
768 .min_final_cltv_expiry_delta(144)
769 .amount_milli_satoshis(128)
770 .build_signed(|hash| {
771 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
776 fn duration_since_epoch() -> Duration {
777 #[cfg(feature = "std")]
778 let duration_since_epoch =
779 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
780 #[cfg(not(feature = "std"))]
781 let duration_since_epoch = Duration::from_secs(1234567);
785 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
786 let payment_hash = Sha256::hash(&payment_preimage.0);
787 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
789 InvoiceBuilder::new(Currency::Bitcoin)
790 .description("test".into())
791 .payment_hash(payment_hash)
792 .payment_secret(PaymentSecret([0; 32]))
793 .duration_since_epoch(duration_since_epoch())
794 .min_final_cltv_expiry_delta(144)
795 .build_signed(|hash| {
796 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
801 #[cfg(feature = "std")]
802 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
803 let payment_hash = Sha256::hash(&payment_preimage.0);
804 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
805 let duration = duration_since_epoch()
806 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
808 InvoiceBuilder::new(Currency::Bitcoin)
809 .description("test".into())
810 .payment_hash(payment_hash)
811 .payment_secret(PaymentSecret([0; 32]))
812 .duration_since_epoch(duration)
813 .min_final_cltv_expiry_delta(144)
814 .amount_milli_satoshis(128)
815 .build_signed(|hash| {
816 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
821 fn pubkey() -> PublicKey {
822 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
826 fn pays_invoice_on_first_attempt() {
827 let event_handled = core::cell::RefCell::new(false);
828 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
830 let payment_preimage = PaymentPreimage([1; 32]);
831 let invoice = invoice(payment_preimage);
832 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
833 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
835 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
836 let router = TestRouter::new(TestScorer::new());
837 let logger = TestLogger::new();
839 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
841 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
842 assert_eq!(*payer.attempts.borrow(), 1);
844 invoice_payer.handle_event(Event::PaymentSent {
845 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
847 assert_eq!(*event_handled.borrow(), true);
848 assert_eq!(*payer.attempts.borrow(), 1);
852 fn pays_invoice_on_retry() {
853 let event_handled = core::cell::RefCell::new(false);
854 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
856 let payment_preimage = PaymentPreimage([1; 32]);
857 let invoice = invoice(payment_preimage);
858 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
859 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
861 let payer = TestPayer::new()
862 .expect_send(Amount::ForInvoice(final_value_msat))
863 .expect_send(Amount::OnRetry(final_value_msat / 2));
864 let router = TestRouter::new(TestScorer::new());
865 let logger = TestLogger::new();
867 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
869 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
870 assert_eq!(*payer.attempts.borrow(), 1);
872 let event = Event::PaymentPathFailed {
875 network_update: None,
876 payment_failed_permanently: false,
877 all_paths_failed: false,
878 path: TestRouter::path_for_value(final_value_msat),
879 short_channel_id: None,
880 retry: Some(TestRouter::retry_for_invoice(&invoice)),
882 invoice_payer.handle_event(event);
883 assert_eq!(*event_handled.borrow(), false);
884 assert_eq!(*payer.attempts.borrow(), 2);
886 invoice_payer.handle_event(Event::PaymentSent {
887 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
889 assert_eq!(*event_handled.borrow(), true);
890 assert_eq!(*payer.attempts.borrow(), 2);
894 fn pays_invoice_on_partial_failure() {
895 let event_handler = |_: Event| { panic!() };
897 let payment_preimage = PaymentPreimage([1; 32]);
898 let invoice = invoice(payment_preimage);
899 let retry = TestRouter::retry_for_invoice(&invoice);
900 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
902 let payer = TestPayer::new()
903 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
904 .fails_with_partial_failure(retry, OnAttempt(2), None)
905 .expect_send(Amount::ForInvoice(final_value_msat))
906 .expect_send(Amount::OnRetry(final_value_msat / 2))
907 .expect_send(Amount::OnRetry(final_value_msat / 2));
908 let router = TestRouter::new(TestScorer::new());
909 let logger = TestLogger::new();
911 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
913 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
917 fn retries_payment_path_for_unknown_payment() {
918 let event_handled = core::cell::RefCell::new(false);
919 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
921 let payment_preimage = PaymentPreimage([1; 32]);
922 let invoice = invoice(payment_preimage);
923 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
924 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
926 let payer = TestPayer::new()
927 .expect_send(Amount::OnRetry(final_value_msat / 2))
928 .expect_send(Amount::OnRetry(final_value_msat / 2));
929 let router = TestRouter::new(TestScorer::new());
930 let logger = TestLogger::new();
932 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
934 let payment_id = Some(PaymentId([1; 32]));
935 let event = Event::PaymentPathFailed {
938 network_update: None,
939 payment_failed_permanently: false,
940 all_paths_failed: false,
941 path: TestRouter::path_for_value(final_value_msat),
942 short_channel_id: None,
943 retry: Some(TestRouter::retry_for_invoice(&invoice)),
945 invoice_payer.handle_event(event.clone());
946 assert_eq!(*event_handled.borrow(), false);
947 assert_eq!(*payer.attempts.borrow(), 1);
949 invoice_payer.handle_event(event.clone());
950 assert_eq!(*event_handled.borrow(), false);
951 assert_eq!(*payer.attempts.borrow(), 2);
953 invoice_payer.handle_event(Event::PaymentSent {
954 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
956 assert_eq!(*event_handled.borrow(), true);
957 assert_eq!(*payer.attempts.borrow(), 2);
961 fn fails_paying_invoice_after_max_retry_counts() {
962 let event_handled = core::cell::RefCell::new(false);
963 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
965 let payment_preimage = PaymentPreimage([1; 32]);
966 let invoice = invoice(payment_preimage);
967 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
969 let payer = TestPayer::new()
970 .expect_send(Amount::ForInvoice(final_value_msat))
971 .expect_send(Amount::OnRetry(final_value_msat / 2))
972 .expect_send(Amount::OnRetry(final_value_msat / 2));
973 let router = TestRouter::new(TestScorer::new());
974 let logger = TestLogger::new();
976 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
978 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
979 assert_eq!(*payer.attempts.borrow(), 1);
981 let event = Event::PaymentPathFailed {
983 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
984 network_update: None,
985 payment_failed_permanently: false,
986 all_paths_failed: true,
987 path: TestRouter::path_for_value(final_value_msat),
988 short_channel_id: None,
989 retry: Some(TestRouter::retry_for_invoice(&invoice)),
991 invoice_payer.handle_event(event);
992 assert_eq!(*event_handled.borrow(), false);
993 assert_eq!(*payer.attempts.borrow(), 2);
995 let event = Event::PaymentPathFailed {
997 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
998 network_update: None,
999 payment_failed_permanently: false,
1000 all_paths_failed: false,
1001 path: TestRouter::path_for_value(final_value_msat / 2),
1002 short_channel_id: None,
1003 retry: Some(RouteParameters {
1004 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1007 invoice_payer.handle_event(event.clone());
1008 assert_eq!(*event_handled.borrow(), false);
1009 assert_eq!(*payer.attempts.borrow(), 3);
1011 invoice_payer.handle_event(event.clone());
1012 assert_eq!(*event_handled.borrow(), true);
1013 assert_eq!(*payer.attempts.borrow(), 3);
1016 #[cfg(feature = "std")]
1018 fn fails_paying_invoice_after_max_retry_timeout() {
1019 let event_handled = core::cell::RefCell::new(false);
1020 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1022 let payment_preimage = PaymentPreimage([1; 32]);
1023 let invoice = invoice(payment_preimage);
1024 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1026 let payer = TestPayer::new()
1027 .expect_send(Amount::ForInvoice(final_value_msat))
1028 .expect_send(Amount::OnRetry(final_value_msat / 2));
1030 let router = TestRouter::new(TestScorer::new());
1031 let logger = TestLogger::new();
1032 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1035 InvoicePayerUsingSinceEpoch::new(&payer, &router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1037 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1038 assert_eq!(*payer.attempts.borrow(), 1);
1040 let event = Event::PaymentPathFailed {
1042 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1043 network_update: None,
1044 payment_failed_permanently: false,
1045 all_paths_failed: true,
1046 path: TestRouter::path_for_value(final_value_msat),
1047 short_channel_id: None,
1048 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1050 invoice_payer.handle_event(event.clone());
1051 assert_eq!(*event_handled.borrow(), false);
1052 assert_eq!(*payer.attempts.borrow(), 2);
1054 SinceEpoch::advance(Duration::from_secs(121));
1056 invoice_payer.handle_event(event.clone());
1057 assert_eq!(*event_handled.borrow(), true);
1058 assert_eq!(*payer.attempts.borrow(), 2);
1062 fn fails_paying_invoice_with_missing_retry_params() {
1063 let event_handled = core::cell::RefCell::new(false);
1064 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1066 let payment_preimage = PaymentPreimage([1; 32]);
1067 let invoice = invoice(payment_preimage);
1068 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1070 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1071 let router = TestRouter::new(TestScorer::new());
1072 let logger = TestLogger::new();
1074 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1076 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1077 assert_eq!(*payer.attempts.borrow(), 1);
1079 let event = Event::PaymentPathFailed {
1081 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1082 network_update: None,
1083 payment_failed_permanently: false,
1084 all_paths_failed: false,
1086 short_channel_id: None,
1089 invoice_payer.handle_event(event);
1090 assert_eq!(*event_handled.borrow(), true);
1091 assert_eq!(*payer.attempts.borrow(), 1);
1094 // Expiration is checked only in an std environment
1095 #[cfg(feature = "std")]
1097 fn fails_paying_invoice_after_expiration() {
1098 let event_handled = core::cell::RefCell::new(false);
1099 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1101 let payer = TestPayer::new();
1102 let router = TestRouter::new(TestScorer::new());
1103 let logger = TestLogger::new();
1105 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1107 let payment_preimage = PaymentPreimage([1; 32]);
1108 let invoice = expired_invoice(payment_preimage);
1109 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1110 assert_eq!(msg, "Invoice expired prior to send");
1111 } else { panic!("Expected Invoice Error"); }
1114 // Expiration is checked only in an std environment
1115 #[cfg(feature = "std")]
1117 fn fails_retrying_invoice_after_expiration() {
1118 let event_handled = core::cell::RefCell::new(false);
1119 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1121 let payment_preimage = PaymentPreimage([1; 32]);
1122 let invoice = invoice(payment_preimage);
1123 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1125 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1126 let router = TestRouter::new(TestScorer::new());
1127 let logger = TestLogger::new();
1129 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1131 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1132 assert_eq!(*payer.attempts.borrow(), 1);
1134 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1135 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1136 .checked_sub(Duration::from_secs(2)).unwrap()
1137 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1138 let event = Event::PaymentPathFailed {
1140 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1141 network_update: None,
1142 payment_failed_permanently: false,
1143 all_paths_failed: false,
1145 short_channel_id: None,
1146 retry: Some(retry_data),
1148 invoice_payer.handle_event(event);
1149 assert_eq!(*event_handled.borrow(), true);
1150 assert_eq!(*payer.attempts.borrow(), 1);
1154 fn fails_paying_invoice_after_retry_error() {
1155 let event_handled = core::cell::RefCell::new(false);
1156 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1158 let payment_preimage = PaymentPreimage([1; 32]);
1159 let invoice = invoice(payment_preimage);
1160 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1162 let payer = TestPayer::new()
1163 .fails_on_attempt(2)
1164 .expect_send(Amount::ForInvoice(final_value_msat))
1165 .expect_send(Amount::OnRetry(final_value_msat / 2));
1166 let router = TestRouter::new(TestScorer::new());
1167 let logger = TestLogger::new();
1169 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1171 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1172 assert_eq!(*payer.attempts.borrow(), 1);
1174 let event = Event::PaymentPathFailed {
1176 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1177 network_update: None,
1178 payment_failed_permanently: false,
1179 all_paths_failed: false,
1180 path: TestRouter::path_for_value(final_value_msat / 2),
1181 short_channel_id: None,
1182 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1184 invoice_payer.handle_event(event);
1185 assert_eq!(*event_handled.borrow(), true);
1186 assert_eq!(*payer.attempts.borrow(), 2);
1190 fn fails_paying_invoice_after_rejected_by_payee() {
1191 let event_handled = core::cell::RefCell::new(false);
1192 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1194 let payment_preimage = PaymentPreimage([1; 32]);
1195 let invoice = invoice(payment_preimage);
1196 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1198 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1199 let router = TestRouter::new(TestScorer::new());
1200 let logger = TestLogger::new();
1202 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1204 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1205 assert_eq!(*payer.attempts.borrow(), 1);
1207 let event = Event::PaymentPathFailed {
1209 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1210 network_update: None,
1211 payment_failed_permanently: true,
1212 all_paths_failed: false,
1214 short_channel_id: None,
1215 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1217 invoice_payer.handle_event(event);
1218 assert_eq!(*event_handled.borrow(), true);
1219 assert_eq!(*payer.attempts.borrow(), 1);
1223 fn fails_repaying_invoice_with_pending_payment() {
1224 let event_handled = core::cell::RefCell::new(false);
1225 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1227 let payment_preimage = PaymentPreimage([1; 32]);
1228 let invoice = invoice(payment_preimage);
1229 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1231 let payer = TestPayer::new()
1232 .expect_send(Amount::ForInvoice(final_value_msat))
1233 .expect_send(Amount::ForInvoice(final_value_msat));
1234 let router = TestRouter::new(TestScorer::new());
1235 let logger = TestLogger::new();
1237 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1239 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1241 // Cannot repay an invoice pending payment.
1242 match invoice_payer.pay_invoice(&invoice) {
1243 Err(PaymentError::Invoice("payment pending")) => {},
1244 Err(_) => panic!("unexpected error"),
1245 Ok(_) => panic!("expected invoice error"),
1248 // Can repay an invoice once cleared from cache.
1249 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1250 invoice_payer.remove_cached_payment(&payment_hash);
1251 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1253 // Cannot retry paying an invoice if cleared from cache.
1254 invoice_payer.remove_cached_payment(&payment_hash);
1255 let event = Event::PaymentPathFailed {
1258 network_update: None,
1259 payment_failed_permanently: false,
1260 all_paths_failed: false,
1262 short_channel_id: None,
1263 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1265 invoice_payer.handle_event(event);
1266 assert_eq!(*event_handled.borrow(), true);
1270 fn fails_paying_invoice_with_routing_errors() {
1271 let payer = TestPayer::new();
1272 let router = FailingRouter {};
1273 let logger = TestLogger::new();
1275 InvoicePayer::new(&payer, &router, &logger, |_: Event| {}, Retry::Attempts(0));
1277 let payment_preimage = PaymentPreimage([1; 32]);
1278 let invoice = invoice(payment_preimage);
1279 match invoice_payer.pay_invoice(&invoice) {
1280 Err(PaymentError::Routing(_)) => {},
1281 Err(_) => panic!("unexpected error"),
1282 Ok(_) => panic!("expected routing error"),
1287 fn fails_paying_invoice_with_sending_errors() {
1288 let payment_preimage = PaymentPreimage([1; 32]);
1289 let invoice = invoice(payment_preimage);
1290 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1292 let payer = TestPayer::new()
1293 .fails_on_attempt(1)
1294 .expect_send(Amount::ForInvoice(final_value_msat));
1295 let router = TestRouter::new(TestScorer::new());
1296 let logger = TestLogger::new();
1298 InvoicePayer::new(&payer, &router, &logger, |_: Event| {}, Retry::Attempts(0));
1300 match invoice_payer.pay_invoice(&invoice) {
1301 Err(PaymentError::Sending(_)) => {},
1302 Err(_) => panic!("unexpected error"),
1303 Ok(_) => panic!("expected sending error"),
1308 fn pays_zero_value_invoice_using_amount() {
1309 let event_handled = core::cell::RefCell::new(false);
1310 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1312 let payment_preimage = PaymentPreimage([1; 32]);
1313 let invoice = zero_value_invoice(payment_preimage);
1314 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1315 let final_value_msat = 100;
1317 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1318 let router = TestRouter::new(TestScorer::new());
1319 let logger = TestLogger::new();
1321 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1324 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1325 assert_eq!(*payer.attempts.borrow(), 1);
1327 invoice_payer.handle_event(Event::PaymentSent {
1328 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1330 assert_eq!(*event_handled.borrow(), true);
1331 assert_eq!(*payer.attempts.borrow(), 1);
1335 fn fails_paying_zero_value_invoice_with_amount() {
1336 let event_handled = core::cell::RefCell::new(false);
1337 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1339 let payer = TestPayer::new();
1340 let router = TestRouter::new(TestScorer::new());
1341 let logger = TestLogger::new();
1343 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1345 let payment_preimage = PaymentPreimage([1; 32]);
1346 let invoice = invoice(payment_preimage);
1348 // Cannot repay an invoice pending payment.
1349 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1350 Err(PaymentError::Invoice("amount unexpected")) => {},
1351 Err(_) => panic!("unexpected error"),
1352 Ok(_) => panic!("expected invoice error"),
1357 fn pays_pubkey_with_amount() {
1358 let event_handled = core::cell::RefCell::new(false);
1359 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1361 let pubkey = pubkey();
1362 let payment_preimage = PaymentPreimage([1; 32]);
1363 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1364 let final_value_msat = 100;
1365 let final_cltv_expiry_delta = 42;
1367 let payer = TestPayer::new()
1368 .expect_send(Amount::Spontaneous(final_value_msat))
1369 .expect_send(Amount::OnRetry(final_value_msat));
1370 let router = TestRouter::new(TestScorer::new());
1371 let logger = TestLogger::new();
1373 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1375 let payment_id = Some(invoice_payer.pay_pubkey(
1376 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1378 assert_eq!(*payer.attempts.borrow(), 1);
1380 let retry = RouteParameters {
1381 payment_params: PaymentParameters::for_keysend(pubkey, final_cltv_expiry_delta),
1383 final_cltv_expiry_delta,
1385 let event = Event::PaymentPathFailed {
1388 network_update: None,
1389 payment_failed_permanently: false,
1390 all_paths_failed: false,
1392 short_channel_id: None,
1395 invoice_payer.handle_event(event);
1396 assert_eq!(*event_handled.borrow(), false);
1397 assert_eq!(*payer.attempts.borrow(), 2);
1399 invoice_payer.handle_event(Event::PaymentSent {
1400 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1402 assert_eq!(*event_handled.borrow(), true);
1403 assert_eq!(*payer.attempts.borrow(), 2);
1407 fn scores_failed_channel() {
1408 let event_handled = core::cell::RefCell::new(false);
1409 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1411 let payment_preimage = PaymentPreimage([1; 32]);
1412 let invoice = invoice(payment_preimage);
1413 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1414 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1415 let path = TestRouter::path_for_value(final_value_msat);
1416 let short_channel_id = Some(path[0].short_channel_id);
1418 // Expect that scorer is given short_channel_id upon handling the event.
1419 let payer = TestPayer::new()
1420 .expect_send(Amount::ForInvoice(final_value_msat))
1421 .expect_send(Amount::OnRetry(final_value_msat / 2));
1422 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1423 path: path.clone(), short_channel_id: path[0].short_channel_id,
1425 let router = TestRouter::new(scorer);
1426 let logger = TestLogger::new();
1428 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1430 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1431 let event = Event::PaymentPathFailed {
1434 network_update: None,
1435 payment_failed_permanently: false,
1436 all_paths_failed: false,
1439 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1441 invoice_payer.handle_event(event);
1445 fn scores_successful_channels() {
1446 let event_handled = core::cell::RefCell::new(false);
1447 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1449 let payment_preimage = PaymentPreimage([1; 32]);
1450 let invoice = invoice(payment_preimage);
1451 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1452 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1453 let route = TestRouter::route_for_value(final_value_msat);
1455 // Expect that scorer is given short_channel_id upon handling the event.
1456 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1457 let scorer = TestScorer::new()
1458 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1459 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1460 let router = TestRouter::new(scorer);
1461 let logger = TestLogger::new();
1463 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1465 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1466 let event = Event::PaymentPathSuccessful {
1467 payment_id, payment_hash, path: route.paths[0].clone()
1469 invoice_payer.handle_event(event);
1470 let event = Event::PaymentPathSuccessful {
1471 payment_id, payment_hash, path: route.paths[1].clone()
1473 invoice_payer.handle_event(event);
1477 fn considers_inflight_htlcs_between_invoice_payments() {
1478 let event_handled = core::cell::RefCell::new(false);
1479 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1481 let payment_preimage = PaymentPreimage([1; 32]);
1482 let payment_invoice = invoice(payment_preimage);
1483 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1485 let payer = TestPayer::new()
1486 .expect_send(Amount::ForInvoice(final_value_msat))
1487 .expect_send(Amount::ForInvoice(final_value_msat));
1488 let scorer = TestScorer::new()
1489 // 1st invoice, 1st path
1490 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1491 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1492 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1493 // 1st invoice, 2nd path
1494 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1495 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1496 // 2nd invoice, 1st path
1497 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1498 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1499 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1500 // 2nd invoice, 2nd path
1501 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1502 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1503 let router = TestRouter::new(scorer);
1504 let logger = TestLogger::new();
1506 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(0));
1508 // Make first invoice payment.
1509 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1511 // Let's pay a second invoice that will be using the same path. This should trigger the
1512 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1514 let payment_preimage_2 = PaymentPreimage([2; 32]);
1515 let payment_invoice_2 = invoice(payment_preimage_2);
1516 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1520 fn considers_inflight_htlcs_between_retries() {
1521 // First, let's just send a payment through, but only make sure one of the path completes
1522 let event_handled = core::cell::RefCell::new(false);
1523 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1525 let payment_preimage = PaymentPreimage([1; 32]);
1526 let payment_invoice = invoice(payment_preimage);
1527 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1528 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1530 let payer = TestPayer::new()
1531 .expect_send(Amount::ForInvoice(final_value_msat))
1532 .expect_send(Amount::OnRetry(final_value_msat / 2))
1533 .expect_send(Amount::OnRetry(final_value_msat / 4));
1534 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1535 let scorer = TestScorer::new()
1536 // 1st invoice, 1st path
1537 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1538 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1539 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1540 // 1st invoice, 2nd path
1541 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1542 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1543 // Retry 1, 1st path
1544 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1545 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1546 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1547 // Retry 1, 2nd path
1548 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1549 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1550 // Retry 2, 1st path
1551 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1552 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1553 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1554 // Retry 2, 2nd path
1555 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1556 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1557 let router = TestRouter::new(scorer);
1558 let logger = TestLogger::new();
1560 InvoicePayer::new(&payer, &router, &logger, event_handler, Retry::Attempts(2));
1562 // Fail 1st path, leave 2nd path inflight
1563 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1564 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1565 invoice_payer.handle_event(Event::PaymentPathFailed {
1568 network_update: None,
1569 payment_failed_permanently: false,
1570 all_paths_failed: false,
1571 path: TestRouter::path_for_value(final_value_msat),
1572 short_channel_id: None,
1573 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1576 // Fails again the 1st path of our retry
1577 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1578 invoice_payer.handle_event(Event::PaymentPathFailed {
1581 network_update: None,
1582 payment_failed_permanently: false,
1583 all_paths_failed: false,
1584 path: TestRouter::path_for_value(final_value_msat / 2),
1585 short_channel_id: None,
1586 retry: Some(RouteParameters {
1587 final_value_msat: final_value_msat / 4,
1588 ..TestRouter::retry_for_invoice(&payment_invoice)
1594 scorer: RefCell<TestScorer>,
1598 fn new(scorer: TestScorer) -> Self {
1599 TestRouter { scorer: RefCell::new(scorer) }
1602 fn route_for_value(final_value_msat: u64) -> Route {
1607 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1608 channel_features: ChannelFeatures::empty(),
1609 node_features: NodeFeatures::empty(),
1610 short_channel_id: 0,
1612 cltv_expiry_delta: 0
1615 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1616 channel_features: ChannelFeatures::empty(),
1617 node_features: NodeFeatures::empty(),
1618 short_channel_id: 1,
1620 cltv_expiry_delta: 0
1623 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1624 channel_features: ChannelFeatures::empty(),
1625 node_features: NodeFeatures::empty(),
1626 short_channel_id: 2,
1627 fee_msat: final_value_msat / 2,
1628 cltv_expiry_delta: 0
1633 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1634 channel_features: ChannelFeatures::empty(),
1635 node_features: NodeFeatures::empty(),
1636 short_channel_id: 3,
1638 cltv_expiry_delta: 144
1641 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1642 channel_features: ChannelFeatures::empty(),
1643 node_features: NodeFeatures::empty(),
1644 short_channel_id: 4,
1645 fee_msat: final_value_msat / 2,
1646 cltv_expiry_delta: 144
1650 payment_params: None,
1654 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1655 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1658 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1659 let mut payment_params = PaymentParameters::from_node_id(
1660 invoice.recover_payee_pub_key(), invoice.min_final_cltv_expiry_delta() as u32)
1661 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1662 .with_route_hints(invoice.route_hints());
1663 if let Some(features) = invoice.features() {
1664 payment_params = payment_params.with_features(features.clone());
1666 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1670 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
1675 impl Router for TestRouter {
1677 &self, payer: &PublicKey, route_params: &RouteParameters,
1678 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
1679 ) -> Result<Route, LightningError> {
1680 // Simulate calling the Scorer just as you would in find_route
1681 let route = Self::route_for_value(route_params.final_value_msat);
1682 let locked_scorer = self.scorer.lock();
1683 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer, inflight_htlcs);
1684 for path in route.paths {
1685 let mut aggregate_msat = 0u64;
1686 for (idx, hop) in path.iter().rev().enumerate() {
1687 aggregate_msat += hop.fee_msat;
1688 let usage = ChannelUsage {
1689 amount_msat: aggregate_msat,
1690 inflight_htlc_msat: 0,
1691 effective_capacity: EffectiveCapacity::Unknown,
1694 // Since the path is reversed, the last element in our iteration is the first
1696 if idx == path.len() - 1 {
1697 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1699 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1705 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1709 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1710 self.scorer.lock().payment_path_failed(path, short_channel_id);
1713 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1714 self.scorer.lock().payment_path_successful(path);
1717 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1718 self.scorer.lock().probe_successful(path);
1721 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1722 self.scorer.lock().probe_failed(path, short_channel_id);
1726 struct FailingRouter;
1728 impl Router for FailingRouter {
1730 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1731 _inflight_htlcs: &InFlightHtlcs,
1732 ) -> Result<Route, LightningError> {
1733 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1736 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1738 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1740 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1742 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1746 event_expectations: Option<VecDeque<TestResult>>,
1747 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1752 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1753 PaymentSuccess { path: Vec<RouteHop> },
1759 event_expectations: None,
1760 scorer_expectations: RefCell::new(None),
1764 fn expect(mut self, expectation: TestResult) -> Self {
1765 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1769 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1770 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1776 impl lightning::util::ser::Writeable for TestScorer {
1777 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1780 impl Score for TestScorer {
1781 fn channel_penalty_msat(
1782 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1784 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1785 match scorer_expectations.pop_front() {
1786 Some(expectation) => {
1787 assert_eq!(expectation.amount_msat, usage.amount_msat);
1788 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1796 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1797 if let Some(expectations) = &mut self.event_expectations {
1798 match expectations.pop_front() {
1799 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1800 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1801 assert_eq!(actual_short_channel_id, short_channel_id);
1803 Some(TestResult::PaymentSuccess { path }) => {
1804 panic!("Unexpected successful payment path: {:?}", path)
1806 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1811 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1812 if let Some(expectations) = &mut self.event_expectations {
1813 match expectations.pop_front() {
1814 Some(TestResult::PaymentFailure { path, .. }) => {
1815 panic!("Unexpected payment path failure: {:?}", path)
1817 Some(TestResult::PaymentSuccess { path }) => {
1818 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1820 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1825 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1826 if let Some(expectations) = &mut self.event_expectations {
1827 match expectations.pop_front() {
1828 Some(TestResult::PaymentFailure { path, .. }) => {
1829 panic!("Unexpected failed payment path: {:?}", path)
1831 Some(TestResult::PaymentSuccess { path }) => {
1832 panic!("Unexpected successful payment path: {:?}", path)
1834 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1838 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1839 if let Some(expectations) = &mut self.event_expectations {
1840 match expectations.pop_front() {
1841 Some(TestResult::PaymentFailure { path, .. }) => {
1842 panic!("Unexpected payment path failure: {:?}", path)
1844 Some(TestResult::PaymentSuccess { path }) => {
1845 panic!("Unexpected successful payment path: {:?}", path)
1847 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1853 impl Drop for TestScorer {
1854 fn drop(&mut self) {
1855 if std::thread::panicking() {
1859 if let Some(event_expectations) = &self.event_expectations {
1860 if !event_expectations.is_empty() {
1861 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1865 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1866 if !scorer_expectations.is_empty() {
1867 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1874 expectations: core::cell::RefCell<VecDeque<Amount>>,
1875 attempts: core::cell::RefCell<usize>,
1876 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1877 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1880 #[derive(Clone, Debug, PartialEq, Eq)]
1887 struct OnAttempt(usize);
1892 expectations: core::cell::RefCell::new(VecDeque::new()),
1893 attempts: core::cell::RefCell::new(0),
1894 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1895 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
1899 fn expect_send(self, value_msat: Amount) -> Self {
1900 self.expectations.borrow_mut().push_back(value_msat);
1904 fn fails_on_attempt(self, attempt: usize) -> Self {
1905 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
1906 self.fails_with(failure, OnAttempt(attempt))
1909 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
1910 self.fails_with(PaymentSendFailure::PartialFailure {
1911 results: results.unwrap_or(vec![]),
1912 failed_paths_retry: Some(retry),
1913 payment_id: PaymentId([1; 32]),
1917 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1918 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1922 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
1923 let mut attempts = self.attempts.borrow_mut();
1926 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1927 Some(failure) => Err(failure),
1932 fn check_value_msats(&self, actual_value_msats: Amount) {
1933 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1934 if let Some(expected_value_msats) = expected_value_msats {
1935 assert_eq!(actual_value_msats, expected_value_msats);
1937 panic!("Unexpected amount: {:?}", actual_value_msats);
1941 fn track_inflight_htlcs(&self, route: &Route) {
1942 for path in &route.paths {
1943 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
1947 fn fail_path(&self, path: &Vec<RouteHop>) {
1948 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
1950 if let Some(idx) = path_idx {
1951 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
1956 impl Drop for TestPayer {
1957 fn drop(&mut self) {
1958 if std::thread::panicking() {
1962 if !self.expectations.borrow().is_empty() {
1963 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1968 impl Payer for TestPayer {
1969 fn node_id(&self) -> PublicKey {
1970 let secp_ctx = Secp256k1::new();
1971 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1974 fn first_hops(&self) -> Vec<ChannelDetails> {
1979 &self, route: &Route, _payment_hash: PaymentHash,
1980 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
1981 ) -> Result<(), PaymentSendFailure> {
1982 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1983 self.track_inflight_htlcs(route);
1984 self.check_attempts()
1987 fn send_spontaneous_payment(
1988 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
1989 ) -> Result<(), PaymentSendFailure> {
1990 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1991 self.check_attempts()
1995 &self, route: &Route, _payment_id: PaymentId
1996 ) -> Result<(), PaymentSendFailure> {
1997 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1998 self.track_inflight_htlcs(route);
1999 self.check_attempts()
2002 fn abandon_payment(&self, _payment_id: PaymentId) { }
2004 fn inflight_htlcs(&self) -> InFlightHtlcs {
2005 let mut inflight_htlcs = InFlightHtlcs::new();
2006 for path in self.inflight_htlcs_paths.clone().into_inner() {
2007 inflight_htlcs.process_path(&path, self.node_id());
2013 // *** Full Featured Functional Tests with a Real ChannelManager ***
2014 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2016 impl Router for ManualRouter {
2018 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2019 _inflight_htlcs: &InFlightHtlcs
2020 ) -> Result<Route, LightningError> {
2021 self.0.borrow_mut().pop_front().unwrap()
2024 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2026 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2028 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2030 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2033 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2034 self.0.borrow_mut().push_back(result);
2037 impl Drop for ManualRouter {
2038 fn drop(&mut self) {
2039 if std::thread::panicking() {
2042 assert!(self.0.borrow_mut().is_empty());
2047 fn retry_multi_path_single_failed_payment() {
2048 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2049 let chanmon_cfgs = create_chanmon_cfgs(2);
2050 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2051 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2052 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2054 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2055 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2056 let chans = nodes[0].node.list_usable_channels();
2057 let mut route = Route {
2060 pubkey: nodes[1].node.get_our_node_id(),
2061 node_features: nodes[1].node.node_features(),
2062 short_channel_id: chans[0].short_channel_id.unwrap(),
2063 channel_features: nodes[1].node.channel_features(),
2065 cltv_expiry_delta: 100,
2068 pubkey: nodes[1].node.get_our_node_id(),
2069 node_features: nodes[1].node.node_features(),
2070 short_channel_id: chans[1].short_channel_id.unwrap(),
2071 channel_features: nodes[1].node.channel_features(),
2072 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2073 cltv_expiry_delta: 100,
2076 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 100)),
2078 let router = ManualRouter(RefCell::new(VecDeque::new()));
2079 router.expect_find_route(Ok(route.clone()));
2080 // On retry, split the payment across both channels.
2081 route.paths[0][0].fee_msat = 50_000_001;
2082 route.paths[1][0].fee_msat = 50_000_000;
2083 router.expect_find_route(Ok(route.clone()));
2085 let event_handler = |_: Event| { panic!(); };
2086 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2088 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2089 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2090 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2092 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2093 assert_eq!(htlc_msgs.len(), 2);
2094 check_added_monitors!(nodes[0], 2);
2098 fn immediate_retry_on_failure() {
2099 // Tests that we can/will retry immediately after a failure
2100 let chanmon_cfgs = create_chanmon_cfgs(2);
2101 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2102 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2103 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2105 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2106 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
2107 let chans = nodes[0].node.list_usable_channels();
2108 let mut route = Route {
2111 pubkey: nodes[1].node.get_our_node_id(),
2112 node_features: nodes[1].node.node_features(),
2113 short_channel_id: chans[0].short_channel_id.unwrap(),
2114 channel_features: nodes[1].node.channel_features(),
2115 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2116 cltv_expiry_delta: 100,
2119 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 100)),
2121 let router = ManualRouter(RefCell::new(VecDeque::new()));
2122 router.expect_find_route(Ok(route.clone()));
2123 // On retry, split the payment across both channels.
2124 route.paths.push(route.paths[0].clone());
2125 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2126 route.paths[0][0].fee_msat = 50_000_000;
2127 route.paths[1][0].fee_msat = 50_000_001;
2128 router.expect_find_route(Ok(route.clone()));
2130 let event_handler = |_: Event| { panic!(); };
2131 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2133 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2134 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2135 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2137 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2138 assert_eq!(htlc_msgs.len(), 2);
2139 check_added_monitors!(nodes[0], 2);
2143 fn no_extra_retries_on_back_to_back_fail() {
2144 // In a previous release, we had a race where we may exceed the payment retry count if we
2145 // get two failures in a row with the second having `all_paths_failed` set.
2146 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2147 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2148 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2149 // pending which we will see later. Thus, when we previously removed the retry tracking map
2150 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2151 // retry entry even though more events for the same payment were still pending. This led to
2152 // us retrying a payment again even though we'd already given up on it.
2154 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2155 // is used to remove the payment retry counter entries instead. This tests for the specific
2156 // excess-retry case while also testing `PaymentFailed` generation.
2158 let chanmon_cfgs = create_chanmon_cfgs(3);
2159 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2160 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2161 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2163 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0).0.contents.short_channel_id;
2164 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0).0.contents.short_channel_id;
2166 let mut route = Route {
2169 pubkey: nodes[1].node.get_our_node_id(),
2170 node_features: nodes[1].node.node_features(),
2171 short_channel_id: chan_1_scid,
2172 channel_features: nodes[1].node.channel_features(),
2174 cltv_expiry_delta: 100,
2176 pubkey: nodes[2].node.get_our_node_id(),
2177 node_features: nodes[2].node.node_features(),
2178 short_channel_id: chan_2_scid,
2179 channel_features: nodes[2].node.channel_features(),
2180 fee_msat: 100_000_000,
2181 cltv_expiry_delta: 100,
2184 pubkey: nodes[1].node.get_our_node_id(),
2185 node_features: nodes[1].node.node_features(),
2186 short_channel_id: chan_1_scid,
2187 channel_features: nodes[2].node.channel_features(),
2189 cltv_expiry_delta: 100,
2191 pubkey: nodes[2].node.get_our_node_id(),
2192 node_features: nodes[2].node.node_features(),
2193 short_channel_id: chan_2_scid,
2194 channel_features: nodes[2].node.channel_features(),
2195 fee_msat: 100_000_000,
2196 cltv_expiry_delta: 100,
2199 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), 100)),
2201 let router = ManualRouter(RefCell::new(VecDeque::new()));
2202 router.expect_find_route(Ok(route.clone()));
2203 // On retry, we'll only be asked for one path
2204 route.paths.remove(1);
2205 router.expect_find_route(Ok(route.clone()));
2207 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2208 let event_handler = |event: Event| {
2209 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2210 event_checker(event);
2212 let invoice_payer = InvoicePayer::new(nodes[0].node, &router, nodes[0].logger, event_handler, Retry::Attempts(1));
2214 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2215 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2216 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600, None).unwrap())
2218 let htlc_updates = SendEvent::from_node(&nodes[0]);
2219 check_added_monitors!(nodes[0], 1);
2220 assert_eq!(htlc_updates.msgs.len(), 1);
2222 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2223 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2224 check_added_monitors!(nodes[1], 1);
2225 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2227 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2228 check_added_monitors!(nodes[0], 1);
2229 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2231 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2232 check_added_monitors!(nodes[0], 1);
2233 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2235 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2236 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2237 check_added_monitors!(nodes[1], 1);
2238 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2240 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2241 check_added_monitors!(nodes[1], 1);
2242 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2244 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2245 check_added_monitors!(nodes[0], 1);
2247 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2248 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2249 check_added_monitors!(nodes[0], 1);
2250 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2252 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2253 check_added_monitors!(nodes[1], 1);
2254 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2256 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2257 check_added_monitors!(nodes[1], 1);
2258 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2260 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2261 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2262 check_added_monitors!(nodes[0], 1);
2264 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2265 check_added_monitors!(nodes[0], 1);
2266 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2268 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2269 check_added_monitors!(nodes[1], 1);
2270 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2271 check_added_monitors!(nodes[1], 1);
2272 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2274 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2275 check_added_monitors!(nodes[0], 1);
2277 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2278 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2279 // with it set. The first event will use up the only retry we are allowed, with the second
2280 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2281 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2282 // if the final HTLC failed.
2283 expected_events.borrow_mut().push_back(&|ev: Event| {
2284 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2285 assert!(!payment_failed_permanently);
2286 assert!(all_paths_failed);
2287 } else { panic!("Unexpected event"); }
2289 nodes[0].node.process_pending_events(&invoice_payer);
2290 assert!(expected_events.borrow().is_empty());
2292 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2293 check_added_monitors!(nodes[0], 1);
2295 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2296 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2297 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2298 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2299 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2301 expected_events.borrow_mut().push_back(&|ev: Event| {
2302 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2303 assert!(!payment_failed_permanently);
2304 assert!(all_paths_failed);
2305 } else { panic!("Unexpected event"); }
2307 expected_events.borrow_mut().push_back(&|ev: Event| {
2308 if let Event::PaymentFailed { .. } = ev {
2309 } else { panic!("Unexpected event"); }
2311 nodes[0].node.process_pending_events(&invoice_payer);
2312 assert!(expected_events.borrow().is_empty());