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::errors::APIError;
151 use lightning::util::events::{Event, EventHandler};
152 use lightning::util::logger::Logger;
153 use crate::time_utils::Time;
154 use crate::sync::Mutex;
156 use secp256k1::PublicKey;
159 use core::fmt::{Debug, Display, Formatter};
160 use core::future::Future;
161 use core::ops::Deref;
162 use core::time::Duration;
163 #[cfg(feature = "std")]
164 use std::time::SystemTime;
166 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
168 /// See [module-level documentation] for details.
170 /// [module-level documentation]: crate::payment
171 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
173 #[cfg(not(feature = "no-std"))]
174 type ConfiguredTime = std::time::Instant;
175 #[cfg(feature = "no-std")]
176 use crate::time_utils;
177 #[cfg(feature = "no-std")]
178 type ConfiguredTime = time_utils::Eternity;
180 /// Sealed trait with a blanket implementation to allow both sync and async implementations of event
181 /// handling to exist within the InvoicePayer.
183 pub trait BaseEventHandler {}
184 impl<T> BaseEventHandler for T {}
187 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
188 pub struct InvoicePayerUsingTime<
192 E: sealed::BaseEventHandler,
202 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
203 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
207 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
208 /// currently being made, or have outstanding paths that need retrying.
209 struct PaymentInfo<T: Time> {
210 attempts: PaymentAttempts<T>,
211 paths: Vec<Vec<RouteHop>>,
214 impl<T: Time> PaymentInfo<T> {
217 attempts: PaymentAttempts::new(),
223 /// Storing minimal payment attempts information required for determining if a outbound payment can
225 #[derive(Clone, Copy)]
226 struct PaymentAttempts<T: Time> {
227 /// This count will be incremented only after the result of the attempt is known. When it's 0,
228 /// it means the result of the first attempt is now known yet.
230 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
231 first_attempted_at: T
234 impl<T: Time> PaymentAttempts<T> {
238 first_attempted_at: T::now()
243 impl<T: Time> Display for PaymentAttempts<T> {
244 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
245 #[cfg(feature = "no-std")]
246 return write!( f, "attempts: {}", self.count);
247 #[cfg(not(feature = "no-std"))]
250 "attempts: {}, duration: {}s",
252 T::now().duration_since(self.first_attempted_at).as_secs()
257 /// A trait defining behavior of an [`Invoice`] payer.
259 /// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls
260 /// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts.
262 /// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`].
264 /// In order to trivially ensure idempotency for payments, the default `Payer` implementation
265 /// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to
266 /// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map
267 /// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key.
269 /// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager
271 /// Returns the payer's node id.
272 fn node_id(&self) -> PublicKey;
274 /// Returns the payer's channels.
275 fn first_hops(&self) -> Vec<ChannelDetails>;
277 /// Sends a payment over the Lightning Network using the given [`Route`].
279 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
280 payment_id: PaymentId
281 ) -> Result<(), PaymentSendFailure>;
283 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
284 fn send_spontaneous_payment(
285 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId
286 ) -> Result<(), PaymentSendFailure>;
288 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
289 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
291 /// Signals that no further retries for the given payment will occur.
292 fn abandon_payment(&self, payment_id: PaymentId);
294 /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
296 fn inflight_htlcs(&self) -> InFlightHtlcs;
299 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
300 /// based on payment and probe success/failure.
302 /// [`Router`]: lightning::routing::router::Router
303 pub trait ScoringRouter: Router {
304 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
305 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
306 fn find_route_with_id(
307 &self, payer: &PublicKey, route_params: &RouteParameters,
308 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
309 _payment_hash: PaymentHash, _payment_id: PaymentId
310 ) -> Result<Route, LightningError> {
311 self.find_route(payer, route_params, first_hops, inflight_htlcs)
313 /// Lets the router know that payment through a specific path has failed.
314 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
315 /// Lets the router know that payment through a specific path was successful.
316 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
317 /// Lets the router know that a payment probe was successful.
318 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
319 /// Lets the router know that a payment probe failed.
320 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
323 /// Strategies available to retry payment path failures for an [`Invoice`].
325 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
327 /// Max number of attempts to retry payment.
329 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
330 /// payments, if this is less than the total number of paths, we will never even retry all of the
333 #[cfg(feature = "std")]
334 /// Time elapsed before abandoning retries for a payment.
339 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
340 match (self, attempts) {
341 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
342 max_retry_count >= &count
344 #[cfg(feature = "std")]
345 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
346 *max_duration >= T::now().duration_since(*first_attempted_at),
351 /// An error that may occur when making a payment.
352 #[derive(Clone, Debug)]
353 pub enum PaymentError {
354 /// An error resulting from the provided [`Invoice`] or payment hash.
355 Invoice(&'static str),
356 /// An error occurring when finding a route.
357 Routing(LightningError),
358 /// An error occurring when sending a payment.
359 Sending(PaymentSendFailure),
362 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
363 InvoicePayerUsingTime<P, R, L, E, T>
368 /// Creates an invoice payer that retries failed payment paths.
370 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
371 /// `retry` has been exceeded for a given [`Invoice`].
373 payer: P, router: R, logger: L, event_handler: E, retry: Retry
380 payment_cache: Mutex::new(HashMap::new()),
385 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
387 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
388 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
389 /// a second payment with the same [`PaymentHash`] is never sent.
391 /// If you wish to use a different payment idempotency token, see
392 /// [`Self::pay_invoice_with_id`].
393 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
394 let payment_id = PaymentId(invoice.payment_hash().into_inner());
395 self.pay_invoice_with_id(invoice, payment_id).map(|()| payment_id)
398 /// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use
399 /// in case a retry is needed.
401 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
402 /// payment completes or fails, no idempotency guarantees are made.
404 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
405 /// has never been paid before.
407 /// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency
409 pub fn pay_invoice_with_id(&self, invoice: &Invoice, payment_id: PaymentId) -> Result<(), PaymentError> {
410 if invoice.amount_milli_satoshis().is_none() {
411 Err(PaymentError::Invoice("amount missing"))
413 self.pay_invoice_using_amount(invoice, None, payment_id)
417 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
418 /// case a retry is needed.
420 /// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long
421 /// as the payment is still pending. Once the payment completes or fails, you must ensure that
422 /// a second payment with the same [`PaymentHash`] is never sent.
424 /// If you wish to use a different payment idempotency token, see
425 /// [`Self::pay_zero_value_invoice_with_id`].
426 pub fn pay_zero_value_invoice(
427 &self, invoice: &Invoice, amount_msats: u64
428 ) -> Result<PaymentId, PaymentError> {
429 let payment_id = PaymentId(invoice.payment_hash().into_inner());
430 self.pay_zero_value_invoice_with_id(invoice, amount_msats, payment_id).map(|()| payment_id)
433 /// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key,
434 /// caching the invoice for later use in case a retry is needed.
436 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
437 /// payment completes or fails, no idempotency guarantees are made.
439 /// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`]
440 /// has never been paid before.
442 /// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the
443 /// idempotency token.
444 pub fn pay_zero_value_invoice_with_id(
445 &self, invoice: &Invoice, amount_msats: u64, payment_id: PaymentId
446 ) -> Result<(), PaymentError> {
447 if invoice.amount_milli_satoshis().is_some() {
448 Err(PaymentError::Invoice("amount unexpected"))
450 self.pay_invoice_using_amount(invoice, Some(amount_msats), payment_id)
454 fn pay_invoice_using_amount(
455 &self, invoice: &Invoice, amount_msats: Option<u64>, payment_id: PaymentId
456 ) -> Result<(), PaymentError> {
457 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
459 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
460 match self.payment_cache.lock().unwrap().entry(payment_hash) {
461 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
462 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
465 let payment_secret = Some(invoice.payment_secret().clone());
466 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
467 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
468 .with_route_hints(invoice.route_hints());
469 if let Some(features) = invoice.features() {
470 payment_params = payment_params.with_features(features.clone());
472 let route_params = RouteParameters {
474 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
475 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
478 let send_payment = |route: &Route| {
479 self.payer.send_payment(route, payment_hash, &payment_secret, payment_id)
482 self.pay_internal(&route_params, payment_hash, send_payment)
483 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
486 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
487 /// case a retry is needed.
489 /// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency
490 /// as long as the payment is still pending. Once the payment completes or fails, you must
491 /// ensure that a second payment with the same [`PaymentPreimage`] is never sent.
493 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
494 final_cltv_expiry_delta: u32
495 ) -> Result<PaymentId, PaymentError> {
496 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
497 let payment_id = PaymentId(payment_hash.0);
498 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
499 final_cltv_expiry_delta)
500 .map(|()| payment_id)
503 /// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key,
504 /// caching the invoice for later use in case a retry is needed.
506 /// Note that idempotency is only guaranteed as long as the payment is still pending. Once the
507 /// payment completes or fails, no idempotency guarantees are made.
509 /// You should ensure that the [`PaymentPreimage`] is unique and the corresponding
510 /// [`PaymentHash`] has never been paid before.
511 pub fn pay_pubkey_with_id(
512 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_id: PaymentId,
513 amount_msats: u64, final_cltv_expiry_delta: u32
514 ) -> Result<(), PaymentError> {
515 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
516 self.do_pay_pubkey(pubkey, payment_preimage, payment_hash, payment_id, amount_msats,
517 final_cltv_expiry_delta)
521 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, payment_hash: PaymentHash,
522 payment_id: PaymentId, amount_msats: u64, final_cltv_expiry_delta: u32
523 ) -> Result<(), PaymentError> {
524 match self.payment_cache.lock().unwrap().entry(payment_hash) {
525 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
526 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
529 let route_params = RouteParameters {
530 payment_params: PaymentParameters::for_keysend(pubkey),
531 final_value_msat: amount_msats,
532 final_cltv_expiry_delta,
535 let send_payment = |route: &Route| {
536 self.payer.send_spontaneous_payment(route, payment_preimage, payment_id)
538 self.pay_internal(&route_params, payment_hash, send_payment)
539 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
542 fn pay_internal<F: FnOnce(&Route) -> Result<(), PaymentSendFailure> + Copy>(
543 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
544 ) -> Result<(), PaymentError> {
545 #[cfg(feature = "std")] {
546 if has_expired(params) {
547 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
548 return Err(PaymentError::Invoice("Invoice expired prior to send"));
552 let payer = self.payer.node_id();
553 let first_hops = self.payer.first_hops();
554 let inflight_htlcs = self.payer.inflight_htlcs();
555 let route = self.router.find_route(
556 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
557 ).map_err(|e| PaymentError::Routing(e))?;
559 match send_payment(&route) {
561 for path in route.paths {
562 self.process_path_inflight_htlcs(payment_hash, path);
567 PaymentSendFailure::ParameterError(_) => Err(e),
568 PaymentSendFailure::PathParameterError(_) => Err(e),
569 PaymentSendFailure::DuplicatePayment => Err(e),
570 PaymentSendFailure::AllFailedResendSafe(_) => {
571 let mut payment_cache = self.payment_cache.lock().unwrap();
572 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
573 payment_info.attempts.count += 1;
574 if self.retry.is_retryable_now(&payment_info.attempts) {
575 core::mem::drop(payment_cache);
576 Ok(self.pay_internal(params, payment_hash, send_payment)?)
581 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
582 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
583 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
584 // means that we are still waiting for our channel monitor update to be completed.
585 for (result, path) in results.iter().zip(route.paths.into_iter()) {
587 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
588 self.process_path_inflight_htlcs(payment_hash, path);
594 if let Some(retry_data) = failed_paths_retry {
595 // Some paths were sent, even if we failed to send the full MPP value our
596 // recipient may misbehave and claim the funds, at which point we have to
597 // consider the payment sent, so return `Ok()` here, ignoring any retry
599 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
602 // This may happen if we send a payment and some paths fail, but
603 // only due to a temporary monitor failure or the like, implying
604 // they're really in-flight, but we haven't sent the initial
605 // HTLC-Add messages yet.
610 }.map_err(|e| PaymentError::Sending(e))
613 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
614 // that are pending retry.
615 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
616 self.payment_cache.lock().unwrap().entry(payment_hash)
617 .or_insert_with(|| PaymentInfo::new())
621 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
622 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
623 self.payment_cache.lock().unwrap().entry(payment_hash)
624 .and_modify(|payment_info| {
625 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
626 payment_info.paths.swap_remove(idx);
632 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
633 ) -> Result<(), ()> {
634 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
635 .and_modify(|info| info.attempts.count += 1 )
636 .or_insert_with(|| PaymentInfo {
637 attempts: PaymentAttempts {
639 first_attempted_at: T::now(),
644 if !self.retry.is_retryable_now(&attempts) {
645 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
649 #[cfg(feature = "std")] {
650 if has_expired(params) {
651 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
656 let payer = self.payer.node_id();
657 let first_hops = self.payer.first_hops();
658 let inflight_htlcs = self.payer.inflight_htlcs();
660 let route = self.router.find_route(
661 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
665 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
669 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
671 for path in route.unwrap().paths.into_iter() {
672 self.process_path_inflight_htlcs(payment_hash, path);
676 Err(PaymentSendFailure::ParameterError(_)) |
677 Err(PaymentSendFailure::PathParameterError(_)) => {
678 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
681 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
682 self.retry_payment(payment_id, payment_hash, params)
684 Err(PaymentSendFailure::DuplicatePayment) => {
685 log_error!(self.logger, "Got a DuplicatePayment error when attempting to retry a payment, this shouldn't happen.");
688 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
689 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
690 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
691 // means that we are still waiting for our channel monitor update to complete.
692 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
694 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
695 self.process_path_inflight_htlcs(payment_hash, path);
701 if let Some(retry) = failed_paths_retry {
702 // Always return Ok for the same reason as noted in pay_internal.
703 let _ = self.retry_payment(payment_id, payment_hash, &retry);
710 /// Removes the payment cached by the given payment hash.
712 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
713 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
714 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
715 self.payment_cache.lock().unwrap().remove(payment_hash);
719 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
720 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
723 #[cfg(feature = "std")]
724 fn has_expired(route_params: &RouteParameters) -> bool {
725 if let Some(expiry_time) = route_params.payment_params.expiry_time {
726 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
730 impl<P: Deref, R: ScoringRouter, L: Deref, E: sealed::BaseEventHandler, T: Time>
731 InvoicePayerUsingTime<P, R, L, E, T>
736 /// Returns a bool indicating whether the processed event should be forwarded to a user-provided
738 fn handle_event_internal(&self, event: &Event) -> bool {
740 Event::PaymentPathFailed { payment_hash, path, .. }
741 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
742 | Event::ProbeSuccessful { payment_hash, path, .. }
743 | Event::ProbeFailed { payment_hash, path, .. } => {
744 self.remove_path_inflight_htlcs(*payment_hash, path);
750 Event::PaymentPathFailed {
751 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
753 if let Some(short_channel_id) = short_channel_id {
754 let path = path.iter().collect::<Vec<_>>();
755 self.router.notify_payment_path_failed(&path, *short_channel_id)
758 if payment_id.is_none() {
759 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
760 } else if *payment_failed_permanently {
761 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
762 self.payer.abandon_payment(payment_id.unwrap());
763 } else if retry.is_none() {
764 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
765 self.payer.abandon_payment(payment_id.unwrap());
766 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
767 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
770 self.payer.abandon_payment(payment_id.unwrap());
773 Event::PaymentFailed { payment_hash, .. } => {
774 self.remove_cached_payment(&payment_hash);
776 Event::PaymentPathSuccessful { path, .. } => {
777 let path = path.iter().collect::<Vec<_>>();
778 self.router.notify_payment_path_successful(&path);
780 Event::PaymentSent { payment_hash, .. } => {
781 let mut payment_cache = self.payment_cache.lock().unwrap();
782 let attempts = payment_cache
783 .remove(payment_hash)
784 .map_or(1, |payment_info| payment_info.attempts.count + 1);
785 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
787 Event::ProbeSuccessful { payment_hash, path, .. } => {
788 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
789 let path = path.iter().collect::<Vec<_>>();
790 self.router.notify_payment_probe_successful(&path);
792 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
793 if let Some(short_channel_id) = short_channel_id {
794 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
795 let path = path.iter().collect::<Vec<_>>();
796 self.router.notify_payment_probe_failed(&path, *short_channel_id);
802 // Delegate to the decorated event handler unless the payment is retried.
807 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
808 EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
813 fn handle_event(&self, event: Event) {
814 let should_forward = self.handle_event_internal(&event);
816 self.event_handler.handle_event(event)
821 impl<P: Deref, R: ScoringRouter, L: Deref, T: Time, F: Future, H: Fn(Event) -> F>
822 InvoicePayerUsingTime<P, R, L, H, T>
827 /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event
828 /// handler, if necessary, to handle them asynchronously.
829 pub async fn handle_event_async(&self, event: Event) {
830 let should_forward = self.handle_event_internal(&event);
832 (self.event_handler)(event).await;
840 use crate::{InvoiceBuilder, Currency};
841 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
842 use bitcoin_hashes::sha256::Hash as Sha256;
843 use lightning::ln::PaymentPreimage;
844 use lightning::ln::channelmanager;
845 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
846 use lightning::ln::functional_test_utils::*;
847 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
848 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
849 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
850 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
851 use lightning::util::test_utils::TestLogger;
852 use lightning::util::errors::APIError;
853 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
854 use secp256k1::{SecretKey, PublicKey, Secp256k1};
855 use std::cell::RefCell;
856 use std::collections::VecDeque;
857 use std::ops::DerefMut;
858 use std::time::{SystemTime, Duration};
859 use crate::time_utils::tests::SinceEpoch;
860 use crate::DEFAULT_EXPIRY_TIME;
862 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
863 let payment_hash = Sha256::hash(&payment_preimage.0);
864 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
866 InvoiceBuilder::new(Currency::Bitcoin)
867 .description("test".into())
868 .payment_hash(payment_hash)
869 .payment_secret(PaymentSecret([0; 32]))
870 .duration_since_epoch(duration_since_epoch())
871 .min_final_cltv_expiry(144)
872 .amount_milli_satoshis(128)
873 .build_signed(|hash| {
874 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
879 fn duration_since_epoch() -> Duration {
880 #[cfg(feature = "std")]
881 let duration_since_epoch =
882 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
883 #[cfg(not(feature = "std"))]
884 let duration_since_epoch = Duration::from_secs(1234567);
888 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
889 let payment_hash = Sha256::hash(&payment_preimage.0);
890 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
892 InvoiceBuilder::new(Currency::Bitcoin)
893 .description("test".into())
894 .payment_hash(payment_hash)
895 .payment_secret(PaymentSecret([0; 32]))
896 .duration_since_epoch(duration_since_epoch())
897 .min_final_cltv_expiry(144)
898 .build_signed(|hash| {
899 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
904 #[cfg(feature = "std")]
905 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
906 let payment_hash = Sha256::hash(&payment_preimage.0);
907 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
908 let duration = duration_since_epoch()
909 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
911 InvoiceBuilder::new(Currency::Bitcoin)
912 .description("test".into())
913 .payment_hash(payment_hash)
914 .payment_secret(PaymentSecret([0; 32]))
915 .duration_since_epoch(duration)
916 .min_final_cltv_expiry(144)
917 .amount_milli_satoshis(128)
918 .build_signed(|hash| {
919 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
924 fn pubkey() -> PublicKey {
925 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
929 fn pays_invoice_on_first_attempt() {
930 let event_handled = core::cell::RefCell::new(false);
931 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
933 let payment_preimage = PaymentPreimage([1; 32]);
934 let invoice = invoice(payment_preimage);
935 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
936 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
938 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
939 let router = TestRouter::new(TestScorer::new());
940 let logger = TestLogger::new();
942 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
944 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
945 assert_eq!(*payer.attempts.borrow(), 1);
947 invoice_payer.handle_event(Event::PaymentSent {
948 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
950 assert_eq!(*event_handled.borrow(), true);
951 assert_eq!(*payer.attempts.borrow(), 1);
955 fn pays_invoice_on_retry() {
956 let event_handled = core::cell::RefCell::new(false);
957 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
959 let payment_preimage = PaymentPreimage([1; 32]);
960 let invoice = invoice(payment_preimage);
961 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
962 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
964 let payer = TestPayer::new()
965 .expect_send(Amount::ForInvoice(final_value_msat))
966 .expect_send(Amount::OnRetry(final_value_msat / 2));
967 let router = TestRouter::new(TestScorer::new());
968 let logger = TestLogger::new();
970 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
972 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
973 assert_eq!(*payer.attempts.borrow(), 1);
975 let event = Event::PaymentPathFailed {
978 network_update: None,
979 payment_failed_permanently: false,
980 all_paths_failed: false,
981 path: TestRouter::path_for_value(final_value_msat),
982 short_channel_id: None,
983 retry: Some(TestRouter::retry_for_invoice(&invoice)),
985 invoice_payer.handle_event(event);
986 assert_eq!(*event_handled.borrow(), false);
987 assert_eq!(*payer.attempts.borrow(), 2);
989 invoice_payer.handle_event(Event::PaymentSent {
990 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
992 assert_eq!(*event_handled.borrow(), true);
993 assert_eq!(*payer.attempts.borrow(), 2);
997 fn pays_invoice_on_partial_failure() {
998 let event_handler = |_: Event| { panic!() };
1000 let payment_preimage = PaymentPreimage([1; 32]);
1001 let invoice = invoice(payment_preimage);
1002 let retry = TestRouter::retry_for_invoice(&invoice);
1003 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1005 let payer = TestPayer::new()
1006 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
1007 .fails_with_partial_failure(retry, OnAttempt(2), None)
1008 .expect_send(Amount::ForInvoice(final_value_msat))
1009 .expect_send(Amount::OnRetry(final_value_msat / 2))
1010 .expect_send(Amount::OnRetry(final_value_msat / 2));
1011 let router = TestRouter::new(TestScorer::new());
1012 let logger = TestLogger::new();
1014 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1016 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1020 fn retries_payment_path_for_unknown_payment() {
1021 let event_handled = core::cell::RefCell::new(false);
1022 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1024 let payment_preimage = PaymentPreimage([1; 32]);
1025 let invoice = invoice(payment_preimage);
1026 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1027 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1029 let payer = TestPayer::new()
1030 .expect_send(Amount::OnRetry(final_value_msat / 2))
1031 .expect_send(Amount::OnRetry(final_value_msat / 2));
1032 let router = TestRouter::new(TestScorer::new());
1033 let logger = TestLogger::new();
1035 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1037 let payment_id = Some(PaymentId([1; 32]));
1038 let event = Event::PaymentPathFailed {
1041 network_update: None,
1042 payment_failed_permanently: false,
1043 all_paths_failed: false,
1044 path: TestRouter::path_for_value(final_value_msat),
1045 short_channel_id: None,
1046 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1048 invoice_payer.handle_event(event.clone());
1049 assert_eq!(*event_handled.borrow(), false);
1050 assert_eq!(*payer.attempts.borrow(), 1);
1052 invoice_payer.handle_event(event.clone());
1053 assert_eq!(*event_handled.borrow(), false);
1054 assert_eq!(*payer.attempts.borrow(), 2);
1056 invoice_payer.handle_event(Event::PaymentSent {
1057 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1059 assert_eq!(*event_handled.borrow(), true);
1060 assert_eq!(*payer.attempts.borrow(), 2);
1064 fn fails_paying_invoice_after_max_retry_counts() {
1065 let event_handled = core::cell::RefCell::new(false);
1066 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1068 let payment_preimage = PaymentPreimage([1; 32]);
1069 let invoice = invoice(payment_preimage);
1070 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1072 let payer = TestPayer::new()
1073 .expect_send(Amount::ForInvoice(final_value_msat))
1074 .expect_send(Amount::OnRetry(final_value_msat / 2))
1075 .expect_send(Amount::OnRetry(final_value_msat / 2));
1076 let router = TestRouter::new(TestScorer::new());
1077 let logger = TestLogger::new();
1079 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1081 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1082 assert_eq!(*payer.attempts.borrow(), 1);
1084 let event = Event::PaymentPathFailed {
1086 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1087 network_update: None,
1088 payment_failed_permanently: false,
1089 all_paths_failed: true,
1090 path: TestRouter::path_for_value(final_value_msat),
1091 short_channel_id: None,
1092 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1094 invoice_payer.handle_event(event);
1095 assert_eq!(*event_handled.borrow(), false);
1096 assert_eq!(*payer.attempts.borrow(), 2);
1098 let event = Event::PaymentPathFailed {
1100 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1101 network_update: None,
1102 payment_failed_permanently: false,
1103 all_paths_failed: false,
1104 path: TestRouter::path_for_value(final_value_msat / 2),
1105 short_channel_id: None,
1106 retry: Some(RouteParameters {
1107 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1110 invoice_payer.handle_event(event.clone());
1111 assert_eq!(*event_handled.borrow(), false);
1112 assert_eq!(*payer.attempts.borrow(), 3);
1114 invoice_payer.handle_event(event.clone());
1115 assert_eq!(*event_handled.borrow(), true);
1116 assert_eq!(*payer.attempts.borrow(), 3);
1119 #[cfg(feature = "std")]
1121 fn fails_paying_invoice_after_max_retry_timeout() {
1122 let event_handled = core::cell::RefCell::new(false);
1123 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1125 let payment_preimage = PaymentPreimage([1; 32]);
1126 let invoice = invoice(payment_preimage);
1127 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1129 let payer = TestPayer::new()
1130 .expect_send(Amount::ForInvoice(final_value_msat))
1131 .expect_send(Amount::OnRetry(final_value_msat / 2));
1133 let router = TestRouter::new(TestScorer::new());
1134 let logger = TestLogger::new();
1135 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1138 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1140 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1141 assert_eq!(*payer.attempts.borrow(), 1);
1143 let event = Event::PaymentPathFailed {
1145 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1146 network_update: None,
1147 payment_failed_permanently: false,
1148 all_paths_failed: true,
1149 path: TestRouter::path_for_value(final_value_msat),
1150 short_channel_id: None,
1151 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1153 invoice_payer.handle_event(event.clone());
1154 assert_eq!(*event_handled.borrow(), false);
1155 assert_eq!(*payer.attempts.borrow(), 2);
1157 SinceEpoch::advance(Duration::from_secs(121));
1159 invoice_payer.handle_event(event.clone());
1160 assert_eq!(*event_handled.borrow(), true);
1161 assert_eq!(*payer.attempts.borrow(), 2);
1165 fn fails_paying_invoice_with_missing_retry_params() {
1166 let event_handled = core::cell::RefCell::new(false);
1167 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1169 let payment_preimage = PaymentPreimage([1; 32]);
1170 let invoice = invoice(payment_preimage);
1171 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1173 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1174 let router = TestRouter::new(TestScorer::new());
1175 let logger = TestLogger::new();
1177 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1179 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1180 assert_eq!(*payer.attempts.borrow(), 1);
1182 let event = Event::PaymentPathFailed {
1184 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1185 network_update: None,
1186 payment_failed_permanently: false,
1187 all_paths_failed: false,
1189 short_channel_id: None,
1192 invoice_payer.handle_event(event);
1193 assert_eq!(*event_handled.borrow(), true);
1194 assert_eq!(*payer.attempts.borrow(), 1);
1197 // Expiration is checked only in an std environment
1198 #[cfg(feature = "std")]
1200 fn fails_paying_invoice_after_expiration() {
1201 let event_handled = core::cell::RefCell::new(false);
1202 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1204 let payer = TestPayer::new();
1205 let router = TestRouter::new(TestScorer::new());
1206 let logger = TestLogger::new();
1208 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1210 let payment_preimage = PaymentPreimage([1; 32]);
1211 let invoice = expired_invoice(payment_preimage);
1212 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1213 assert_eq!(msg, "Invoice expired prior to send");
1214 } else { panic!("Expected Invoice Error"); }
1217 // Expiration is checked only in an std environment
1218 #[cfg(feature = "std")]
1220 fn fails_retrying_invoice_after_expiration() {
1221 let event_handled = core::cell::RefCell::new(false);
1222 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1224 let payment_preimage = PaymentPreimage([1; 32]);
1225 let invoice = invoice(payment_preimage);
1226 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1228 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1229 let router = TestRouter::new(TestScorer::new());
1230 let logger = TestLogger::new();
1232 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1234 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1235 assert_eq!(*payer.attempts.borrow(), 1);
1237 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1238 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1239 .checked_sub(Duration::from_secs(2)).unwrap()
1240 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1241 let event = Event::PaymentPathFailed {
1243 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1244 network_update: None,
1245 payment_failed_permanently: false,
1246 all_paths_failed: false,
1248 short_channel_id: None,
1249 retry: Some(retry_data),
1251 invoice_payer.handle_event(event);
1252 assert_eq!(*event_handled.borrow(), true);
1253 assert_eq!(*payer.attempts.borrow(), 1);
1257 fn fails_paying_invoice_after_retry_error() {
1258 let event_handled = core::cell::RefCell::new(false);
1259 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1261 let payment_preimage = PaymentPreimage([1; 32]);
1262 let invoice = invoice(payment_preimage);
1263 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1265 let payer = TestPayer::new()
1266 .fails_on_attempt(2)
1267 .expect_send(Amount::ForInvoice(final_value_msat))
1268 .expect_send(Amount::OnRetry(final_value_msat / 2));
1269 let router = TestRouter::new(TestScorer::new());
1270 let logger = TestLogger::new();
1272 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1274 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1275 assert_eq!(*payer.attempts.borrow(), 1);
1277 let event = Event::PaymentPathFailed {
1279 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1280 network_update: None,
1281 payment_failed_permanently: false,
1282 all_paths_failed: false,
1283 path: TestRouter::path_for_value(final_value_msat / 2),
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);
1289 assert_eq!(*payer.attempts.borrow(), 2);
1293 fn fails_paying_invoice_after_rejected_by_payee() {
1294 let event_handled = core::cell::RefCell::new(false);
1295 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1297 let payment_preimage = PaymentPreimage([1; 32]);
1298 let invoice = invoice(payment_preimage);
1299 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1301 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1302 let router = TestRouter::new(TestScorer::new());
1303 let logger = TestLogger::new();
1305 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1307 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1308 assert_eq!(*payer.attempts.borrow(), 1);
1310 let event = Event::PaymentPathFailed {
1312 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1313 network_update: None,
1314 payment_failed_permanently: true,
1315 all_paths_failed: false,
1317 short_channel_id: None,
1318 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1320 invoice_payer.handle_event(event);
1321 assert_eq!(*event_handled.borrow(), true);
1322 assert_eq!(*payer.attempts.borrow(), 1);
1326 fn fails_repaying_invoice_with_pending_payment() {
1327 let event_handled = core::cell::RefCell::new(false);
1328 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1330 let payment_preimage = PaymentPreimage([1; 32]);
1331 let invoice = invoice(payment_preimage);
1332 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1334 let payer = TestPayer::new()
1335 .expect_send(Amount::ForInvoice(final_value_msat))
1336 .expect_send(Amount::ForInvoice(final_value_msat));
1337 let router = TestRouter::new(TestScorer::new());
1338 let logger = TestLogger::new();
1340 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1342 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1344 // Cannot repay an invoice pending payment.
1345 match invoice_payer.pay_invoice(&invoice) {
1346 Err(PaymentError::Invoice("payment pending")) => {},
1347 Err(_) => panic!("unexpected error"),
1348 Ok(_) => panic!("expected invoice error"),
1351 // Can repay an invoice once cleared from cache.
1352 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1353 invoice_payer.remove_cached_payment(&payment_hash);
1354 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1356 // Cannot retry paying an invoice if cleared from cache.
1357 invoice_payer.remove_cached_payment(&payment_hash);
1358 let event = Event::PaymentPathFailed {
1361 network_update: None,
1362 payment_failed_permanently: false,
1363 all_paths_failed: false,
1365 short_channel_id: None,
1366 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1368 invoice_payer.handle_event(event);
1369 assert_eq!(*event_handled.borrow(), true);
1373 fn fails_paying_invoice_with_routing_errors() {
1374 let payer = TestPayer::new();
1375 let router = FailingRouter {};
1376 let logger = TestLogger::new();
1378 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1380 let payment_preimage = PaymentPreimage([1; 32]);
1381 let invoice = invoice(payment_preimage);
1382 match invoice_payer.pay_invoice(&invoice) {
1383 Err(PaymentError::Routing(_)) => {},
1384 Err(_) => panic!("unexpected error"),
1385 Ok(_) => panic!("expected routing error"),
1390 fn fails_paying_invoice_with_sending_errors() {
1391 let payment_preimage = PaymentPreimage([1; 32]);
1392 let invoice = invoice(payment_preimage);
1393 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1395 let payer = TestPayer::new()
1396 .fails_on_attempt(1)
1397 .expect_send(Amount::ForInvoice(final_value_msat));
1398 let router = TestRouter::new(TestScorer::new());
1399 let logger = TestLogger::new();
1401 InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0));
1403 match invoice_payer.pay_invoice(&invoice) {
1404 Err(PaymentError::Sending(_)) => {},
1405 Err(_) => panic!("unexpected error"),
1406 Ok(_) => panic!("expected sending error"),
1411 fn pays_zero_value_invoice_using_amount() {
1412 let event_handled = core::cell::RefCell::new(false);
1413 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1415 let payment_preimage = PaymentPreimage([1; 32]);
1416 let invoice = zero_value_invoice(payment_preimage);
1417 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1418 let final_value_msat = 100;
1420 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1421 let router = TestRouter::new(TestScorer::new());
1422 let logger = TestLogger::new();
1424 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1427 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1428 assert_eq!(*payer.attempts.borrow(), 1);
1430 invoice_payer.handle_event(Event::PaymentSent {
1431 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1433 assert_eq!(*event_handled.borrow(), true);
1434 assert_eq!(*payer.attempts.borrow(), 1);
1438 fn fails_paying_zero_value_invoice_with_amount() {
1439 let event_handled = core::cell::RefCell::new(false);
1440 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1442 let payer = TestPayer::new();
1443 let router = TestRouter::new(TestScorer::new());
1444 let logger = TestLogger::new();
1446 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1448 let payment_preimage = PaymentPreimage([1; 32]);
1449 let invoice = invoice(payment_preimage);
1451 // Cannot repay an invoice pending payment.
1452 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1453 Err(PaymentError::Invoice("amount unexpected")) => {},
1454 Err(_) => panic!("unexpected error"),
1455 Ok(_) => panic!("expected invoice error"),
1460 fn pays_pubkey_with_amount() {
1461 let event_handled = core::cell::RefCell::new(false);
1462 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1464 let pubkey = pubkey();
1465 let payment_preimage = PaymentPreimage([1; 32]);
1466 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1467 let final_value_msat = 100;
1468 let final_cltv_expiry_delta = 42;
1470 let payer = TestPayer::new()
1471 .expect_send(Amount::Spontaneous(final_value_msat))
1472 .expect_send(Amount::OnRetry(final_value_msat));
1473 let router = TestRouter::new(TestScorer::new());
1474 let logger = TestLogger::new();
1476 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1478 let payment_id = Some(invoice_payer.pay_pubkey(
1479 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1481 assert_eq!(*payer.attempts.borrow(), 1);
1483 let retry = RouteParameters {
1484 payment_params: PaymentParameters::for_keysend(pubkey),
1486 final_cltv_expiry_delta,
1488 let event = Event::PaymentPathFailed {
1491 network_update: None,
1492 payment_failed_permanently: false,
1493 all_paths_failed: false,
1495 short_channel_id: None,
1498 invoice_payer.handle_event(event);
1499 assert_eq!(*event_handled.borrow(), false);
1500 assert_eq!(*payer.attempts.borrow(), 2);
1502 invoice_payer.handle_event(Event::PaymentSent {
1503 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1505 assert_eq!(*event_handled.borrow(), true);
1506 assert_eq!(*payer.attempts.borrow(), 2);
1510 fn scores_failed_channel() {
1511 let event_handled = core::cell::RefCell::new(false);
1512 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1514 let payment_preimage = PaymentPreimage([1; 32]);
1515 let invoice = invoice(payment_preimage);
1516 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1517 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1518 let path = TestRouter::path_for_value(final_value_msat);
1519 let short_channel_id = Some(path[0].short_channel_id);
1521 // Expect that scorer is given short_channel_id upon handling the event.
1522 let payer = TestPayer::new()
1523 .expect_send(Amount::ForInvoice(final_value_msat))
1524 .expect_send(Amount::OnRetry(final_value_msat / 2));
1525 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1526 path: path.clone(), short_channel_id: path[0].short_channel_id,
1528 let router = TestRouter::new(scorer);
1529 let logger = TestLogger::new();
1531 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1533 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1534 let event = Event::PaymentPathFailed {
1537 network_update: None,
1538 payment_failed_permanently: false,
1539 all_paths_failed: false,
1542 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1544 invoice_payer.handle_event(event);
1548 fn scores_successful_channels() {
1549 let event_handled = core::cell::RefCell::new(false);
1550 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1552 let payment_preimage = PaymentPreimage([1; 32]);
1553 let invoice = invoice(payment_preimage);
1554 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1555 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1556 let route = TestRouter::route_for_value(final_value_msat);
1558 // Expect that scorer is given short_channel_id upon handling the event.
1559 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1560 let scorer = TestScorer::new()
1561 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1562 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1563 let router = TestRouter::new(scorer);
1564 let logger = TestLogger::new();
1566 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1568 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1569 let event = Event::PaymentPathSuccessful {
1570 payment_id, payment_hash, path: route.paths[0].clone()
1572 invoice_payer.handle_event(event);
1573 let event = Event::PaymentPathSuccessful {
1574 payment_id, payment_hash, path: route.paths[1].clone()
1576 invoice_payer.handle_event(event);
1580 fn considers_inflight_htlcs_between_invoice_payments() {
1581 let event_handled = core::cell::RefCell::new(false);
1582 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1584 let payment_preimage = PaymentPreimage([1; 32]);
1585 let payment_invoice = invoice(payment_preimage);
1586 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1588 let payer = TestPayer::new()
1589 .expect_send(Amount::ForInvoice(final_value_msat))
1590 .expect_send(Amount::ForInvoice(final_value_msat));
1591 let scorer = TestScorer::new()
1592 // 1st invoice, 1st path
1593 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1594 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1595 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1596 // 1st invoice, 2nd path
1597 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1598 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1599 // 2nd invoice, 1st path
1600 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1601 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1602 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
1603 // 2nd invoice, 2nd path
1604 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1605 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1606 let router = TestRouter::new(scorer);
1607 let logger = TestLogger::new();
1609 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1611 // Make first invoice payment.
1612 invoice_payer.pay_invoice(&payment_invoice).unwrap();
1614 // Let's pay a second invoice that will be using the same path. This should trigger the
1615 // assertions that expect `ChannelUsage` values of the first invoice payment that is still
1617 let payment_preimage_2 = PaymentPreimage([2; 32]);
1618 let payment_invoice_2 = invoice(payment_preimage_2);
1619 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1623 fn considers_inflight_htlcs_between_retries() {
1624 // First, let's just send a payment through, but only make sure one of the path completes
1625 let event_handled = core::cell::RefCell::new(false);
1626 let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1628 let payment_preimage = PaymentPreimage([1; 32]);
1629 let payment_invoice = invoice(payment_preimage);
1630 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1631 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1633 let payer = TestPayer::new()
1634 .expect_send(Amount::ForInvoice(final_value_msat))
1635 .expect_send(Amount::OnRetry(final_value_msat / 2))
1636 .expect_send(Amount::OnRetry(final_value_msat / 4));
1637 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1638 let scorer = TestScorer::new()
1639 // 1st invoice, 1st path
1640 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1641 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1642 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1643 // 1st invoice, 2nd path
1644 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1645 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1646 // Retry 1, 1st path
1647 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1648 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1649 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1650 // Retry 1, 2nd path
1651 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1652 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1653 // Retry 2, 1st path
1654 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1655 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1656 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1657 // Retry 2, 2nd path
1658 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1659 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1660 let router = TestRouter::new(scorer);
1661 let logger = TestLogger::new();
1663 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1665 // Fail 1st path, leave 2nd path inflight
1666 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1667 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
1668 invoice_payer.handle_event(Event::PaymentPathFailed {
1671 network_update: None,
1672 payment_failed_permanently: false,
1673 all_paths_failed: false,
1674 path: TestRouter::path_for_value(final_value_msat),
1675 short_channel_id: None,
1676 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1679 // Fails again the 1st path of our retry
1680 invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
1681 invoice_payer.handle_event(Event::PaymentPathFailed {
1684 network_update: None,
1685 payment_failed_permanently: false,
1686 all_paths_failed: false,
1687 path: TestRouter::path_for_value(final_value_msat / 2),
1688 short_channel_id: None,
1689 retry: Some(RouteParameters {
1690 final_value_msat: final_value_msat / 4,
1691 ..TestRouter::retry_for_invoice(&payment_invoice)
1697 scorer: RefCell<TestScorer>,
1701 fn new(scorer: TestScorer) -> Self {
1702 TestRouter { scorer: RefCell::new(scorer) }
1705 fn route_for_value(final_value_msat: u64) -> Route {
1710 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1711 channel_features: ChannelFeatures::empty(),
1712 node_features: NodeFeatures::empty(),
1713 short_channel_id: 0,
1715 cltv_expiry_delta: 0
1718 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1719 channel_features: ChannelFeatures::empty(),
1720 node_features: NodeFeatures::empty(),
1721 short_channel_id: 1,
1723 cltv_expiry_delta: 0
1726 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1727 channel_features: ChannelFeatures::empty(),
1728 node_features: NodeFeatures::empty(),
1729 short_channel_id: 2,
1730 fee_msat: final_value_msat / 2,
1731 cltv_expiry_delta: 0
1736 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1737 channel_features: ChannelFeatures::empty(),
1738 node_features: NodeFeatures::empty(),
1739 short_channel_id: 3,
1741 cltv_expiry_delta: 144
1744 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1745 channel_features: ChannelFeatures::empty(),
1746 node_features: NodeFeatures::empty(),
1747 short_channel_id: 4,
1748 fee_msat: final_value_msat / 2,
1749 cltv_expiry_delta: 144
1753 payment_params: None,
1757 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1758 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1761 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1762 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1763 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1764 .with_route_hints(invoice.route_hints());
1765 if let Some(features) = invoice.features() {
1766 payment_params = payment_params.with_features(features.clone());
1768 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1772 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1777 impl Router for TestRouter {
1779 &self, payer: &PublicKey, route_params: &RouteParameters,
1780 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1781 ) -> Result<Route, LightningError> {
1782 // Simulate calling the Scorer just as you would in find_route
1783 let route = Self::route_for_value(route_params.final_value_msat);
1784 let mut locked_scorer = self.scorer.lock();
1785 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1786 for path in route.paths {
1787 let mut aggregate_msat = 0u64;
1788 for (idx, hop) in path.iter().rev().enumerate() {
1789 aggregate_msat += hop.fee_msat;
1790 let usage = ChannelUsage {
1791 amount_msat: aggregate_msat,
1792 inflight_htlc_msat: 0,
1793 effective_capacity: EffectiveCapacity::Unknown,
1796 // Since the path is reversed, the last element in our iteration is the first
1798 if idx == path.len() - 1 {
1799 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1801 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1807 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1812 impl ScoringRouter for TestRouter {
1813 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1814 self.scorer.lock().payment_path_failed(path, short_channel_id);
1817 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1818 self.scorer.lock().payment_path_successful(path);
1821 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1822 self.scorer.lock().probe_successful(path);
1825 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1826 self.scorer.lock().probe_failed(path, short_channel_id);
1830 struct FailingRouter;
1832 impl Router for FailingRouter {
1834 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1835 _inflight_htlcs: InFlightHtlcs,
1836 ) -> Result<Route, LightningError> {
1837 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1841 impl ScoringRouter for FailingRouter {
1842 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1844 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1846 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1848 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1852 event_expectations: Option<VecDeque<TestResult>>,
1853 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1858 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1859 PaymentSuccess { path: Vec<RouteHop> },
1865 event_expectations: None,
1866 scorer_expectations: RefCell::new(None),
1870 fn expect(mut self, expectation: TestResult) -> Self {
1871 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1875 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1876 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1882 impl lightning::util::ser::Writeable for TestScorer {
1883 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1886 impl Score for TestScorer {
1887 fn channel_penalty_msat(
1888 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1890 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1891 match scorer_expectations.pop_front() {
1892 Some(expectation) => {
1893 assert_eq!(expectation.amount_msat, usage.amount_msat);
1894 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1902 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1903 if let Some(expectations) = &mut self.event_expectations {
1904 match expectations.pop_front() {
1905 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1906 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1907 assert_eq!(actual_short_channel_id, short_channel_id);
1909 Some(TestResult::PaymentSuccess { path }) => {
1910 panic!("Unexpected successful payment path: {:?}", path)
1912 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1917 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1918 if let Some(expectations) = &mut self.event_expectations {
1919 match expectations.pop_front() {
1920 Some(TestResult::PaymentFailure { path, .. }) => {
1921 panic!("Unexpected payment path failure: {:?}", path)
1923 Some(TestResult::PaymentSuccess { path }) => {
1924 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1926 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1931 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1932 if let Some(expectations) = &mut self.event_expectations {
1933 match expectations.pop_front() {
1934 Some(TestResult::PaymentFailure { path, .. }) => {
1935 panic!("Unexpected failed payment path: {:?}", path)
1937 Some(TestResult::PaymentSuccess { path }) => {
1938 panic!("Unexpected successful payment path: {:?}", path)
1940 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1944 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1945 if let Some(expectations) = &mut self.event_expectations {
1946 match expectations.pop_front() {
1947 Some(TestResult::PaymentFailure { path, .. }) => {
1948 panic!("Unexpected payment path failure: {:?}", path)
1950 Some(TestResult::PaymentSuccess { path }) => {
1951 panic!("Unexpected successful payment path: {:?}", path)
1953 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1959 impl Drop for TestScorer {
1960 fn drop(&mut self) {
1961 if std::thread::panicking() {
1965 if let Some(event_expectations) = &self.event_expectations {
1966 if !event_expectations.is_empty() {
1967 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1971 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1972 if !scorer_expectations.is_empty() {
1973 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1980 expectations: core::cell::RefCell<VecDeque<Amount>>,
1981 attempts: core::cell::RefCell<usize>,
1982 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1983 inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
1986 #[derive(Clone, Debug, PartialEq, Eq)]
1993 struct OnAttempt(usize);
1998 expectations: core::cell::RefCell::new(VecDeque::new()),
1999 attempts: core::cell::RefCell::new(0),
2000 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2001 inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
2005 fn expect_send(self, value_msat: Amount) -> Self {
2006 self.expectations.borrow_mut().push_back(value_msat);
2010 fn fails_on_attempt(self, attempt: usize) -> Self {
2011 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2012 self.fails_with(failure, OnAttempt(attempt))
2015 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2016 self.fails_with(PaymentSendFailure::PartialFailure {
2017 results: results.unwrap_or(vec![]),
2018 failed_paths_retry: Some(retry),
2019 payment_id: PaymentId([1; 32]),
2023 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2024 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2028 fn check_attempts(&self) -> Result<(), PaymentSendFailure> {
2029 let mut attempts = self.attempts.borrow_mut();
2032 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2033 Some(failure) => Err(failure),
2038 fn check_value_msats(&self, actual_value_msats: Amount) {
2039 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2040 if let Some(expected_value_msats) = expected_value_msats {
2041 assert_eq!(actual_value_msats, expected_value_msats);
2043 panic!("Unexpected amount: {:?}", actual_value_msats);
2047 fn track_inflight_htlcs(&self, route: &Route) {
2048 for path in &route.paths {
2049 self.inflight_htlcs_paths.borrow_mut().push(path.clone());
2053 fn fail_path(&self, path: &Vec<RouteHop>) {
2054 let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
2056 if let Some(idx) = path_idx {
2057 self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
2062 impl Drop for TestPayer {
2063 fn drop(&mut self) {
2064 if std::thread::panicking() {
2068 if !self.expectations.borrow().is_empty() {
2069 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2074 impl Payer for TestPayer {
2075 fn node_id(&self) -> PublicKey {
2076 let secp_ctx = Secp256k1::new();
2077 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2080 fn first_hops(&self) -> Vec<ChannelDetails> {
2085 &self, route: &Route, _payment_hash: PaymentHash,
2086 _payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
2087 ) -> Result<(), PaymentSendFailure> {
2088 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2089 self.track_inflight_htlcs(route);
2090 self.check_attempts()
2093 fn send_spontaneous_payment(
2094 &self, route: &Route, _payment_preimage: PaymentPreimage, _payment_id: PaymentId,
2095 ) -> Result<(), PaymentSendFailure> {
2096 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2097 self.check_attempts()
2101 &self, route: &Route, _payment_id: PaymentId
2102 ) -> Result<(), PaymentSendFailure> {
2103 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2104 self.track_inflight_htlcs(route);
2105 self.check_attempts()
2108 fn abandon_payment(&self, _payment_id: PaymentId) { }
2110 fn inflight_htlcs(&self) -> InFlightHtlcs {
2111 let mut inflight_htlcs = InFlightHtlcs::new();
2112 for path in self.inflight_htlcs_paths.clone().into_inner() {
2113 inflight_htlcs.process_path(&path, self.node_id());
2119 // *** Full Featured Functional Tests with a Real ChannelManager ***
2120 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2122 impl Router for ManualRouter {
2124 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2125 _inflight_htlcs: InFlightHtlcs
2126 ) -> Result<Route, LightningError> {
2127 self.0.borrow_mut().pop_front().unwrap()
2130 impl ScoringRouter for ManualRouter {
2131 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2133 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2135 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2137 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2140 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2141 self.0.borrow_mut().push_back(result);
2144 impl Drop for ManualRouter {
2145 fn drop(&mut self) {
2146 if std::thread::panicking() {
2149 assert!(self.0.borrow_mut().is_empty());
2154 fn retry_multi_path_single_failed_payment() {
2155 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2156 let chanmon_cfgs = create_chanmon_cfgs(2);
2157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2159 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2161 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2162 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2163 let chans = nodes[0].node.list_usable_channels();
2164 let mut route = Route {
2167 pubkey: nodes[1].node.get_our_node_id(),
2168 node_features: channelmanager::provided_node_features(),
2169 short_channel_id: chans[0].short_channel_id.unwrap(),
2170 channel_features: channelmanager::provided_channel_features(),
2172 cltv_expiry_delta: 100,
2175 pubkey: nodes[1].node.get_our_node_id(),
2176 node_features: channelmanager::provided_node_features(),
2177 short_channel_id: chans[1].short_channel_id.unwrap(),
2178 channel_features: channelmanager::provided_channel_features(),
2179 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2180 cltv_expiry_delta: 100,
2183 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2185 let router = ManualRouter(RefCell::new(VecDeque::new()));
2186 router.expect_find_route(Ok(route.clone()));
2187 // On retry, split the payment across both channels.
2188 route.paths[0][0].fee_msat = 50_000_001;
2189 route.paths[1][0].fee_msat = 50_000_000;
2190 router.expect_find_route(Ok(route.clone()));
2192 let event_handler = |_: Event| { panic!(); };
2193 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2195 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2196 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2197 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2199 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2200 assert_eq!(htlc_msgs.len(), 2);
2201 check_added_monitors!(nodes[0], 2);
2205 fn immediate_retry_on_failure() {
2206 // Tests that we can/will retry immediately after a failure
2207 let chanmon_cfgs = create_chanmon_cfgs(2);
2208 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2209 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2210 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2212 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2213 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2214 let chans = nodes[0].node.list_usable_channels();
2215 let mut route = Route {
2218 pubkey: nodes[1].node.get_our_node_id(),
2219 node_features: channelmanager::provided_node_features(),
2220 short_channel_id: chans[0].short_channel_id.unwrap(),
2221 channel_features: channelmanager::provided_channel_features(),
2222 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2223 cltv_expiry_delta: 100,
2226 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2228 let router = ManualRouter(RefCell::new(VecDeque::new()));
2229 router.expect_find_route(Ok(route.clone()));
2230 // On retry, split the payment across both channels.
2231 route.paths.push(route.paths[0].clone());
2232 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2233 route.paths[0][0].fee_msat = 50_000_000;
2234 route.paths[1][0].fee_msat = 50_000_001;
2235 router.expect_find_route(Ok(route.clone()));
2237 let event_handler = |_: Event| { panic!(); };
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_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2245 assert_eq!(htlc_msgs.len(), 2);
2246 check_added_monitors!(nodes[0], 2);
2250 fn no_extra_retries_on_back_to_back_fail() {
2251 // In a previous release, we had a race where we may exceed the payment retry count if we
2252 // get two failures in a row with the second having `all_paths_failed` set.
2253 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2254 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2255 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2256 // pending which we will see later. Thus, when we previously removed the retry tracking map
2257 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2258 // retry entry even though more events for the same payment were still pending. This led to
2259 // us retrying a payment again even though we'd already given up on it.
2261 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2262 // is used to remove the payment retry counter entries instead. This tests for the specific
2263 // excess-retry case while also testing `PaymentFailed` generation.
2265 let chanmon_cfgs = create_chanmon_cfgs(3);
2266 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2267 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2268 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2270 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;
2271 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;
2273 let mut route = Route {
2276 pubkey: nodes[1].node.get_our_node_id(),
2277 node_features: channelmanager::provided_node_features(),
2278 short_channel_id: chan_1_scid,
2279 channel_features: channelmanager::provided_channel_features(),
2281 cltv_expiry_delta: 100,
2283 pubkey: nodes[2].node.get_our_node_id(),
2284 node_features: channelmanager::provided_node_features(),
2285 short_channel_id: chan_2_scid,
2286 channel_features: channelmanager::provided_channel_features(),
2287 fee_msat: 100_000_000,
2288 cltv_expiry_delta: 100,
2291 pubkey: nodes[1].node.get_our_node_id(),
2292 node_features: channelmanager::provided_node_features(),
2293 short_channel_id: chan_1_scid,
2294 channel_features: channelmanager::provided_channel_features(),
2296 cltv_expiry_delta: 100,
2298 pubkey: nodes[2].node.get_our_node_id(),
2299 node_features: channelmanager::provided_node_features(),
2300 short_channel_id: chan_2_scid,
2301 channel_features: channelmanager::provided_channel_features(),
2302 fee_msat: 100_000_000,
2303 cltv_expiry_delta: 100,
2306 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2308 let router = ManualRouter(RefCell::new(VecDeque::new()));
2309 router.expect_find_route(Ok(route.clone()));
2310 // On retry, we'll only be asked for one path
2311 route.paths.remove(1);
2312 router.expect_find_route(Ok(route.clone()));
2314 let expected_events: RefCell<VecDeque<&dyn Fn(Event)>> = RefCell::new(VecDeque::new());
2315 let event_handler = |event: Event| {
2316 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2317 event_checker(event);
2319 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2321 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2322 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2323 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2325 let htlc_updates = SendEvent::from_node(&nodes[0]);
2326 check_added_monitors!(nodes[0], 1);
2327 assert_eq!(htlc_updates.msgs.len(), 1);
2329 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2330 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2331 check_added_monitors!(nodes[1], 1);
2332 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2334 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2335 check_added_monitors!(nodes[0], 1);
2336 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2338 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2339 check_added_monitors!(nodes[0], 1);
2340 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2342 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2343 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2344 check_added_monitors!(nodes[1], 1);
2345 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2347 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2348 check_added_monitors!(nodes[1], 1);
2349 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2351 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2352 check_added_monitors!(nodes[0], 1);
2354 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2355 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2356 check_added_monitors!(nodes[0], 1);
2357 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2359 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2360 check_added_monitors!(nodes[1], 1);
2361 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2363 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2364 check_added_monitors!(nodes[1], 1);
2365 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2367 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2369 check_added_monitors!(nodes[0], 1);
2371 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2372 check_added_monitors!(nodes[0], 1);
2373 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2375 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2376 check_added_monitors!(nodes[1], 1);
2377 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2378 check_added_monitors!(nodes[1], 1);
2379 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2381 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2382 check_added_monitors!(nodes[0], 1);
2384 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2385 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2386 // with it set. The first event will use up the only retry we are allowed, with the second
2387 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2388 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2389 // if the final HTLC failed.
2390 expected_events.borrow_mut().push_back(&|ev: Event| {
2391 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2392 assert!(!payment_failed_permanently);
2393 assert!(all_paths_failed);
2394 } else { panic!("Unexpected event"); }
2396 nodes[0].node.process_pending_events(&invoice_payer);
2397 assert!(expected_events.borrow().is_empty());
2399 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2400 check_added_monitors!(nodes[0], 1);
2402 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2403 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2404 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2405 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2406 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2408 expected_events.borrow_mut().push_back(&|ev: Event| {
2409 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2410 assert!(!payment_failed_permanently);
2411 assert!(all_paths_failed);
2412 } else { panic!("Unexpected event"); }
2414 expected_events.borrow_mut().push_back(&|ev: Event| {
2415 if let Event::PaymentFailed { .. } = ev {
2416 } else { panic!("Unexpected event"); }
2418 nodes[0].node.process_pending_events(&invoice_payer);
2419 assert!(expected_events.borrow().is_empty());