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, ScoringRouter};
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!() }
82 //! # impl ScoringRouter for FakeRouter {
83 //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
84 //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() }
85 //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() }
86 //! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
89 //! # struct FakeScorer {}
90 //! # impl Writeable for FakeScorer {
91 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
93 //! # impl Score for FakeScorer {
94 //! # fn channel_penalty_msat(
95 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
97 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
99 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
100 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
103 //! # struct FakeLogger {}
104 //! # impl Logger for FakeLogger {
105 //! # fn log(&self, record: &Record) { unimplemented!() }
109 //! let event_handler = |event: Event| {
111 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
112 //! Event::PaymentSent { .. } => println!("payment successful"),
116 //! # let payer = FakePayer {};
117 //! # let router = FakeRouter {};
118 //! # let scorer = RefCell::new(FakeScorer {});
119 //! # let logger = FakeLogger {};
120 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
122 //! let invoice = "...";
123 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
124 //! invoice_payer.pay_invoice(&invoice).unwrap();
126 //! # let event_provider = FakeEventProvider {};
128 //! event_provider.process_pending_events(&invoice_payer);
136 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
137 //! as updates to the network graph or changes to channel scores should be applied prior to
138 //! retries, typically by way of composing [`EventHandler`]s accordingly.
142 use bitcoin_hashes::Hash;
143 use bitcoin_hashes::sha256::Hash as Sha256;
145 use crate::prelude::*;
146 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
147 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
148 use lightning::ln::msgs::LightningError;
149 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router};
150 use lightning::util::events::{Event, EventHandler};
151 use lightning::util::logger::Logger;
152 use crate::time_utils::Time;
153 use crate::sync::Mutex;
155 use secp256k1::PublicKey;
158 use core::fmt::{Debug, Display, Formatter};
159 use core::future::Future;
160 use core::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
167 /// See [module-level documentation] for details.
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
175 use crate::time_utils;
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
179 /// Sealed trait with a blanket implementation to allow both sync and async implementations of event
180 /// handling to exist within the InvoicePayer.
182 pub trait BaseEventHandler {}
183 impl<T> BaseEventHandler for T {}
186 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
187 pub struct InvoicePayerUsingTime<
191 E: sealed::BaseEventHandler,
201 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
202 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
206 /// Storing minimal payment attempts information required for determining if a outbound payment can
208 #[derive(Clone, Copy)]
209 struct PaymentAttempts<T: Time> {
210 /// This count will be incremented only after the result of the attempt is known. When it's 0,
211 /// it means the result of the first attempt is now known yet.
213 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
214 first_attempted_at: T
217 impl<T: Time> PaymentAttempts<T> {
221 first_attempted_at: T::now()
226 impl<T: Time> Display for PaymentAttempts<T> {
227 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
228 #[cfg(feature = "no-std")]
229 return write!( f, "attempts: {}", self.count);
230 #[cfg(not(feature = "no-std"))]
233 "attempts: {}, duration: {}s",
235 T::now().duration_since(self.first_attempted_at).as_secs()
240 /// A trait defining behavior of an [`Invoice`] payer.
242 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
243 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
245 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
247 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
248 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
249 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
250 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
252 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
254 /// Returns the payer's node id.
255 fn node_id(&self) -> PublicKey;
257 /// Returns the payer's channels.
258 fn first_hops(&self) -> Vec<ChannelDetails>;
260 /// Sends a payment over the Lightning Network using the given [`Route`].
262 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
263 payment_id: PaymentId
264 ) -> Result<(), PaymentSendFailure>;
266 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
267 fn send_spontaneous_payment(
268 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
269 ) -> Result<(), PaymentSendFailure>;
271 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
272 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
274 /// Signals that no further retries for the given payment will occur.
275 fn abandon_payment(&self, payment_id: PaymentId);
277 /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
279 fn inflight_htlcs(&self) -> InFlightHtlcs;
282 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
283 /// based on payment and probe success/failure.
285 /// [`Router`]: lightning::routing::router::Router
286 pub trait ScoringRouter: Router {
287 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
288 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
289 fn find_route_with_id(
290 &self, payer: &PublicKey, route_params: &RouteParameters,
291 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
292 _payment_hash: PaymentHash, _payment_id: PaymentId
293 ) -> Result<Route, LightningError> {
294 self.find_route(payer, route_params, first_hops, inflight_htlcs)
296 /// Lets the router know that payment through a specific path has failed.
297 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
298 /// Lets the router know that payment through a specific path was successful.
299 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
300 /// Lets the router know that a payment probe was successful.
301 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
302 /// Lets the router know that a payment probe failed.
303 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
306 /// Strategies available to retry payment path failures for an [`Invoice`].
308 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
310 /// Max number of attempts to retry payment.
312 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
313 /// payments, if this is less than the total number of paths, we will never even retry all of the
316 #[cfg(feature = "std")]
317 /// Time elapsed before abandoning retries for a payment.
322 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
323 match (self, attempts) {
324 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
325 max_retry_count >= &count
327 #[cfg(feature = "std")]
328 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
329 *max_duration >= T::now().duration_since(*first_attempted_at),
334 /// An error that may occur when making a payment.
335 #[derive(Clone, Debug)]
336 pub enum PaymentError {
337 /// An error resulting from the provided [`Invoice`] or payment hash.
338 Invoice(&'static str),
339 /// An error occurring when finding a route.
340 Routing(LightningError),
341 /// An error occurring when sending a payment.
342 Sending(PaymentSendFailure),
345 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
346 InvoicePayerUsingTime<P, R, L, E, T>
351 /// Creates an invoice payer that retries failed payment paths.
353 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
354 /// `retry` has been exceeded for a given [`Invoice`].
356 payer: P, router: R, logger: L, event_handler: E, retry: Retry
363 payment_cache: Mutex::new(HashMap::new()),
368 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
370 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
371 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
372 /// a second payment with the same [`PaymentHash`] is never sent.
374 /// If you wish to use a different payment idempotency token, see
375 /// [`Self::pay_invoice_with_id`].
376 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
377 let payment_id = PaymentId(invoice.payment_hash().into_inner());
378 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
381 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
382 /// in case a retry is needed.
384 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
385 /// payment completes or fails, no idempotency guarantees are made.
387 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
388 /// has never been paid before.
390 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
392 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
393 if invoice.amount_milli_satoshis().is_none() {
394 Err(PaymentError::Invoice("amount missing"))
396 self.pay_invoice_using_amount(invoice, None, payment_id)
400 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
401 /// case a retry is needed.
403 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
404 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
405 /// a second payment with the same [`PaymentHash`] is never sent.
407 /// If you wish to use a different payment idempotency token, see
408 /// [`Self::pay_zero_value_invoice_with_id`].
409 pub fn pay_zero_value_invoice(
410 &self, invoice: &Invoice, amount_msats: u64
411 ) -> Result<PaymentId, PaymentError> {
412 let payment_id = PaymentId(invoice.payment_hash().into_inner());
413 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
416 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
417 /// caching the invoice for later use in case a retry is needed.
419 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
420 /// payment completes or fails, no idempotency guarantees are made.
422 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
423 /// has never been paid before.
425 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
426 /// idempotency token.
427 pub fn pay_zero_value_invoice_with_id(
428 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
429 ) -> Result<(), PaymentError> {
430 if invoice.amount_milli_satoshis().is_some() {
431 Err(PaymentError::Invoice("amount unexpected"))
433 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
437 fn pay_invoice_using_amount(
438 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
439 ) -> Result<(), PaymentError> {
440 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
442 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
443 match self.payment_cache.lock().unwrap().entry(payment_hash) {
444 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
445 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
448 let payment_secret = Some(invoice.payment_secret().clone());
449 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
450 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
451 .with_route_hints(invoice.route_hints());
452 if let Some(features) = invoice.features() {
453 payment_params = payment_params.with_features(features.clone());
455 let route_params = RouteParameters {
457 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
458 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
461 let send_payment = |route: &Route| {
462 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
465 self.pay_internal(&route_params, payment_hash, send_payment)
466 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
469 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
470 /// case a retry is needed.
472 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
473 /// as long as the payment is still pending. Once the payment completes or fails, you must
474 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
476 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
477 final_cltv_expiry_delta: u32
478 ) -> Result<PaymentId, PaymentError> {
479 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
480 let payment_id = PaymentId(payment_hash.0);
481 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
482 final_cltv_expiry_delta)
483 .map(|()| payment_id)
486 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
487 /// caching the invoice for later use in case a retry is needed.
489 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
490 /// payment completes or fails, no idempotency guarantees are made.
492 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
493 /// [`PaymentHash`] has never been paid before.
494 pub fn pay_pubkey_with_id(
495 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
496 amount_msats: u64, final_cltv_expiry_delta: u32
497 ) -> Result<(), PaymentError> {
498 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
499 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
500 final_cltv_expiry_delta)
504 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
505 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
506 ) -> Result<(), PaymentError> {
507 match self.payment_cache.lock().unwrap().entry(payment_hash) {
508 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
509 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
512 let route_params = RouteParameters {
513 payment_params: PaymentParameters::for_keysend(pubkey),
514 final_value_msat: amount_msats,
515 final_cltv_expiry_delta,
518 let send_payment = |route: &Route| {
519 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
521 self.pay_internal(&route_params, payment_hash, send_payment)
522 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
525 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
526 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
527 ) -> Result<(), PaymentError> {
528 #[cfg(feature = "std")] {
529 if has_expired(params) {
530 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
531 return Err(PaymentError::Invoice("Invoice expired prior to send"));
535 let payer = self.payer.node_id();
536 let first_hops = self.payer.first_hops();
537 let inflight_htlcs = self.payer.inflight_htlcs();
538 let route = self.router.find_route(
539 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
540 ).map_err(|e| PaymentError::Routing(e))?;
542 match send_payment(&route) {
545 PaymentSendFailure::ParameterError(_) => Err(e),
546 PaymentSendFailure::PathParameterError(_) => Err(e),
547 PaymentSendFailure::DuplicatePayment => Err(e),
548 PaymentSendFailure::AllFailedResendSafe(_) => {
549 let mut payment_cache = self.payment_cache.lock().unwrap();
550 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
551 payment_attempts.count += 1;
552 if self.retry.is_retryable_now(payment_attempts) {
553 core::mem::drop(payment_cache);
554 Ok(self.pay_internal(params, payment_hash, send_payment)?)
559 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
560 if let Some(retry_data) = failed_paths_retry {
561 // Some paths were sent, even if we failed to send the full MPP value our
562 // recipient may misbehave and claim the funds, at which point we have to
563 // consider the payment sent, so return `Ok()` here, ignoring any retry
565 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
568 // This may happen if we send a payment and some paths fail, but
569 // only due to a temporary monitor failure or the like, implying
570 // they're really in-flight, but we haven't sent the initial
571 // HTLC-Add messages yet.
576 }.map_err(|e| PaymentError::Sending(e))
580 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
581 ) -> Result<(), ()> {
583 *self.payment_cache.lock().unwrap().entry(payment_hash)
584 .and_modify(|attempts| attempts.count += 1)
585 .or_insert(PaymentAttempts {
587 first_attempted_at: T::now()
590 if !self.retry.is_retryable_now(&attempts) {
591 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
595 #[cfg(feature = "std")] {
596 if has_expired(params) {
597 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
602 let payer = self.payer.node_id();
603 let first_hops = self.payer.first_hops();
604 let inflight_htlcs = self.payer.inflight_htlcs();
606 let route = self.router.find_route(
607 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
611 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
615 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
617 Err(PaymentSendFailure::ParameterError(_)) |
618 Err(PaymentSendFailure::PathParameterError(_)) => {
619 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
622 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
623 self.retry_payment(payment_id, payment_hash, params)
625 Err(PaymentSendFailure::DuplicatePayment) => {
626 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
629 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
630 if let Some(retry) = failed_paths_retry {
631 // Always return Ok for the same reason as noted in pay_internal.
632 let _ = self.retry_payment(payment_id, payment_hash, &retry);
639 /// Removes the payment cached by the given payment hash.
641 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
642 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
643 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
644 self.payment_cache.lock().unwrap().remove(payment_hash);
648 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
649 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
652 #[cfg(feature = "std")]
653 fn has_expired(route_params: &RouteParameters) -> bool {
654 if let Some(expiry_time) = route_params.payment_params.expiry_time {
655 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
659 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
660 InvoicePayerUsingTime<P, R, L, E, T>
665 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
667 fn handle_event_internal(&self, event: &Event) -> bool {
669 Event::PaymentPathFailed {
670 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
672 if let Some(short_channel_id) = short_channel_id {
673 let path = path.iter().collect::<Vec<_>>();
674 self.router.notify_payment_path_failed(&path, *short_channel_id)
677 if payment_id.is_none() {
678 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
679 } else if *payment_failed_permanently {
680 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
681 self.payer.abandon_payment(payment_id.unwrap());
682 } else if retry.is_none() {
683 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
684 self.payer.abandon_payment(payment_id.unwrap());
685 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
686 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
689 self.payer.abandon_payment(payment_id.unwrap());
692 Event::PaymentFailed { payment_hash, .. } => {
693 self.remove_cached_payment(&payment_hash);
695 Event::PaymentPathSuccessful { path, .. } => {
696 let path = path.iter().collect::<Vec<_>>();
697 self.router.notify_payment_path_successful(&path);
699 Event::PaymentSent { payment_hash, .. } => {
700 let mut payment_cache = self.payment_cache.lock().unwrap();
701 let attempts = payment_cache
702 .remove(payment_hash)
703 .map_or(1, |attempts| attempts.count + 1);
704 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
706 Event::ProbeSuccessful { payment_hash, path, .. } => {
707 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
708 let path = path.iter().collect::<Vec<_>>();
709 self.router.notify_payment_probe_successful(&path);
711 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
712 if let Some(short_channel_id) = short_channel_id {
713 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
714 let path = path.iter().collect::<Vec<_>>();
715 self.router.notify_payment_probe_failed(&path, *short_channel_id);
721 // Delegate to the decorated event handler unless the payment is retried.
726 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
727 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
732 fn handle_event(&self, event: Event) {
733 let should_forward = self.handle_event_internal(&event);
735 self.event_handler.handle_event(event)
740 impl<P: Deref, R: ScoringRouter, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
741 InvoicePayerUsingTime<P, R, L, H, T>
746 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
747 /// handler, if necessary, to handle them asynchronously.
748 pub async fn handle_event_async(&self, event: Event) {
749 let should_forward = self.handle_event_internal(&event);
751 (self.event_handler)(event).await;
759 use crate::{InvoiceBuilder, Currency};
760 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
761 use bitcoin_hashes::sha256::Hash as Sha256;
762 use lightning::ln::PaymentPreimage;
763 use lightning::ln::channelmanager;
764 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
765 use lightning::ln::functional_test_utils::*;
766 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
767 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
768 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
769 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
770 use lightning::util::test_utils::TestLogger;
771 use lightning::util::errors::APIError;
772 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
773 use secp256k1::{SecretKey, PublicKey, Secp256k1};
774 use std::cell::RefCell;
775 use std::collections::VecDeque;
776 use std::ops::DerefMut;
777 use std::time::{SystemTime, Duration};
778 use crate::time_utils::tests::SinceEpoch;
779 use crate::DEFAULT_EXPIRY_TIME;
781 fn 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 .amount_milli_satoshis(128)
792 .build_signed(|hash| {
793 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
798 fn duration_since_epoch() -> Duration {
799 #[cfg(feature = "std")]
800 let duration_since_epoch =
801 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
802 #[cfg(not(feature = "std"))]
803 let duration_since_epoch = Duration::from_secs(1234567);
807 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
808 let payment_hash = Sha256::hash(&payment_preimage.0);
809 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
811 InvoiceBuilder::new(Currency::Bitcoin)
812 .description("test".into())
813 .payment_hash(payment_hash)
814 .payment_secret(PaymentSecret([0; 32]))
815 .duration_since_epoch(duration_since_epoch())
816 .min_final_cltv_expiry(144)
817 .build_signed(|hash| {
818 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
823 #[cfg(feature = "std")]
824 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
825 let payment_hash = Sha256::hash(&payment_preimage.0);
826 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
827 let duration = duration_since_epoch()
828 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
830 InvoiceBuilder::new(Currency::Bitcoin)
831 .description("test".into())
832 .payment_hash(payment_hash)
833 .payment_secret(PaymentSecret([0; 32]))
834 .duration_since_epoch(duration)
835 .min_final_cltv_expiry(144)
836 .amount_milli_satoshis(128)
837 .build_signed(|hash| {
838 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
843 fn pubkey() -> PublicKey {
844 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
848 fn pays_invoice_on_first_attempt() {
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().expect_send(Amount::ForInvoice(final_value_msat));
858 let router = TestRouter::new(TestScorer::new());
859 let logger = TestLogger::new();
861 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
863 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
864 assert_eq!(*payer.attempts.borrow(), 1);
866 invoice_payer.handle_event(Event::PaymentSent {
867 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
869 assert_eq!(*event_handled.borrow(), true);
870 assert_eq!(*payer.attempts.borrow(), 1);
874 fn pays_invoice_on_retry() {
875 let event_handled = core::cell::RefCell::new(false);
876 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
878 let payment_preimage = PaymentPreimage([1; 32]);
879 let invoice = invoice(payment_preimage);
880 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
881 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
883 let payer = TestPayer::new()
884 .expect_send(Amount::ForInvoice(final_value_msat))
885 .expect_send(Amount::OnRetry(final_value_msat / 2));
886 let router = TestRouter::new(TestScorer::new());
887 let logger = TestLogger::new();
889 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
891 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
892 assert_eq!(*payer.attempts.borrow(), 1);
894 let event = Event::PaymentPathFailed {
897 network_update: None,
898 payment_failed_permanently: false,
899 all_paths_failed: false,
900 path: TestRouter::path_for_value(final_value_msat),
901 short_channel_id: None,
902 retry: Some(TestRouter::retry_for_invoice(&invoice)),
904 invoice_payer.handle_event(event);
905 assert_eq!(*event_handled.borrow(), false);
906 assert_eq!(*payer.attempts.borrow(), 2);
908 invoice_payer.handle_event(Event::PaymentSent {
909 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
911 assert_eq!(*event_handled.borrow(), true);
912 assert_eq!(*payer.attempts.borrow(), 2);
916 fn pays_invoice_on_partial_failure() {
917 let event_handler = |_: Event| { panic!() };
919 let payment_preimage = PaymentPreimage([1; 32]);
920 let invoice = invoice(payment_preimage);
921 let retry = TestRouter::retry_for_invoice(&invoice);
922 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
924 let payer = TestPayer::new()
925 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
926 .fails_with_partial_failure(retry, OnAttempt(2), None)
927 .expect_send(Amount::ForInvoice(final_value_msat))
928 .expect_send(Amount::OnRetry(final_value_msat / 2))
929 .expect_send(Amount::OnRetry(final_value_msat / 2));
930 let router = TestRouter::new(TestScorer::new());
931 let logger = TestLogger::new();
933 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
935 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
939 fn retries_payment_path_for_unknown_payment() {
940 let event_handled = core::cell::RefCell::new(false);
941 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
943 let payment_preimage = PaymentPreimage([1; 32]);
944 let invoice = invoice(payment_preimage);
945 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
946 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
948 let payer = TestPayer::new()
949 .expect_send(Amount::OnRetry(final_value_msat / 2))
950 .expect_send(Amount::OnRetry(final_value_msat / 2));
951 let router = TestRouter::new(TestScorer::new());
952 let logger = TestLogger::new();
954 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
956 let payment_id = Some(PaymentId([1; 32]));
957 let event = Event::PaymentPathFailed {
960 network_update: None,
961 payment_failed_permanently: false,
962 all_paths_failed: false,
963 path: TestRouter::path_for_value(final_value_msat),
964 short_channel_id: None,
965 retry: Some(TestRouter::retry_for_invoice(&invoice)),
967 invoice_payer.handle_event(event.clone());
968 assert_eq!(*event_handled.borrow(), false);
969 assert_eq!(*payer.attempts.borrow(), 1);
971 invoice_payer.handle_event(event.clone());
972 assert_eq!(*event_handled.borrow(), false);
973 assert_eq!(*payer.attempts.borrow(), 2);
975 invoice_payer.handle_event(Event::PaymentSent {
976 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
978 assert_eq!(*event_handled.borrow(), true);
979 assert_eq!(*payer.attempts.borrow(), 2);
983 fn fails_paying_invoice_after_max_retry_counts() {
984 let event_handled = core::cell::RefCell::new(false);
985 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
987 let payment_preimage = PaymentPreimage([1; 32]);
988 let invoice = invoice(payment_preimage);
989 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
991 let payer = TestPayer::new()
992 .expect_send(Amount::ForInvoice(final_value_msat))
993 .expect_send(Amount::OnRetry(final_value_msat / 2))
994 .expect_send(Amount::OnRetry(final_value_msat / 2));
995 let router = TestRouter::new(TestScorer::new());
996 let logger = TestLogger::new();
998 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1000 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1001 assert_eq!(*payer.attempts.borrow(), 1);
1003 let event = Event::PaymentPathFailed {
1005 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1006 network_update: None,
1007 payment_failed_permanently: false,
1008 all_paths_failed: true,
1009 path: TestRouter::path_for_value(final_value_msat),
1010 short_channel_id: None,
1011 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1013 invoice_payer.handle_event(event);
1014 assert_eq!(*event_handled.borrow(), false);
1015 assert_eq!(*payer.attempts.borrow(), 2);
1017 let event = Event::PaymentPathFailed {
1019 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1020 network_update: None,
1021 payment_failed_permanently: false,
1022 all_paths_failed: false,
1023 path: TestRouter::path_for_value(final_value_msat / 2),
1024 short_channel_id: None,
1025 retry: Some(RouteParameters {
1026 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1029 invoice_payer.handle_event(event.clone());
1030 assert_eq!(*event_handled.borrow(), false);
1031 assert_eq!(*payer.attempts.borrow(), 3);
1033 invoice_payer.handle_event(event.clone());
1034 assert_eq!(*event_handled.borrow(), true);
1035 assert_eq!(*payer.attempts.borrow(), 3);
1038 #[cfg(feature = "std")]
1040 fn fails_paying_invoice_after_max_retry_timeout() {
1041 let event_handled = core::cell::RefCell::new(false);
1042 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1044 let payment_preimage = PaymentPreimage([1; 32]);
1045 let invoice = invoice(payment_preimage);
1046 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1048 let payer = TestPayer::new()
1049 .expect_send(Amount::ForInvoice(final_value_msat))
1050 .expect_send(Amount::OnRetry(final_value_msat / 2));
1052 let router = TestRouter::new(TestScorer::new());
1053 let logger = TestLogger::new();
1054 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1057 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1059 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1060 assert_eq!(*payer.attempts.borrow(), 1);
1062 let event = Event::PaymentPathFailed {
1064 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1065 network_update: None,
1066 payment_failed_permanently: false,
1067 all_paths_failed: true,
1068 path: TestRouter::path_for_value(final_value_msat),
1069 short_channel_id: None,
1070 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1072 invoice_payer.handle_event(event.clone());
1073 assert_eq!(*event_handled.borrow(), false);
1074 assert_eq!(*payer.attempts.borrow(), 2);
1076 SinceEpoch::advance(Duration::from_secs(121));
1078 invoice_payer.handle_event(event.clone());
1079 assert_eq!(*event_handled.borrow(), true);
1080 assert_eq!(*payer.attempts.borrow(), 2);
1084 fn fails_paying_invoice_with_missing_retry_params() {
1085 let event_handled = core::cell::RefCell::new(false);
1086 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1088 let payment_preimage = PaymentPreimage([1; 32]);
1089 let invoice = invoice(payment_preimage);
1090 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1092 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1093 let router = TestRouter::new(TestScorer::new());
1094 let logger = TestLogger::new();
1096 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1098 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1099 assert_eq!(*payer.attempts.borrow(), 1);
1101 let event = Event::PaymentPathFailed {
1103 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1104 network_update: None,
1105 payment_failed_permanently: false,
1106 all_paths_failed: false,
1108 short_channel_id: None,
1111 invoice_payer.handle_event(event);
1112 assert_eq!(*event_handled.borrow(), true);
1113 assert_eq!(*payer.attempts.borrow(), 1);
1116 // Expiration is checked only in an std environment
1117 #[cfg(feature = "std")]
1119 fn fails_paying_invoice_after_expiration() {
1120 let event_handled = core::cell::RefCell::new(false);
1121 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1123 let payer = TestPayer::new();
1124 let router = TestRouter::new(TestScorer::new());
1125 let logger = TestLogger::new();
1127 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1129 let payment_preimage = PaymentPreimage([1; 32]);
1130 let invoice = expired_invoice(payment_preimage);
1131 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1132 assert_eq!(msg, "Invoice expired prior to send");
1133 } else { panic!("Expected Invoice Error"); }
1136 // Expiration is checked only in an std environment
1137 #[cfg(feature = "std")]
1139 fn fails_retrying_invoice_after_expiration() {
1140 let event_handled = core::cell::RefCell::new(false);
1141 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1143 let payment_preimage = PaymentPreimage([1; 32]);
1144 let invoice = invoice(payment_preimage);
1145 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1147 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1148 let router = TestRouter::new(TestScorer::new());
1149 let logger = TestLogger::new();
1151 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1153 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1154 assert_eq!(*payer.attempts.borrow(), 1);
1156 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1157 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1158 .checked_sub(Duration::from_secs(2)).unwrap()
1159 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1160 let event = Event::PaymentPathFailed {
1162 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1163 network_update: None,
1164 payment_failed_permanently: false,
1165 all_paths_failed: false,
1167 short_channel_id: None,
1168 retry: Some(retry_data),
1170 invoice_payer.handle_event(event);
1171 assert_eq!(*event_handled.borrow(), true);
1172 assert_eq!(*payer.attempts.borrow(), 1);
1176 fn fails_paying_invoice_after_retry_error() {
1177 let event_handled = core::cell::RefCell::new(false);
1178 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1180 let payment_preimage = PaymentPreimage([1; 32]);
1181 let invoice = invoice(payment_preimage);
1182 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1184 let payer = TestPayer::new()
1185 .fails_on_attempt(2)
1186 .expect_send(Amount::ForInvoice(final_value_msat))
1187 .expect_send(Amount::OnRetry(final_value_msat / 2));
1188 let router = TestRouter::new(TestScorer::new());
1189 let logger = TestLogger::new();
1191 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1193 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1194 assert_eq!(*payer.attempts.borrow(), 1);
1196 let event = Event::PaymentPathFailed {
1198 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1199 network_update: None,
1200 payment_failed_permanently: false,
1201 all_paths_failed: false,
1202 path: TestRouter::path_for_value(final_value_msat / 2),
1203 short_channel_id: None,
1204 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1206 invoice_payer.handle_event(event);
1207 assert_eq!(*event_handled.borrow(), true);
1208 assert_eq!(*payer.attempts.borrow(), 2);
1212 fn fails_paying_invoice_after_rejected_by_payee() {
1213 let event_handled = core::cell::RefCell::new(false);
1214 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1216 let payment_preimage = PaymentPreimage([1; 32]);
1217 let invoice = invoice(payment_preimage);
1218 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1220 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1221 let router = TestRouter::new(TestScorer::new());
1222 let logger = TestLogger::new();
1224 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1226 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1227 assert_eq!(*payer.attempts.borrow(), 1);
1229 let event = Event::PaymentPathFailed {
1231 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1232 network_update: None,
1233 payment_failed_permanently: true,
1234 all_paths_failed: false,
1236 short_channel_id: None,
1237 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1239 invoice_payer.handle_event(event);
1240 assert_eq!(*event_handled.borrow(), true);
1241 assert_eq!(*payer.attempts.borrow(), 1);
1245 fn fails_repaying_invoice_with_pending_payment() {
1246 let event_handled = core::cell::RefCell::new(false);
1247 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1249 let payment_preimage = PaymentPreimage([1; 32]);
1250 let invoice = invoice(payment_preimage);
1251 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1253 let payer = TestPayer::new()
1254 .expect_send(Amount::ForInvoice(final_value_msat))
1255 .expect_send(Amount::ForInvoice(final_value_msat));
1256 let router = TestRouter::new(TestScorer::new());
1257 let logger = TestLogger::new();
1259 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1261 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1263 // Cannot repay an invoice pending payment.
1264 match invoice_payer.pay_invoice(&invoice) {
1265 Err(PaymentError::Invoice("payment pending")) => {},
1266 Err(_) => panic!("unexpected error"),
1267 Ok(_) => panic!("expected invoice error"),
1270 // Can repay an invoice once cleared from cache.
1271 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1272 invoice_payer.remove_cached_payment(&payment_hash);
1273 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1275 // Cannot retry paying an invoice if cleared from cache.
1276 invoice_payer.remove_cached_payment(&payment_hash);
1277 let event = Event::PaymentPathFailed {
1280 network_update: None,
1281 payment_failed_permanently: false,
1282 all_paths_failed: false,
1284 short_channel_id: None,
1285 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1287 invoice_payer.handle_event(event);
1288 assert_eq!(*event_handled.borrow(), true);
1292 fn fails_paying_invoice_with_routing_errors() {
1293 let payer = TestPayer::new();
1294 let router = FailingRouter {};
1295 let logger = TestLogger::new();
1297 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1299 let payment_preimage = PaymentPreimage([1; 32]);
1300 let invoice = invoice(payment_preimage);
1301 match invoice_payer.pay_invoice(&invoice) {
1302 Err(PaymentError::Routing(_)) => {},
1303 Err(_) => panic!("unexpected error"),
1304 Ok(_) => panic!("expected routing error"),
1309 fn fails_paying_invoice_with_sending_errors() {
1310 let payment_preimage = PaymentPreimage([1; 32]);
1311 let invoice = invoice(payment_preimage);
1312 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1314 let payer = TestPayer::new()
1315 .fails_on_attempt(1)
1316 .expect_send(Amount::ForInvoice(final_value_msat));
1317 let router = TestRouter::new(TestScorer::new());
1318 let logger = TestLogger::new();
1320 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1322 match invoice_payer.pay_invoice(&invoice) {
1323 Err(PaymentError::Sending(_)) => {},
1324 Err(_) => panic!("unexpected error"),
1325 Ok(_) => panic!("expected sending error"),
1330 fn pays_zero_value_invoice_using_amount() {
1331 let event_handled = core::cell::RefCell::new(false);
1332 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1334 let payment_preimage = PaymentPreimage([1; 32]);
1335 let invoice = zero_value_invoice(payment_preimage);
1336 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1337 let final_value_msat = 100;
1339 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1340 let router = TestRouter::new(TestScorer::new());
1341 let logger = TestLogger::new();
1343 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1346 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1347 assert_eq!(*payer.attempts.borrow(), 1);
1349 invoice_payer.handle_event(Event::PaymentSent {
1350 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1352 assert_eq!(*event_handled.borrow(), true);
1353 assert_eq!(*payer.attempts.borrow(), 1);
1357 fn fails_paying_zero_value_invoice_with_amount() {
1358 let event_handled = core::cell::RefCell::new(false);
1359 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1361 let payer = TestPayer::new();
1362 let router = TestRouter::new(TestScorer::new());
1363 let logger = TestLogger::new();
1365 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1367 let payment_preimage = PaymentPreimage([1; 32]);
1368 let invoice = invoice(payment_preimage);
1370 // Cannot repay an invoice pending payment.
1371 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1372 Err(PaymentError::Invoice("amount unexpected")) => {},
1373 Err(_) => panic!("unexpected error"),
1374 Ok(_) => panic!("expected invoice error"),
1379 fn pays_pubkey_with_amount() {
1380 let event_handled = core::cell::RefCell::new(false);
1381 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1383 let pubkey = pubkey();
1384 let payment_preimage = PaymentPreimage([1; 32]);
1385 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1386 let final_value_msat = 100;
1387 let final_cltv_expiry_delta = 42;
1389 let payer = TestPayer::new()
1390 .expect_send(Amount::Spontaneous(final_value_msat))
1391 .expect_send(Amount::OnRetry(final_value_msat));
1392 let router = TestRouter::new(TestScorer::new());
1393 let logger = TestLogger::new();
1395 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1397 let payment_id = Some(invoice_payer.pay_pubkey(
1398 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1400 assert_eq!(*payer.attempts.borrow(), 1);
1402 let retry = RouteParameters {
1403 payment_params: PaymentParameters::for_keysend(pubkey),
1405 final_cltv_expiry_delta,
1407 let event = Event::PaymentPathFailed {
1410 network_update: None,
1411 payment_failed_permanently: false,
1412 all_paths_failed: false,
1414 short_channel_id: None,
1417 invoice_payer.handle_event(event);
1418 assert_eq!(*event_handled.borrow(), false);
1419 assert_eq!(*payer.attempts.borrow(), 2);
1421 invoice_payer.handle_event(Event::PaymentSent {
1422 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1424 assert_eq!(*event_handled.borrow(), true);
1425 assert_eq!(*payer.attempts.borrow(), 2);
1429 fn scores_failed_channel() {
1430 let event_handled = core::cell::RefCell::new(false);
1431 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1433 let payment_preimage = PaymentPreimage([1; 32]);
1434 let invoice = invoice(payment_preimage);
1435 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1436 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1437 let path = TestRouter::path_for_value(final_value_msat);
1438 let short_channel_id = Some(path[0].short_channel_id);
1440 // Expect that scorer is given short_channel_id upon handling the event.
1441 let payer = TestPayer::new()
1442 .expect_send(Amount::ForInvoice(final_value_msat))
1443 .expect_send(Amount::OnRetry(final_value_msat / 2));
1444 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1445 path: path.clone(), short_channel_id: path[0].short_channel_id,
1447 let router = TestRouter::new(scorer);
1448 let logger = TestLogger::new();
1450 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1452 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1453 let event = Event::PaymentPathFailed {
1456 network_update: None,
1457 payment_failed_permanently: false,
1458 all_paths_failed: false,
1461 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1463 invoice_payer.handle_event(event);
1467 fn scores_successful_channels() {
1468 let event_handled = core::cell::RefCell::new(false);
1469 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1471 let payment_preimage = PaymentPreimage([1; 32]);
1472 let invoice = invoice(payment_preimage);
1473 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1474 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1475 let route = TestRouter::route_for_value(final_value_msat);
1477 // Expect that scorer is given short_channel_id upon handling the event.
1478 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1479 let scorer = TestScorer::new()
1480 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1481 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1482 let router = TestRouter::new(scorer);
1483 let logger = TestLogger::new();
1485 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1487 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1488 let event = Event::PaymentPathSuccessful {
1489 payment_id, payment_hash, path: route.paths[0].clone()
1491 invoice_payer.handle_event(event);
1492 let event = Event::PaymentPathSuccessful {
1493 payment_id, payment_hash, path: route.paths[1].clone()
1495 invoice_payer.handle_event(event);
1499 fn considers_inflight_htlcs_between_invoice_payments() {
1500 let event_handled = core::cell::RefCell::new(false);
1501 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1503 let payment_preimage = PaymentPreimage([1; 32]);
1504 let payment_invoice = invoice(payment_preimage);
1505 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1507 let payer = TestPayer::new()
1508 .expect_send(Amount::ForInvoice(final_value_msat))
1509 .expect_send(Amount::ForInvoice(final_value_msat));
1510 let scorer = TestScorer::new()
1511 // 1st invoice, 1st path
1512 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1513 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1514 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1515 // 1st invoice, 2nd path
1516 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1517 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1518 // 2nd invoice, 1st path
1519 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1520 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1521 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1522 // 2nd invoice, 2nd path
1523 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1524 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1525 let router = TestRouter::new(scorer);
1526 let logger = TestLogger::new();
1528 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1530 // Make first invoice payment.
1531 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1533 // Let's pay a second invoice that will be using the same path. This should trigger the
1534 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1536 let payment_preimage_2 = PaymentPreimage([2; 32]);
1537 let payment_invoice_2 = invoice(payment_preimage_2);
1538 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1542 fn considers_inflight_htlcs_between_retries() {
1543 // First, let's just send a payment through, but only make sure one of the path completes
1544 let event_handled = core::cell::RefCell::new(false);
1545 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1547 let payment_preimage = PaymentPreimage([1; 32]);
1548 let payment_invoice = invoice(payment_preimage);
1549 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1550 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1552 let payer = TestPayer::new()
1553 .expect_send(Amount::ForInvoice(final_value_msat))
1554 .expect_send(Amount::OnRetry(final_value_msat / 2))
1555 .expect_send(Amount::OnRetry(final_value_msat / 4));
1556 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1557 let scorer = TestScorer::new()
1558 // 1st invoice, 1st path
1559 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1560 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1561 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1562 // 1st invoice, 2nd path
1563 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1564 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1565 // Retry 1, 1st path
1566 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1567 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1568 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1569 // Retry 1, 2nd path
1570 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1571 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1572 // Retry 2, 1st path
1573 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1574 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1575 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1576 // Retry 2, 2nd path
1577 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1578 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1579 let router = TestRouter::new(scorer);
1580 let logger = TestLogger::new();
1582 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1584 // Fail 1st path, leave 2nd path inflight
1585 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1586 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1587 invoice_payer.handle_event(Event::PaymentPathFailed {
1590 network_update: None,
1591 payment_failed_permanently: false,
1592 all_paths_failed: false,
1593 path: TestRouter::path_for_value(final_value_msat),
1594 short_channel_id: None,
1595 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1598 // Fails again the 1st path of our retry
1599 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1600 invoice_payer.handle_event(Event::PaymentPathFailed {
1603 network_update: None,
1604 payment_failed_permanently: false,
1605 all_paths_failed: false,
1606 path: TestRouter::path_for_value(final_value_msat / 2),
1607 short_channel_id: None,
1608 retry: Some(RouteParameters {
1609 final_value_msat: final_value_msat / 4,
1610 ..TestRouter::retry_for_invoice(&payment_invoice)
1616 scorer: RefCell<TestScorer>,
1620 fn new(scorer: TestScorer) -> Self {
1621 TestRouter { scorer: RefCell::new(scorer) }
1624 fn route_for_value(final_value_msat: u64) -> Route {
1629 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1630 channel_features: ChannelFeatures::empty(),
1631 node_features: NodeFeatures::empty(),
1632 short_channel_id: 0,
1634 cltv_expiry_delta: 0
1637 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1638 channel_features: ChannelFeatures::empty(),
1639 node_features: NodeFeatures::empty(),
1640 short_channel_id: 1,
1642 cltv_expiry_delta: 0
1645 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1646 channel_features: ChannelFeatures::empty(),
1647 node_features: NodeFeatures::empty(),
1648 short_channel_id: 2,
1649 fee_msat: final_value_msat / 2,
1650 cltv_expiry_delta: 0
1655 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1656 channel_features: ChannelFeatures::empty(),
1657 node_features: NodeFeatures::empty(),
1658 short_channel_id: 3,
1660 cltv_expiry_delta: 144
1663 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1664 channel_features: ChannelFeatures::empty(),
1665 node_features: NodeFeatures::empty(),
1666 short_channel_id: 4,
1667 fee_msat: final_value_msat / 2,
1668 cltv_expiry_delta: 144
1672 payment_params: None,
1676 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1677 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1680 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1681 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1682 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1683 .with_route_hints(invoice.route_hints());
1684 if let Some(features) = invoice.features() {
1685 payment_params = payment_params.with_features(features.clone());
1687 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1691 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1696 impl Router for TestRouter {
1698 &self, payer: &PublicKey, route_params: &RouteParameters,
1699 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1700 ) -> Result<Route, LightningError> {
1701 // Simulate calling the Scorer just as you would in find_route
1702 let route = Self::route_for_value(route_params.final_value_msat);
1703 let mut locked_scorer = self.scorer.lock();
1704 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1705 for path in route.paths {
1706 let mut aggregate_msat = 0u64;
1707 for (idx, hop) in path.iter().rev().enumerate() {
1708 aggregate_msat += hop.fee_msat;
1709 let usage = ChannelUsage {
1710 amount_msat: aggregate_msat,
1711 inflight_htlc_msat: 0,
1712 effective_capacity: EffectiveCapacity::Unknown,
1715 // Since the path is reversed, the last element in our iteration is the first
1717 if idx == path.len() - 1 {
1718 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1720 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1726 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1731 impl ScoringRouter for TestRouter {
1732 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1733 self.scorer.lock().payment_path_failed(path, short_channel_id);
1736 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1737 self.scorer.lock().payment_path_successful(path);
1740 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1741 self.scorer.lock().probe_successful(path);
1744 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1745 self.scorer.lock().probe_failed(path, short_channel_id);
1749 struct FailingRouter;
1751 impl Router for FailingRouter {
1753 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1754 _inflight_htlcs: InFlightHtlcs,
1755 ) -> Result<Route, LightningError> {
1756 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1760 impl ScoringRouter for FailingRouter {
1761 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1763 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1765 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1767 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1771 event_expectations: Option<VecDeque<TestResult>>,
1772 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1777 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1778 PaymentSuccess { path: Vec<RouteHop> },
1784 event_expectations: None,
1785 scorer_expectations: RefCell::new(None),
1789 fn expect(mut self, expectation: TestResult) -> Self {
1790 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1794 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1795 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1801 impl lightning::util::ser::Writeable for TestScorer {
1802 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1805 impl Score for TestScorer {
1806 fn channel_penalty_msat(
1807 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1809 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1810 match scorer_expectations.pop_front() {
1811 Some(expectation) => {
1812 assert_eq!(expectation.amount_msat, usage.amount_msat);
1813 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1821 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1822 if let Some(expectations) = &mut self.event_expectations {
1823 match expectations.pop_front() {
1824 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1825 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1826 assert_eq!(actual_short_channel_id, short_channel_id);
1828 Some(TestResult::PaymentSuccess { path }) => {
1829 panic!("Unexpected successful payment path: {:?}", path)
1831 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1836 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1837 if let Some(expectations) = &mut self.event_expectations {
1838 match expectations.pop_front() {
1839 Some(TestResult::PaymentFailure { path, .. }) => {
1840 panic!("Unexpected payment path failure: {:?}", path)
1842 Some(TestResult::PaymentSuccess { path }) => {
1843 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1845 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1850 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1851 if let Some(expectations) = &mut self.event_expectations {
1852 match expectations.pop_front() {
1853 Some(TestResult::PaymentFailure { path, .. }) => {
1854 panic!("Unexpected failed payment path: {:?}", path)
1856 Some(TestResult::PaymentSuccess { path }) => {
1857 panic!("Unexpected successful payment path: {:?}", path)
1859 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1863 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1864 if let Some(expectations) = &mut self.event_expectations {
1865 match expectations.pop_front() {
1866 Some(TestResult::PaymentFailure { path, .. }) => {
1867 panic!("Unexpected payment path failure: {:?}", path)
1869 Some(TestResult::PaymentSuccess { path }) => {
1870 panic!("Unexpected successful payment path: {:?}", path)
1872 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1878 impl Drop for TestScorer {
1879 fn drop(&mut self) {
1880 if std::thread::panicking() {
1884 if let Some(event_expectations) = &self.event_expectations {
1885 if !event_expectations.is_empty() {
1886 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1890 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1891 if !scorer_expectations.is_empty() {
1892 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1899 expectations: core::cell::RefCell<VecDeque<Amount>>,
1900 attempts: core::cell::RefCell<usize>,
1901 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1902 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1905 #[derive(Clone, Debug, PartialEq, Eq)]
1912 struct OnAttempt(usize);
1917 expectations: core::cell::RefCell::new(VecDeque::new()),
1918 attempts: core::cell::RefCell::new(0),
1919 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1920 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
1924 fn expect_send(self, value_msat: Amount) -> Self {
1925 self.expectations.borrow_mut().push_back(value_msat);
1929 fn fails_on_attempt(self, attempt: usize) -> Self {
1930 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
1931 self.fails_with(failure, OnAttempt(attempt))
1934 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
1935 self.fails_with(PaymentSendFailure::PartialFailure {
1936 results: results.unwrap_or(vec![]),
1937 failed_paths_retry: Some(retry),
1938 payment_id: PaymentId([1; 32]),
1942 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1943 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1947 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
1948 let mut attempts = self.attempts.borrow_mut();
1951 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1952 Some(failure) => Err(failure),
1957 fn check_value_msats(&self, actual_value_msats: Amount) {
1958 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1959 if let Some(expected_value_msats) = expected_value_msats {
1960 assert_eq!(actual_value_msats, expected_value_msats);
1962 panic!("Unexpected amount: {:?}", actual_value_msats);
1966 fn track_inflight_htlcs(&self, route: &Route) {
1967 for path in &route.paths {
1968 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
1972 fn fail_path(&self, path: &Vec<RouteHop>) {
1973 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
1975 if let Some(idx) = path_idx {
1976 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
1981 impl Drop for TestPayer {
1982 fn drop(&mut self) {
1983 if std::thread::panicking() {
1987 if !self.expectations.borrow().is_empty() {
1988 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1993 impl Payer for TestPayer {
1994 fn node_id(&self) -> PublicKey {
1995 let secp_ctx = Secp256k1::new();
1996 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1999 fn first_hops(&self) -> Vec<ChannelDetails> {
2004 &self, route: &Route, _payment_hash: PaymentHash,
2005 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2006 ) -> Result<(), PaymentSendFailure> {
2007 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2008 self.track_inflight_htlcs(route);
2009 self.check_attempts()
2012 fn send_spontaneous_payment(
2013 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2014 ) -> Result<(), PaymentSendFailure> {
2015 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2016 self.check_attempts()
2020 &self, route: &Route, _payment_id: PaymentId
2021 ) -> Result<(), PaymentSendFailure> {
2022 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2023 self.track_inflight_htlcs(route);
2024 self.check_attempts()
2027 fn abandon_payment(&self, _payment_id: PaymentId) { }
2029 fn inflight_htlcs(&self) -> InFlightHtlcs {
2030 let mut inflight_htlcs = InFlightHtlcs::new();
2031 for path in self.inflight_htlcs_paths.clone().into_inner() {
2032 inflight_htlcs.process_path(&path, self.node_id());
2038 // *** Full Featured Functional Tests with a Real ChannelManager ***
2039 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2041 impl Router for ManualRouter {
2043 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2044 _inflight_htlcs: InFlightHtlcs
2045 ) -> Result<Route, LightningError> {
2046 self.0.borrow_mut().pop_front().unwrap()
2049 impl ScoringRouter for ManualRouter {
2050 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2052 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2054 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2056 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2059 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2060 self.0.borrow_mut().push_back(result);
2063 impl Drop for ManualRouter {
2064 fn drop(&mut self) {
2065 if std::thread::panicking() {
2068 assert!(self.0.borrow_mut().is_empty());
2073 fn retry_multi_path_single_failed_payment() {
2074 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2075 let chanmon_cfgs = create_chanmon_cfgs(2);
2076 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2077 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2078 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2080 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2081 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2082 let chans = nodes[0].node.list_usable_channels();
2083 let mut route = Route {
2086 pubkey: nodes[1].node.get_our_node_id(),
2087 node_features: channelmanager::provided_node_features(),
2088 short_channel_id: chans[0].short_channel_id.unwrap(),
2089 channel_features: channelmanager::provided_channel_features(),
2091 cltv_expiry_delta: 100,
2094 pubkey: nodes[1].node.get_our_node_id(),
2095 node_features: channelmanager::provided_node_features(),
2096 short_channel_id: chans[1].short_channel_id.unwrap(),
2097 channel_features: channelmanager::provided_channel_features(),
2098 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2099 cltv_expiry_delta: 100,
2102 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2104 let router = ManualRouter(RefCell::new(VecDeque::new()));
2105 router.expect_find_route(Ok(route.clone()));
2106 // On retry, split the payment across both channels.
2107 route.paths[0][0].fee_msat = 50_000_001;
2108 route.paths[1][0].fee_msat = 50_000_000;
2109 router.expect_find_route(Ok(route.clone()));
2111 let event_handler = |_: Event| { panic!(); };
2112 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2114 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2115 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2116 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2118 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2119 assert_eq!(htlc_msgs.len(), 2);
2120 check_added_monitors!(nodes[0], 2);
2124 fn immediate_retry_on_failure() {
2125 // Tests that we can/will retry immediately after a failure
2126 let chanmon_cfgs = create_chanmon_cfgs(2);
2127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2131 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2132 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2133 let chans = nodes[0].node.list_usable_channels();
2134 let mut route = Route {
2137 pubkey: nodes[1].node.get_our_node_id(),
2138 node_features: channelmanager::provided_node_features(),
2139 short_channel_id: chans[0].short_channel_id.unwrap(),
2140 channel_features: channelmanager::provided_channel_features(),
2141 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2142 cltv_expiry_delta: 100,
2145 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2147 let router = ManualRouter(RefCell::new(VecDeque::new()));
2148 router.expect_find_route(Ok(route.clone()));
2149 // On retry, split the payment across both channels.
2150 route.paths.push(route.paths[0].clone());
2151 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2152 route.paths[0][0].fee_msat = 50_000_000;
2153 route.paths[1][0].fee_msat = 50_000_001;
2154 router.expect_find_route(Ok(route.clone()));
2156 let event_handler = |_: Event| { panic!(); };
2157 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2159 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2160 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2161 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2163 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2164 assert_eq!(htlc_msgs.len(), 2);
2165 check_added_monitors!(nodes[0], 2);
2169 fn no_extra_retries_on_back_to_back_fail() {
2170 // In a previous release, we had a race where we may exceed the payment retry count if we
2171 // get two failures in a row with the second having `all_paths_failed` set.
2172 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2173 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2174 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2175 // pending which we will see later. Thus, when we previously removed the retry tracking map
2176 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2177 // retry entry even though more events for the same payment were still pending. This led to
2178 // us retrying a payment again even though we'd already given up on it.
2180 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2181 // is used to remove the payment retry counter entries instead. This tests for the specific
2182 // excess-retry case while also testing `PaymentFailed` generation.
2184 let chanmon_cfgs = create_chanmon_cfgs(3);
2185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2187 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2189 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;
2190 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;
2192 let mut route = Route {
2195 pubkey: nodes[1].node.get_our_node_id(),
2196 node_features: channelmanager::provided_node_features(),
2197 short_channel_id: chan_1_scid,
2198 channel_features: channelmanager::provided_channel_features(),
2200 cltv_expiry_delta: 100,
2202 pubkey: nodes[2].node.get_our_node_id(),
2203 node_features: channelmanager::provided_node_features(),
2204 short_channel_id: chan_2_scid,
2205 channel_features: channelmanager::provided_channel_features(),
2206 fee_msat: 100_000_000,
2207 cltv_expiry_delta: 100,
2210 pubkey: nodes[1].node.get_our_node_id(),
2211 node_features: channelmanager::provided_node_features(),
2212 short_channel_id: chan_1_scid,
2213 channel_features: channelmanager::provided_channel_features(),
2215 cltv_expiry_delta: 100,
2217 pubkey: nodes[2].node.get_our_node_id(),
2218 node_features: channelmanager::provided_node_features(),
2219 short_channel_id: chan_2_scid,
2220 channel_features: channelmanager::provided_channel_features(),
2221 fee_msat: 100_000_000,
2222 cltv_expiry_delta: 100,
2225 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2227 let router = ManualRouter(RefCell::new(VecDeque::new()));
2228 router.expect_find_route(Ok(route.clone()));
2229 // On retry, we'll only be asked for one path
2230 route.paths.remove(1);
2231 router.expect_find_route(Ok(route.clone()));
2233 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2234 let event_handler = |event: Event| {
2235 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2236 event_checker(event);
2238 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2240 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2241 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2242 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2244 let htlc_updates = SendEvent::from_node(&nodes[0]);
2245 check_added_monitors!(nodes[0], 1);
2246 assert_eq!(htlc_updates.msgs.len(), 1);
2248 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2249 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2250 check_added_monitors!(nodes[1], 1);
2251 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2253 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2254 check_added_monitors!(nodes[0], 1);
2255 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2257 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2258 check_added_monitors!(nodes[0], 1);
2259 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2261 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2262 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2263 check_added_monitors!(nodes[1], 1);
2264 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2266 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2267 check_added_monitors!(nodes[1], 1);
2268 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2270 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2271 check_added_monitors!(nodes[0], 1);
2273 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2274 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2275 check_added_monitors!(nodes[0], 1);
2276 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2278 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2279 check_added_monitors!(nodes[1], 1);
2280 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2282 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2283 check_added_monitors!(nodes[1], 1);
2284 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2286 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2288 check_added_monitors!(nodes[0], 1);
2290 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2291 check_added_monitors!(nodes[0], 1);
2292 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2294 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2295 check_added_monitors!(nodes[1], 1);
2296 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2297 check_added_monitors!(nodes[1], 1);
2298 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2301 check_added_monitors!(nodes[0], 1);
2303 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2304 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2305 // with it set. The first event will use up the only retry we are allowed, with the second
2306 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2307 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2308 // if the final HTLC failed.
2309 expected_events.borrow_mut().push_back(&|ev: Event| {
2310 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2311 assert!(!payment_failed_permanently);
2312 assert!(all_paths_failed);
2313 } else { panic!("Unexpected event"); }
2315 nodes[0].node.process_pending_events(&invoice_payer);
2316 assert!(expected_events.borrow().is_empty());
2318 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2319 check_added_monitors!(nodes[0], 1);
2321 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2322 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2323 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2324 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2325 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2327 expected_events.borrow_mut().push_back(&|ev: Event| {
2328 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2329 assert!(!payment_failed_permanently);
2330 assert!(all_paths_failed);
2331 } else { panic!("Unexpected event"); }
2333 expected_events.borrow_mut().push_back(&|ev: Event| {
2334 if let Event::PaymentFailed { .. } = ev {
2335 } else { panic!("Unexpected event"); }
2337 nodes[0].node.process_pending_events(&invoice_payer);
2338 assert!(expected_events.borrow().is_empty());