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`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
19 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
20 //! [`Event::PaymentPathSuccessful`] events, respectively.
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
35 //! # #[cfg(feature = "no-std")]
36 //! # extern crate core2;
38 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
39 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
40 //! # use lightning::ln::msgs::LightningError;
41 //! # use lightning::routing::gossip::NodeId;
42 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
43 //! # use lightning::routing::scoring::{ChannelUsage, Score};
44 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # use lightning::util::ser::{Writeable, Writer};
47 //! # use lightning_invoice::Invoice;
48 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, Router};
49 //! # use secp256k1::PublicKey;
50 //! # use std::cell::RefCell;
51 //! # use std::ops::Deref;
53 //! # #[cfg(not(feature = "std"))]
55 //! # #[cfg(feature = "std")]
58 //! # struct FakeEventProvider {}
59 //! # impl EventsProvider for FakeEventProvider {
60 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
63 //! # struct FakePayer {}
64 //! # impl Payer for FakePayer {
65 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
66 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
67 //! # fn send_payment(
68 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
69 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
70 //! # fn send_spontaneous_payment(
71 //! # &self, route: &Route, payment_preimage: PaymentPreimage
72 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
73 //! # fn retry_payment(
74 //! # &self, route: &Route, payment_id: PaymentId
75 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
76 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
79 //! # struct FakeRouter {}
80 //! # impl Router for FakeRouter {
81 //! # fn find_route<S: Score>(
82 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
83 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
84 //! # ) -> Result<Route, LightningError> { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
101 //! # struct FakeLogger {}
102 //! # impl Logger for FakeLogger {
103 //! # fn log(&self, record: &Record) { unimplemented!() }
107 //! let event_handler = |event: &Event| {
109 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
110 //! Event::PaymentSent { .. } => println!("payment successful"),
114 //! # let payer = FakePayer {};
115 //! # let router = FakeRouter {};
116 //! # let scorer = RefCell::new(FakeScorer {});
117 //! # let logger = FakeLogger {};
118 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
120 //! let invoice = "...";
121 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
122 //! invoice_payer.pay_invoice(&invoice).unwrap();
124 //! # let event_provider = FakeEventProvider {};
126 //! event_provider.process_pending_events(&invoice_payer);
134 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
135 //! as updates to the network graph or changes to channel scores should be applied prior to
136 //! retries, typically by way of composing [`EventHandler`]s accordingly.
140 use bitcoin_hashes::Hash;
141 use bitcoin_hashes::sha256::Hash as Sha256;
143 use crate::prelude::*;
144 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
145 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
146 use lightning::ln::msgs::LightningError;
147 use lightning::routing::gossip::NodeId;
148 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
149 use lightning::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters};
150 use lightning::util::errors::APIError;
151 use lightning::util::events::{Event, EventHandler};
152 use lightning::util::logger::Logger;
153 use time_utils::Time;
154 use crate::sync::Mutex;
156 use secp256k1::PublicKey;
159 use core::fmt::{Debug, Display, Formatter};
160 use core::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
167 /// See [module-level documentation] for details.
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, ConfiguredTime>;
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
179 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
180 pub struct InvoicePayerUsingTime<P: Deref, R: Router, S: Deref, L: Deref, E: EventHandler, T: Time>
183 S::Target: for <'a> LockableScore<'a>,
191 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
192 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
196 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
197 /// currently being made, or have outstanding paths that need retrying.
198 struct PaymentInfo<T: Time> {
199 attempts: PaymentAttempts<T>,
200 paths: Vec<Vec<RouteHop>>,
203 impl<T: Time> PaymentInfo<T> {
206 attempts: PaymentAttempts::new(),
212 /// Used to store information about all the HTLCs that are inflight across all payment attempts
213 struct AccountForInFlightHtlcs<'a, S: Score> {
215 /// Maps a channel's short channel id and its direction to the liquidity used up.
216 inflight_htlcs: HashMap<(u64, bool), u64>,
220 impl<'a, S:Score> lightning::util::ser::Writeable for AccountForInFlightHtlcs<'a, S> {
221 fn write<W: lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), std::io::Error> { self.scorer.write(writer) }
224 impl<'a, S: Score> Score for AccountForInFlightHtlcs<'a, S> {
225 fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
226 if let Some(used_liqudity) = self.inflight_htlcs.get(&(short_channel_id, source < target)) {
227 let usage = ChannelUsage {
228 inflight_htlc_msat: usage.inflight_htlc_msat + used_liqudity,
232 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
234 self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
238 fn payment_path_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
239 self.scorer.payment_path_failed(path, short_channel_id)
242 fn payment_path_successful(&mut self, path: &[&RouteHop]) {
243 self.scorer.payment_path_successful(path)
246 fn probe_failed(&mut self, path: &[&RouteHop], short_channel_id: u64) {
247 self.scorer.probe_failed(path, short_channel_id)
250 fn probe_successful(&mut self, path: &[&RouteHop]) {
251 self.scorer.probe_successful(path)
255 /// Storing minimal payment attempts information required for determining if a outbound payment can
257 #[derive(Clone, Copy)]
258 struct PaymentAttempts<T: Time> {
259 /// This count will be incremented only after the result of the attempt is known. When it's 0,
260 /// it means the result of the first attempt is now known yet.
262 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
263 first_attempted_at: T
266 impl<T: Time> PaymentAttempts<T> {
270 first_attempted_at: T::now()
275 impl<T: Time> Display for PaymentAttempts<T> {
276 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
277 #[cfg(feature = "no-std")]
278 return write!( f, "attempts: {}", self.count);
279 #[cfg(not(feature = "no-std"))]
282 "attempts: {}, duration: {}s",
284 T::now().duration_since(self.first_attempted_at).as_secs()
289 /// A trait defining behavior of an [`Invoice`] payer.
291 /// Returns the payer's node id.
292 fn node_id(&self) -> PublicKey;
294 /// Returns the payer's channels.
295 fn first_hops(&self) -> Vec<ChannelDetails>;
297 /// Sends a payment over the Lightning Network using the given [`Route`].
299 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
300 ) -> Result<PaymentId, PaymentSendFailure>;
302 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
303 fn send_spontaneous_payment(
304 &self, route: &Route, payment_preimage: PaymentPreimage
305 ) -> Result<PaymentId, PaymentSendFailure>;
307 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
308 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
310 /// Signals that no further retries for the given payment will occur.
311 fn abandon_payment(&self, payment_id: PaymentId);
314 /// A trait defining behavior for routing an [`Invoice`] payment.
316 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
317 fn find_route<S: Score>(
318 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
319 first_hops: Option<&[&ChannelDetails]>, scorer: &S
320 ) -> Result<Route, LightningError>;
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: Router, S: Deref, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, S, L, E, T>
365 S::Target: for <'a> LockableScore<'a>,
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, scorer: S, logger: L, event_handler: E, retry: Retry
381 payment_cache: Mutex::new(HashMap::new()),
386 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
388 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
389 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
391 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
392 if invoice.amount_milli_satoshis().is_none() {
393 Err(PaymentError::Invoice("amount missing"))
395 self.pay_invoice_using_amount(invoice, None)
399 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
400 /// case a retry is needed.
402 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
403 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
405 pub fn pay_zero_value_invoice(
406 &self, invoice: &Invoice, amount_msats: u64
407 ) -> Result<PaymentId, PaymentError> {
408 if invoice.amount_milli_satoshis().is_some() {
409 Err(PaymentError::Invoice("amount unexpected"))
411 self.pay_invoice_using_amount(invoice, Some(amount_msats))
415 fn pay_invoice_using_amount(
416 &self, invoice: &Invoice, amount_msats: Option<u64>
417 ) -> Result<PaymentId, PaymentError> {
418 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
420 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
421 match self.payment_cache.lock().unwrap().entry(payment_hash) {
422 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
423 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
426 let payment_secret = Some(invoice.payment_secret().clone());
427 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
428 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
429 .with_route_hints(invoice.route_hints());
430 if let Some(features) = invoice.features() {
431 payment_params = payment_params.with_features(features.clone());
433 let route_params = RouteParameters {
435 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
436 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
439 let send_payment = |route: &Route| {
440 self.payer.send_payment(route, payment_hash, &payment_secret)
443 self.pay_internal(&route_params, payment_hash, send_payment)
444 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
447 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
448 /// case a retry is needed.
450 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
451 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
453 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
454 final_cltv_expiry_delta: u32
455 ) -> Result<PaymentId, PaymentError> {
456 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
457 match self.payment_cache.lock().unwrap().entry(payment_hash) {
458 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
459 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
462 let route_params = RouteParameters {
463 payment_params: PaymentParameters::for_keysend(pubkey),
464 final_value_msat: amount_msats,
465 final_cltv_expiry_delta,
468 let send_payment = |route: &Route| {
469 self.payer.send_spontaneous_payment(route, payment_preimage)
471 self.pay_internal(&route_params, payment_hash, send_payment)
472 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
475 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
476 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
477 ) -> Result<PaymentId, PaymentError> {
478 #[cfg(feature = "std")] {
479 if has_expired(params) {
480 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
481 return Err(PaymentError::Invoice("Invoice expired prior to send"));
485 let payer = self.payer.node_id();
486 let first_hops = self.payer.first_hops();
487 let inflight_htlcs = self.create_inflight_map();
488 let route = self.router.find_route(
489 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
490 &AccountForInFlightHtlcs { scorer: &mut self.scorer.lock(), inflight_htlcs }
491 ).map_err(|e| PaymentError::Routing(e))?;
493 match send_payment(&route) {
495 for path in route.paths {
496 self.process_path_inflight_htlcs(payment_hash, path);
501 PaymentSendFailure::ParameterError(_) => Err(e),
502 PaymentSendFailure::PathParameterError(_) => Err(e),
503 PaymentSendFailure::AllFailedRetrySafe(_) => {
504 let mut payment_cache = self.payment_cache.lock().unwrap();
505 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
506 payment_info.attempts.count += 1;
507 if self.retry.is_retryable_now(&payment_info.attempts) {
508 core::mem::drop(payment_cache);
509 Ok(self.pay_internal(params, payment_hash, send_payment)?)
514 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
515 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
516 // part of our payment is retried. When we receive `MonitorUpdateFailed`, it
517 // means that we are still waiting for our channel monitor update to be completed.
518 for (result, path) in results.iter().zip(route.paths.into_iter()) {
520 Ok(_) | Err(APIError::MonitorUpdateFailed) => {
521 self.process_path_inflight_htlcs(payment_hash, path);
527 if let Some(retry_data) = failed_paths_retry {
528 // Some paths were sent, even if we failed to send the full MPP value our
529 // recipient may misbehave and claim the funds, at which point we have to
530 // consider the payment sent, so return `Ok()` here, ignoring any retry
532 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
535 // This may happen if we send a payment and some paths fail, but
536 // only due to a temporary monitor failure or the like, implying
537 // they're really in-flight, but we haven't sent the initial
538 // HTLC-Add messages yet.
543 }.map_err(|e| PaymentError::Sending(e))
546 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
547 // that are pending retry.
548 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
549 self.payment_cache.lock().unwrap().entry(payment_hash)
550 .or_insert_with(|| PaymentInfo::new())
554 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
555 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
556 self.payment_cache.lock().unwrap().entry(payment_hash)
557 .and_modify(|payment_info| {
558 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
559 payment_info.paths.swap_remove(idx);
565 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
566 ) -> Result<(), ()> {
567 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
568 .and_modify(|info| info.attempts.count += 1 )
569 .or_insert_with(|| PaymentInfo {
570 attempts: PaymentAttempts {
572 first_attempted_at: T::now(),
577 if !self.retry.is_retryable_now(&attempts) {
578 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
582 #[cfg(feature = "std")] {
583 if has_expired(params) {
584 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
589 let payer = self.payer.node_id();
590 let first_hops = self.payer.first_hops();
591 let inflight_htlcs = self.create_inflight_map();
593 let route = self.router.find_route(
594 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
595 &AccountForInFlightHtlcs { scorer: &mut self.scorer.lock(), inflight_htlcs }
599 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
603 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
605 for path in route.unwrap().paths.into_iter() {
606 self.process_path_inflight_htlcs(payment_hash, path);
610 Err(PaymentSendFailure::ParameterError(_)) |
611 Err(PaymentSendFailure::PathParameterError(_)) => {
612 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
615 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
616 self.retry_payment(payment_id, payment_hash, params)
618 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
619 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
620 // part of our payment is retried. When we receive `MonitorUpdateFailed`, it
621 // means that we are still waiting for our channel monitor update to complete.
622 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
624 Ok(_) | Err(APIError::MonitorUpdateFailed) => {
625 self.process_path_inflight_htlcs(payment_hash, path);
631 if let Some(retry) = failed_paths_retry {
632 // Always return Ok for the same reason as noted in pay_internal.
633 let _ = self.retry_payment(payment_id, payment_hash, &retry);
640 /// Removes the payment cached by the given payment hash.
642 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
643 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
644 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
645 self.payment_cache.lock().unwrap().remove(payment_hash);
648 /// Given a [`PaymentHash`], this function looks up inflight path attempts in the payment_cache.
649 /// Then, it uses the path information inside the cache to construct a HashMap mapping a channel's
650 /// short channel id and direction to the amount being sent through it.
652 /// This function should be called whenever we need information about currently used up liquidity
654 fn create_inflight_map(&self) -> HashMap<(u64, bool), u64> {
655 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
656 // Make an attempt at finding existing payment information from `payment_cache`. If it
657 // does not exist, it probably is a fresh payment and we can just return an empty
659 for payment_info in self.payment_cache.lock().unwrap().values() {
660 for path in &payment_info.paths {
661 if path.is_empty() { break };
662 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
663 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
664 // the router excludes the payer node. In the following lines, the payer's information is
665 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
666 // in our sliding window of two.
667 let our_node_id: PublicKey = self.payer.node_id();
668 let reversed_hops_with_payer = path.iter().rev().skip(1)
669 .map(|hop| hop.pubkey)
670 .chain(core::iter::once(our_node_id));
671 let mut cumulative_msat = 0;
673 // Taking the reversed vector from above, we zip it with just the reversed hops list to
674 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
675 // the total amount sent.
676 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
677 cumulative_msat += next_hop.fee_msat;
679 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
680 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
681 .or_insert(cumulative_msat);
690 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
691 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
694 #[cfg(feature = "std")]
695 fn has_expired(route_params: &RouteParameters) -> bool {
696 if let Some(expiry_time) = route_params.payment_params.expiry_time {
697 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
701 impl<P: Deref, R: Router, S: Deref, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, S, L, E, T>
704 S::Target: for <'a> LockableScore<'a>,
707 fn handle_event(&self, event: &Event) {
709 Event::PaymentPathFailed { payment_hash, path, .. }
710 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
711 | Event::ProbeSuccessful { payment_hash, path, .. }
712 | Event::ProbeFailed { payment_hash, path, .. } => {
713 self.remove_path_inflight_htlcs(*payment_hash, path);
719 Event::PaymentPathFailed {
720 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
722 if let Some(short_channel_id) = short_channel_id {
723 let path = path.iter().collect::<Vec<_>>();
724 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
727 if payment_id.is_none() {
728 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
729 } else if *rejected_by_dest {
730 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
731 self.payer.abandon_payment(payment_id.unwrap());
732 } else if retry.is_none() {
733 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
734 self.payer.abandon_payment(payment_id.unwrap());
735 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
736 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
739 self.payer.abandon_payment(payment_id.unwrap());
742 Event::PaymentFailed { payment_hash, .. } => {
743 self.remove_cached_payment(&payment_hash);
745 Event::PaymentPathSuccessful { path, .. } => {
746 let path = path.iter().collect::<Vec<_>>();
747 self.scorer.lock().payment_path_successful(&path);
749 Event::PaymentSent { payment_hash, .. } => {
750 let mut payment_cache = self.payment_cache.lock().unwrap();
751 let attempts = payment_cache
752 .remove(payment_hash)
753 .map_or(1, |payment_info| payment_info.attempts.count + 1);
754 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
756 Event::ProbeSuccessful { payment_hash, path, .. } => {
757 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
758 let path = path.iter().collect::<Vec<_>>();
759 self.scorer.lock().probe_successful(&path);
761 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
762 if let Some(short_channel_id) = short_channel_id {
763 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
764 let path = path.iter().collect::<Vec<_>>();
765 self.scorer.lock().probe_failed(&path, *short_channel_id);
771 // Delegate to the decorated event handler unless the payment is retried.
772 self.event_handler.handle_event(event)
779 use crate::{InvoiceBuilder, Currency};
780 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
781 use bitcoin_hashes::sha256::Hash as Sha256;
782 use lightning::ln::PaymentPreimage;
783 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
784 use lightning::ln::functional_test_utils::*;
785 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
786 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
787 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
788 use lightning::routing::scoring::ChannelUsage;
789 use lightning::util::test_utils::TestLogger;
790 use lightning::util::errors::APIError;
791 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
792 use secp256k1::{SecretKey, PublicKey, Secp256k1};
793 use std::cell::RefCell;
794 use std::collections::VecDeque;
795 use std::time::{SystemTime, Duration};
796 use time_utils::tests::SinceEpoch;
797 use DEFAULT_EXPIRY_TIME;
798 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateFailed};
800 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
801 let payment_hash = Sha256::hash(&payment_preimage.0);
802 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
804 InvoiceBuilder::new(Currency::Bitcoin)
805 .description("test".into())
806 .payment_hash(payment_hash)
807 .payment_secret(PaymentSecret([0; 32]))
808 .duration_since_epoch(duration_since_epoch())
809 .min_final_cltv_expiry(144)
810 .amount_milli_satoshis(128)
811 .build_signed(|hash| {
812 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
817 fn duration_since_epoch() -> Duration {
818 #[cfg(feature = "std")]
819 let duration_since_epoch =
820 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
821 #[cfg(not(feature = "std"))]
822 let duration_since_epoch = Duration::from_secs(1234567);
826 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
827 let payment_hash = Sha256::hash(&payment_preimage.0);
828 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
830 InvoiceBuilder::new(Currency::Bitcoin)
831 .description("test".into())
832 .payment_hash(payment_hash)
833 .payment_secret(PaymentSecret([0; 32]))
834 .duration_since_epoch(duration_since_epoch())
835 .min_final_cltv_expiry(144)
836 .build_signed(|hash| {
837 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
842 #[cfg(feature = "std")]
843 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
844 let payment_hash = Sha256::hash(&payment_preimage.0);
845 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
846 let duration = duration_since_epoch()
847 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
849 InvoiceBuilder::new(Currency::Bitcoin)
850 .description("test".into())
851 .payment_hash(payment_hash)
852 .payment_secret(PaymentSecret([0; 32]))
853 .duration_since_epoch(duration)
854 .min_final_cltv_expiry(144)
855 .amount_milli_satoshis(128)
856 .build_signed(|hash| {
857 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
862 fn pubkey() -> PublicKey {
863 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
867 fn pays_invoice_on_first_attempt() {
868 let event_handled = core::cell::RefCell::new(false);
869 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
871 let payment_preimage = PaymentPreimage([1; 32]);
872 let invoice = invoice(payment_preimage);
873 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
874 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
876 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
877 let router = TestRouter {};
878 let scorer = RefCell::new(TestScorer::new());
879 let logger = TestLogger::new();
881 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
883 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
884 assert_eq!(*payer.attempts.borrow(), 1);
886 invoice_payer.handle_event(&Event::PaymentSent {
887 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
889 assert_eq!(*event_handled.borrow(), true);
890 assert_eq!(*payer.attempts.borrow(), 1);
894 fn pays_invoice_on_retry() {
895 let event_handled = core::cell::RefCell::new(false);
896 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
898 let payment_preimage = PaymentPreimage([1; 32]);
899 let invoice = invoice(payment_preimage);
900 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
901 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
903 let payer = TestPayer::new()
904 .expect_send(Amount::ForInvoice(final_value_msat))
905 .expect_send(Amount::OnRetry(final_value_msat / 2));
906 let router = TestRouter {};
907 let scorer = RefCell::new(TestScorer::new());
908 let logger = TestLogger::new();
910 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
912 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
913 assert_eq!(*payer.attempts.borrow(), 1);
915 let event = Event::PaymentPathFailed {
918 network_update: None,
919 rejected_by_dest: false,
920 all_paths_failed: false,
921 path: TestRouter::path_for_value(final_value_msat),
922 short_channel_id: None,
923 retry: Some(TestRouter::retry_for_invoice(&invoice)),
925 invoice_payer.handle_event(&event);
926 assert_eq!(*event_handled.borrow(), false);
927 assert_eq!(*payer.attempts.borrow(), 2);
929 invoice_payer.handle_event(&Event::PaymentSent {
930 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
932 assert_eq!(*event_handled.borrow(), true);
933 assert_eq!(*payer.attempts.borrow(), 2);
937 fn pays_invoice_on_partial_failure() {
938 let event_handler = |_: &_| { panic!() };
940 let payment_preimage = PaymentPreimage([1; 32]);
941 let invoice = invoice(payment_preimage);
942 let retry = TestRouter::retry_for_invoice(&invoice);
943 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
945 let payer = TestPayer::new()
946 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
947 .fails_with_partial_failure(retry, OnAttempt(2), None)
948 .expect_send(Amount::ForInvoice(final_value_msat))
949 .expect_send(Amount::OnRetry(final_value_msat / 2))
950 .expect_send(Amount::OnRetry(final_value_msat / 2));
951 let router = TestRouter {};
952 let scorer = RefCell::new(TestScorer::new());
953 let logger = TestLogger::new();
955 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
957 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
961 fn retries_payment_path_for_unknown_payment() {
962 let event_handled = core::cell::RefCell::new(false);
963 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
965 let payment_preimage = PaymentPreimage([1; 32]);
966 let invoice = invoice(payment_preimage);
967 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
968 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
970 let payer = TestPayer::new()
971 .expect_send(Amount::OnRetry(final_value_msat / 2))
972 .expect_send(Amount::OnRetry(final_value_msat / 2));
973 let router = TestRouter {};
974 let scorer = RefCell::new(TestScorer::new());
975 let logger = TestLogger::new();
977 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
979 let payment_id = Some(PaymentId([1; 32]));
980 let event = Event::PaymentPathFailed {
983 network_update: None,
984 rejected_by_dest: false,
985 all_paths_failed: false,
986 path: TestRouter::path_for_value(final_value_msat),
987 short_channel_id: None,
988 retry: Some(TestRouter::retry_for_invoice(&invoice)),
990 invoice_payer.handle_event(&event);
991 assert_eq!(*event_handled.borrow(), false);
992 assert_eq!(*payer.attempts.borrow(), 1);
994 invoice_payer.handle_event(&event);
995 assert_eq!(*event_handled.borrow(), false);
996 assert_eq!(*payer.attempts.borrow(), 2);
998 invoice_payer.handle_event(&Event::PaymentSent {
999 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1001 assert_eq!(*event_handled.borrow(), true);
1002 assert_eq!(*payer.attempts.borrow(), 2);
1006 fn fails_paying_invoice_after_max_retry_counts() {
1007 let event_handled = core::cell::RefCell::new(false);
1008 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1010 let payment_preimage = PaymentPreimage([1; 32]);
1011 let invoice = invoice(payment_preimage);
1012 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1014 let payer = TestPayer::new()
1015 .expect_send(Amount::ForInvoice(final_value_msat))
1016 .expect_send(Amount::OnRetry(final_value_msat / 2))
1017 .expect_send(Amount::OnRetry(final_value_msat / 2));
1018 let router = TestRouter {};
1019 let scorer = RefCell::new(TestScorer::new());
1020 let logger = TestLogger::new();
1022 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1024 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1025 assert_eq!(*payer.attempts.borrow(), 1);
1027 let event = Event::PaymentPathFailed {
1029 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1030 network_update: None,
1031 rejected_by_dest: false,
1032 all_paths_failed: true,
1033 path: TestRouter::path_for_value(final_value_msat),
1034 short_channel_id: None,
1035 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1037 invoice_payer.handle_event(&event);
1038 assert_eq!(*event_handled.borrow(), false);
1039 assert_eq!(*payer.attempts.borrow(), 2);
1041 let event = Event::PaymentPathFailed {
1043 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1044 network_update: None,
1045 rejected_by_dest: false,
1046 all_paths_failed: false,
1047 path: TestRouter::path_for_value(final_value_msat / 2),
1048 short_channel_id: None,
1049 retry: Some(RouteParameters {
1050 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1053 invoice_payer.handle_event(&event);
1054 assert_eq!(*event_handled.borrow(), false);
1055 assert_eq!(*payer.attempts.borrow(), 3);
1057 invoice_payer.handle_event(&event);
1058 assert_eq!(*event_handled.borrow(), true);
1059 assert_eq!(*payer.attempts.borrow(), 3);
1062 #[cfg(feature = "std")]
1064 fn fails_paying_invoice_after_max_retry_timeout() {
1065 let event_handled = core::cell::RefCell::new(false);
1066 let event_handler = |_: &_| { *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));
1076 let router = TestRouter {};
1077 let scorer = RefCell::new(TestScorer::new());
1078 let logger = TestLogger::new();
1079 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
1082 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1084 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1085 assert_eq!(*payer.attempts.borrow(), 1);
1087 let event = Event::PaymentPathFailed {
1089 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1090 network_update: None,
1091 rejected_by_dest: false,
1092 all_paths_failed: true,
1093 path: TestRouter::path_for_value(final_value_msat),
1094 short_channel_id: None,
1095 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1097 invoice_payer.handle_event(&event);
1098 assert_eq!(*event_handled.borrow(), false);
1099 assert_eq!(*payer.attempts.borrow(), 2);
1101 SinceEpoch::advance(Duration::from_secs(121));
1103 invoice_payer.handle_event(&event);
1104 assert_eq!(*event_handled.borrow(), true);
1105 assert_eq!(*payer.attempts.borrow(), 2);
1109 fn fails_paying_invoice_with_missing_retry_params() {
1110 let event_handled = core::cell::RefCell::new(false);
1111 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1113 let payment_preimage = PaymentPreimage([1; 32]);
1114 let invoice = invoice(payment_preimage);
1115 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1117 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1118 let router = TestRouter {};
1119 let scorer = RefCell::new(TestScorer::new());
1120 let logger = TestLogger::new();
1122 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1124 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1125 assert_eq!(*payer.attempts.borrow(), 1);
1127 let event = Event::PaymentPathFailed {
1129 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1130 network_update: None,
1131 rejected_by_dest: false,
1132 all_paths_failed: false,
1134 short_channel_id: None,
1137 invoice_payer.handle_event(&event);
1138 assert_eq!(*event_handled.borrow(), true);
1139 assert_eq!(*payer.attempts.borrow(), 1);
1142 // Expiration is checked only in an std environment
1143 #[cfg(feature = "std")]
1145 fn fails_paying_invoice_after_expiration() {
1146 let event_handled = core::cell::RefCell::new(false);
1147 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1149 let payer = TestPayer::new();
1150 let router = TestRouter {};
1151 let scorer = RefCell::new(TestScorer::new());
1152 let logger = TestLogger::new();
1154 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1156 let payment_preimage = PaymentPreimage([1; 32]);
1157 let invoice = expired_invoice(payment_preimage);
1158 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1159 assert_eq!(msg, "Invoice expired prior to send");
1160 } else { panic!("Expected Invoice Error"); }
1163 // Expiration is checked only in an std environment
1164 #[cfg(feature = "std")]
1166 fn fails_retrying_invoice_after_expiration() {
1167 let event_handled = core::cell::RefCell::new(false);
1168 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1170 let payment_preimage = PaymentPreimage([1; 32]);
1171 let invoice = invoice(payment_preimage);
1172 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1174 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1175 let router = TestRouter {};
1176 let scorer = RefCell::new(TestScorer::new());
1177 let logger = TestLogger::new();
1179 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1181 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1182 assert_eq!(*payer.attempts.borrow(), 1);
1184 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1185 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1186 .checked_sub(Duration::from_secs(2)).unwrap()
1187 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1188 let event = Event::PaymentPathFailed {
1190 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1191 network_update: None,
1192 rejected_by_dest: false,
1193 all_paths_failed: false,
1195 short_channel_id: None,
1196 retry: Some(retry_data),
1198 invoice_payer.handle_event(&event);
1199 assert_eq!(*event_handled.borrow(), true);
1200 assert_eq!(*payer.attempts.borrow(), 1);
1204 fn fails_paying_invoice_after_retry_error() {
1205 let event_handled = core::cell::RefCell::new(false);
1206 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1208 let payment_preimage = PaymentPreimage([1; 32]);
1209 let invoice = invoice(payment_preimage);
1210 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1212 let payer = TestPayer::new()
1213 .fails_on_attempt(2)
1214 .expect_send(Amount::ForInvoice(final_value_msat))
1215 .expect_send(Amount::OnRetry(final_value_msat / 2));
1216 let router = TestRouter {};
1217 let scorer = RefCell::new(TestScorer::new());
1218 let logger = TestLogger::new();
1220 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1222 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1223 assert_eq!(*payer.attempts.borrow(), 1);
1225 let event = Event::PaymentPathFailed {
1227 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1228 network_update: None,
1229 rejected_by_dest: false,
1230 all_paths_failed: false,
1231 path: TestRouter::path_for_value(final_value_msat / 2),
1232 short_channel_id: None,
1233 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1235 invoice_payer.handle_event(&event);
1236 assert_eq!(*event_handled.borrow(), true);
1237 assert_eq!(*payer.attempts.borrow(), 2);
1241 fn fails_paying_invoice_after_rejected_by_payee() {
1242 let event_handled = core::cell::RefCell::new(false);
1243 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1245 let payment_preimage = PaymentPreimage([1; 32]);
1246 let invoice = invoice(payment_preimage);
1247 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1249 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1250 let router = TestRouter {};
1251 let scorer = RefCell::new(TestScorer::new());
1252 let logger = TestLogger::new();
1254 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1256 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1257 assert_eq!(*payer.attempts.borrow(), 1);
1259 let event = Event::PaymentPathFailed {
1261 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1262 network_update: None,
1263 rejected_by_dest: true,
1264 all_paths_failed: false,
1266 short_channel_id: None,
1267 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1269 invoice_payer.handle_event(&event);
1270 assert_eq!(*event_handled.borrow(), true);
1271 assert_eq!(*payer.attempts.borrow(), 1);
1275 fn fails_repaying_invoice_with_pending_payment() {
1276 let event_handled = core::cell::RefCell::new(false);
1277 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1279 let payment_preimage = PaymentPreimage([1; 32]);
1280 let invoice = invoice(payment_preimage);
1281 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1283 let payer = TestPayer::new()
1284 .expect_send(Amount::ForInvoice(final_value_msat))
1285 .expect_send(Amount::ForInvoice(final_value_msat));
1286 let router = TestRouter {};
1287 let scorer = RefCell::new(TestScorer::new());
1288 let logger = TestLogger::new();
1290 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1292 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1294 // Cannot repay an invoice pending payment.
1295 match invoice_payer.pay_invoice(&invoice) {
1296 Err(PaymentError::Invoice("payment pending")) => {},
1297 Err(_) => panic!("unexpected error"),
1298 Ok(_) => panic!("expected invoice error"),
1301 // Can repay an invoice once cleared from cache.
1302 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1303 invoice_payer.remove_cached_payment(&payment_hash);
1304 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1306 // Cannot retry paying an invoice if cleared from cache.
1307 invoice_payer.remove_cached_payment(&payment_hash);
1308 let event = Event::PaymentPathFailed {
1311 network_update: None,
1312 rejected_by_dest: false,
1313 all_paths_failed: false,
1315 short_channel_id: None,
1316 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1318 invoice_payer.handle_event(&event);
1319 assert_eq!(*event_handled.borrow(), true);
1323 fn fails_paying_invoice_with_routing_errors() {
1324 let payer = TestPayer::new();
1325 let router = FailingRouter {};
1326 let scorer = RefCell::new(TestScorer::new());
1327 let logger = TestLogger::new();
1329 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1331 let payment_preimage = PaymentPreimage([1; 32]);
1332 let invoice = invoice(payment_preimage);
1333 match invoice_payer.pay_invoice(&invoice) {
1334 Err(PaymentError::Routing(_)) => {},
1335 Err(_) => panic!("unexpected error"),
1336 Ok(_) => panic!("expected routing error"),
1341 fn fails_paying_invoice_with_sending_errors() {
1342 let payment_preimage = PaymentPreimage([1; 32]);
1343 let invoice = invoice(payment_preimage);
1344 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1346 let payer = TestPayer::new()
1347 .fails_on_attempt(1)
1348 .expect_send(Amount::ForInvoice(final_value_msat));
1349 let router = TestRouter {};
1350 let scorer = RefCell::new(TestScorer::new());
1351 let logger = TestLogger::new();
1353 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1355 match invoice_payer.pay_invoice(&invoice) {
1356 Err(PaymentError::Sending(_)) => {},
1357 Err(_) => panic!("unexpected error"),
1358 Ok(_) => panic!("expected sending error"),
1363 fn pays_zero_value_invoice_using_amount() {
1364 let event_handled = core::cell::RefCell::new(false);
1365 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1367 let payment_preimage = PaymentPreimage([1; 32]);
1368 let invoice = zero_value_invoice(payment_preimage);
1369 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1370 let final_value_msat = 100;
1372 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1373 let router = TestRouter {};
1374 let scorer = RefCell::new(TestScorer::new());
1375 let logger = TestLogger::new();
1377 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1380 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1381 assert_eq!(*payer.attempts.borrow(), 1);
1383 invoice_payer.handle_event(&Event::PaymentSent {
1384 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1386 assert_eq!(*event_handled.borrow(), true);
1387 assert_eq!(*payer.attempts.borrow(), 1);
1391 fn fails_paying_zero_value_invoice_with_amount() {
1392 let event_handled = core::cell::RefCell::new(false);
1393 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1395 let payer = TestPayer::new();
1396 let router = TestRouter {};
1397 let scorer = RefCell::new(TestScorer::new());
1398 let logger = TestLogger::new();
1400 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1402 let payment_preimage = PaymentPreimage([1; 32]);
1403 let invoice = invoice(payment_preimage);
1405 // Cannot repay an invoice pending payment.
1406 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1407 Err(PaymentError::Invoice("amount unexpected")) => {},
1408 Err(_) => panic!("unexpected error"),
1409 Ok(_) => panic!("expected invoice error"),
1414 fn pays_pubkey_with_amount() {
1415 let event_handled = core::cell::RefCell::new(false);
1416 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1418 let pubkey = pubkey();
1419 let payment_preimage = PaymentPreimage([1; 32]);
1420 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1421 let final_value_msat = 100;
1422 let final_cltv_expiry_delta = 42;
1424 let payer = TestPayer::new()
1425 .expect_send(Amount::Spontaneous(final_value_msat))
1426 .expect_send(Amount::OnRetry(final_value_msat));
1427 let router = TestRouter {};
1428 let scorer = RefCell::new(TestScorer::new());
1429 let logger = TestLogger::new();
1431 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1433 let payment_id = Some(invoice_payer.pay_pubkey(
1434 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1436 assert_eq!(*payer.attempts.borrow(), 1);
1438 let retry = RouteParameters {
1439 payment_params: PaymentParameters::for_keysend(pubkey),
1441 final_cltv_expiry_delta,
1443 let event = Event::PaymentPathFailed {
1446 network_update: None,
1447 rejected_by_dest: false,
1448 all_paths_failed: false,
1450 short_channel_id: None,
1453 invoice_payer.handle_event(&event);
1454 assert_eq!(*event_handled.borrow(), false);
1455 assert_eq!(*payer.attempts.borrow(), 2);
1457 invoice_payer.handle_event(&Event::PaymentSent {
1458 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1460 assert_eq!(*event_handled.borrow(), true);
1461 assert_eq!(*payer.attempts.borrow(), 2);
1465 fn scores_failed_channel() {
1466 let event_handled = core::cell::RefCell::new(false);
1467 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1469 let payment_preimage = PaymentPreimage([1; 32]);
1470 let invoice = invoice(payment_preimage);
1471 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1472 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1473 let path = TestRouter::path_for_value(final_value_msat);
1474 let short_channel_id = Some(path[0].short_channel_id);
1476 // Expect that scorer is given short_channel_id upon handling the event.
1477 let payer = TestPayer::new()
1478 .expect_send(Amount::ForInvoice(final_value_msat))
1479 .expect_send(Amount::OnRetry(final_value_msat / 2));
1480 let router = TestRouter {};
1481 let scorer = RefCell::new(TestScorer::new().expect(TestResult::PaymentFailure {
1482 path: path.clone(), short_channel_id: path[0].short_channel_id,
1484 let logger = TestLogger::new();
1486 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1488 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1489 let event = Event::PaymentPathFailed {
1492 network_update: None,
1493 rejected_by_dest: false,
1494 all_paths_failed: false,
1497 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1499 invoice_payer.handle_event(&event);
1503 fn scores_successful_channels() {
1504 let event_handled = core::cell::RefCell::new(false);
1505 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1507 let payment_preimage = PaymentPreimage([1; 32]);
1508 let invoice = invoice(payment_preimage);
1509 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1510 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1511 let route = TestRouter::route_for_value(final_value_msat);
1513 // Expect that scorer is given short_channel_id upon handling the event.
1514 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1515 let router = TestRouter {};
1516 let scorer = RefCell::new(TestScorer::new()
1517 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1518 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() })
1520 let logger = TestLogger::new();
1522 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1524 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1525 let event = Event::PaymentPathSuccessful {
1526 payment_id, payment_hash, path: route.paths[0].clone()
1528 invoice_payer.handle_event(&event);
1529 let event = Event::PaymentPathSuccessful {
1530 payment_id, payment_hash, path: route.paths[1].clone()
1532 invoice_payer.handle_event(&event);
1536 fn generates_correct_inflight_map_data() {
1537 let event_handled = core::cell::RefCell::new(false);
1538 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1540 let payment_preimage = PaymentPreimage([1; 32]);
1541 let invoice = invoice(payment_preimage);
1542 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1543 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1545 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1546 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1547 let route = TestRouter::route_for_value(final_value_msat);
1548 let router = TestRouter {};
1549 let scorer = RefCell::new(TestScorer::new());
1550 let logger = TestLogger::new();
1552 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1554 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1556 let inflight_map = invoice_payer.create_inflight_map();
1558 assert_eq!(inflight_map.get(&(0, false)).unwrap().clone(), 94);
1559 assert_eq!(inflight_map.get(&(1, true)).unwrap().clone(), 84);
1560 assert_eq!(inflight_map.get(&(2, false)).unwrap().clone(), 64);
1562 // Second path check
1563 assert_eq!(inflight_map.get(&(1, false)).unwrap().clone(), 64);
1565 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1566 payment_id, payment_hash, path: route.paths[0].clone()
1569 let inflight_map = invoice_payer.create_inflight_map();
1571 assert_eq!(inflight_map.get(&(0, false)), None);
1572 assert_eq!(inflight_map.get(&(1, true)), None);
1573 assert_eq!(inflight_map.get(&(2, false)), None);
1575 // Second path should still be inflight
1576 assert_eq!(inflight_map.get(&(1, false)).unwrap().clone(), 64)
1580 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1581 // First, let's just send a payment through, but only make sure one of the path completes
1582 let event_handled = core::cell::RefCell::new(false);
1583 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1585 let payment_preimage = PaymentPreimage([1; 32]);
1586 let payment_invoice = invoice(payment_preimage);
1587 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1588 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1590 let payer = TestPayer::new()
1591 .expect_send(Amount::ForInvoice(final_value_msat))
1592 .expect_send(Amount::ForInvoice(final_value_msat));
1593 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1594 let route = TestRouter::route_for_value(final_value_msat);
1595 let router = TestRouter {};
1596 let scorer = RefCell::new(TestScorer::new()
1597 // 1st invoice, 1st path
1598 .expect_usage(ChannelUsage { amount_msat: 10, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1599 .expect_usage(ChannelUsage { amount_msat: 20, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1600 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1601 // 1st invoice, 2nd path
1602 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1603 // 2nd invoice, 1st path
1604 .expect_usage(ChannelUsage { amount_msat: 10, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1605 .expect_usage(ChannelUsage { amount_msat: 20, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1606 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1607 // 2nd invoice, 2nd path
1608 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1610 let logger = TestLogger::new();
1612 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1614 // Succeed 1st path, leave 2nd path inflight
1615 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1616 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1617 payment_id, payment_hash, path: route.paths[0].clone()
1620 // Let's pay a second invoice that will be using the same path. This should trigger the
1621 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1622 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1623 // have 64 msats inflight for paths considering the channel with scid of 1.
1624 let payment_preimage_2 = PaymentPreimage([2; 32]);
1625 let payment_invoice_2 = invoice(payment_preimage_2);
1626 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1630 fn considers_inflight_htlcs_between_retries() {
1631 // First, let's just send a payment through, but only make sure one of the path completes
1632 let event_handled = core::cell::RefCell::new(false);
1633 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1635 let payment_preimage = PaymentPreimage([1; 32]);
1636 let payment_invoice = invoice(payment_preimage);
1637 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1638 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1640 let payer = TestPayer::new()
1641 .expect_send(Amount::ForInvoice(final_value_msat))
1642 .expect_send(Amount::OnRetry(final_value_msat / 2))
1643 .expect_send(Amount::OnRetry(final_value_msat / 2));
1644 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1645 let router = TestRouter {};
1646 let scorer = RefCell::new(TestScorer::new()
1647 // 1st invoice, 1st path
1648 .expect_usage(ChannelUsage { amount_msat: 10, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1649 .expect_usage(ChannelUsage { amount_msat: 20, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1650 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1651 // 1st invoice, 2nd path
1652 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1654 .expect_usage(ChannelUsage { amount_msat: 10, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1655 .expect_usage(ChannelUsage { amount_msat: 20, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1656 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1657 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1659 .expect_usage(ChannelUsage { amount_msat: 10, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1660 .expect_usage(ChannelUsage { amount_msat: 20, inflight_htlc_msat: 96, effective_capacity: EffectiveCapacity::Unknown } )
1661 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1662 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 96, effective_capacity: EffectiveCapacity::Unknown } )
1664 let logger = TestLogger::new();
1666 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1668 // Fail 1st path, leave 2nd path inflight
1669 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1670 invoice_payer.handle_event(&Event::PaymentPathFailed {
1673 network_update: None,
1674 rejected_by_dest: false,
1675 all_paths_failed: false,
1676 path: TestRouter::path_for_value(final_value_msat),
1677 short_channel_id: None,
1678 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1681 // Fails again the 1st path of our retry
1682 invoice_payer.handle_event(&Event::PaymentPathFailed {
1685 network_update: None,
1686 rejected_by_dest: false,
1687 all_paths_failed: false,
1688 path: TestRouter::path_for_value(final_value_msat / 2),
1689 short_channel_id: None,
1690 retry: Some(RouteParameters {
1691 final_value_msat: final_value_msat / 2,
1692 ..TestRouter::retry_for_invoice(&payment_invoice)
1698 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1699 let event_handled = core::cell::RefCell::new(false);
1700 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1702 let payment_preimage = PaymentPreimage([1; 32]);
1703 let invoice_to_pay = invoice(payment_preimage);
1704 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1706 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1707 let payer = TestPayer::new()
1708 .fails_with_partial_failure(
1709 retry.clone(), OnAttempt(1),
1711 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateFailed)
1713 .expect_send(Amount::ForInvoice(final_value_msat));
1715 let router = TestRouter {};
1716 let scorer = RefCell::new(TestScorer::new());
1717 let logger = TestLogger::new();
1719 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1721 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1722 let inflight_map = invoice_payer.create_inflight_map();
1724 // Only the second path, which failed with `MonitorUpdateFailed` should be added to our
1725 // inflight map because retries are disabled.
1726 assert_eq!(inflight_map.len(), 1);
1730 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1731 let event_handled = core::cell::RefCell::new(false);
1732 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1734 let payment_preimage = PaymentPreimage([1; 32]);
1735 let invoice_to_pay = invoice(payment_preimage);
1736 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1738 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1739 let payer = TestPayer::new()
1740 .fails_with_partial_failure(
1741 retry.clone(), OnAttempt(1),
1743 Ok(()), Err(MonitorUpdateFailed)
1745 .expect_send(Amount::ForInvoice(final_value_msat));
1747 let router = TestRouter {};
1748 let scorer = RefCell::new(TestScorer::new());
1749 let logger = TestLogger::new();
1751 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1753 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1754 let inflight_map = invoice_payer.create_inflight_map();
1756 // All paths successful, hence we check of the existence of all 4 hops.
1757 assert_eq!(inflight_map.len(), 4);
1763 fn route_for_value(final_value_msat: u64) -> Route {
1768 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1769 channel_features: ChannelFeatures::empty(),
1770 node_features: NodeFeatures::empty(),
1771 short_channel_id: 0,
1773 cltv_expiry_delta: 0
1776 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1777 channel_features: ChannelFeatures::empty(),
1778 node_features: NodeFeatures::empty(),
1779 short_channel_id: 1,
1781 cltv_expiry_delta: 0
1784 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1785 channel_features: ChannelFeatures::empty(),
1786 node_features: NodeFeatures::empty(),
1787 short_channel_id: 2,
1788 fee_msat: final_value_msat / 2,
1789 cltv_expiry_delta: 0
1793 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1794 channel_features: ChannelFeatures::empty(),
1795 node_features: NodeFeatures::empty(),
1796 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1799 payment_params: None,
1803 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1804 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1807 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1808 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1809 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1810 .with_route_hints(invoice.route_hints());
1811 if let Some(features) = invoice.features() {
1812 payment_params = payment_params.with_features(features.clone());
1814 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1818 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1823 impl Router for TestRouter {
1824 fn find_route<S: Score>(
1825 &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1826 _first_hops: Option<&[&ChannelDetails]>, scorer: &S
1827 ) -> Result<Route, LightningError> {
1828 // Simulate calling the Scorer just as you would in find_route
1829 let route = Self::route_for_value(route_params.final_value_msat);
1830 for path in route.paths {
1832 let usage = ChannelUsage {
1833 amount_msat: hop.fee_msat,
1834 inflight_htlc_msat: 0,
1835 effective_capacity: EffectiveCapacity::Unknown,
1837 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1842 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1847 struct FailingRouter;
1849 impl Router for FailingRouter {
1850 fn find_route<S: Score>(
1851 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1852 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1853 ) -> Result<Route, LightningError> {
1854 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1859 event_expectations: Option<VecDeque<TestResult>>,
1860 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1865 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1866 PaymentSuccess { path: Vec<RouteHop> },
1872 event_expectations: None,
1873 scorer_expectations: RefCell::new(None),
1877 fn expect(mut self, expectation: TestResult) -> Self {
1878 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1882 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1883 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1889 impl lightning::util::ser::Writeable for TestScorer {
1890 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1893 impl Score for TestScorer {
1894 fn channel_penalty_msat(
1895 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1897 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1898 match scorer_expectations.pop_front() {
1899 Some(expectation) => {
1900 assert_eq!(expectation.amount_msat, usage.amount_msat);
1901 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1909 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1910 if let Some(expectations) = &mut self.event_expectations {
1911 match expectations.pop_front() {
1912 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1913 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1914 assert_eq!(actual_short_channel_id, short_channel_id);
1916 Some(TestResult::PaymentSuccess { path }) => {
1917 panic!("Unexpected successful payment path: {:?}", path)
1919 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1924 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1925 if let Some(expectations) = &mut self.event_expectations {
1926 match expectations.pop_front() {
1927 Some(TestResult::PaymentFailure { path, .. }) => {
1928 panic!("Unexpected payment path failure: {:?}", path)
1930 Some(TestResult::PaymentSuccess { path }) => {
1931 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1933 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1938 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1939 if let Some(expectations) = &mut self.event_expectations {
1940 match expectations.pop_front() {
1941 Some(TestResult::PaymentFailure { path, .. }) => {
1942 panic!("Unexpected failed payment path: {:?}", path)
1944 Some(TestResult::PaymentSuccess { path }) => {
1945 panic!("Unexpected successful payment path: {:?}", path)
1947 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1951 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1952 if let Some(expectations) = &mut self.event_expectations {
1953 match expectations.pop_front() {
1954 Some(TestResult::PaymentFailure { path, .. }) => {
1955 panic!("Unexpected payment path failure: {:?}", path)
1957 Some(TestResult::PaymentSuccess { path }) => {
1958 panic!("Unexpected successful payment path: {:?}", path)
1960 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1966 impl Drop for TestScorer {
1967 fn drop(&mut self) {
1968 if std::thread::panicking() {
1972 if let Some(event_expectations) = &self.event_expectations {
1973 if !event_expectations.is_empty() {
1974 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1978 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1979 if !scorer_expectations.is_empty() {
1980 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1987 expectations: core::cell::RefCell<VecDeque<Amount>>,
1988 attempts: core::cell::RefCell<usize>,
1989 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1992 #[derive(Clone, Debug, PartialEq, Eq)]
1999 struct OnAttempt(usize);
2004 expectations: core::cell::RefCell::new(VecDeque::new()),
2005 attempts: core::cell::RefCell::new(0),
2006 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2010 fn expect_send(self, value_msat: Amount) -> Self {
2011 self.expectations.borrow_mut().push_back(value_msat);
2015 fn fails_on_attempt(self, attempt: usize) -> Self {
2016 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
2017 self.fails_with(failure, OnAttempt(attempt))
2020 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2021 self.fails_with(PaymentSendFailure::PartialFailure {
2022 results: results.unwrap_or(vec![]),
2023 failed_paths_retry: Some(retry),
2024 payment_id: PaymentId([1; 32]),
2028 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2029 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2033 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2034 let mut attempts = self.attempts.borrow_mut();
2037 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2038 Some(failure) => Err(failure),
2039 None => Ok(PaymentId([1; 32])),
2043 fn check_value_msats(&self, actual_value_msats: Amount) {
2044 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2045 if let Some(expected_value_msats) = expected_value_msats {
2046 assert_eq!(actual_value_msats, expected_value_msats);
2048 panic!("Unexpected amount: {:?}", actual_value_msats);
2053 impl Drop for TestPayer {
2054 fn drop(&mut self) {
2055 if std::thread::panicking() {
2059 if !self.expectations.borrow().is_empty() {
2060 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2065 impl Payer for TestPayer {
2066 fn node_id(&self) -> PublicKey {
2067 let secp_ctx = Secp256k1::new();
2068 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2071 fn first_hops(&self) -> Vec<ChannelDetails> {
2076 &self, route: &Route, _payment_hash: PaymentHash,
2077 _payment_secret: &Option<PaymentSecret>
2078 ) -> Result<PaymentId, PaymentSendFailure> {
2079 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2080 self.check_attempts()
2083 fn send_spontaneous_payment(
2084 &self, route: &Route, _payment_preimage: PaymentPreimage,
2085 ) -> Result<PaymentId, PaymentSendFailure> {
2086 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2087 self.check_attempts()
2091 &self, route: &Route, _payment_id: PaymentId
2092 ) -> Result<(), PaymentSendFailure> {
2093 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2094 self.check_attempts().map(|_| ())
2097 fn abandon_payment(&self, _payment_id: PaymentId) { }
2100 // *** Full Featured Functional Tests with a Real ChannelManager ***
2101 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2103 impl Router for ManualRouter {
2104 fn find_route<S: Score>(
2105 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
2106 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
2107 ) -> Result<Route, LightningError> {
2108 self.0.borrow_mut().pop_front().unwrap()
2112 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2113 self.0.borrow_mut().push_back(result);
2116 impl Drop for ManualRouter {
2117 fn drop(&mut self) {
2118 if std::thread::panicking() {
2121 assert!(self.0.borrow_mut().is_empty());
2126 fn retry_multi_path_single_failed_payment() {
2127 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2128 let chanmon_cfgs = create_chanmon_cfgs(2);
2129 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2133 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2134 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2135 let chans = nodes[0].node.list_usable_channels();
2136 let mut route = Route {
2139 pubkey: nodes[1].node.get_our_node_id(),
2140 node_features: NodeFeatures::known(),
2141 short_channel_id: chans[0].short_channel_id.unwrap(),
2142 channel_features: ChannelFeatures::known(),
2144 cltv_expiry_delta: 100,
2147 pubkey: nodes[1].node.get_our_node_id(),
2148 node_features: NodeFeatures::known(),
2149 short_channel_id: chans[1].short_channel_id.unwrap(),
2150 channel_features: ChannelFeatures::known(),
2151 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2152 cltv_expiry_delta: 100,
2155 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2157 let router = ManualRouter(RefCell::new(VecDeque::new()));
2158 router.expect_find_route(Ok(route.clone()));
2159 // On retry, split the payment across both channels.
2160 route.paths[0][0].fee_msat = 50_000_001;
2161 route.paths[1][0].fee_msat = 50_000_000;
2162 router.expect_find_route(Ok(route.clone()));
2164 let event_handler = |_: &_| { panic!(); };
2165 let scorer = RefCell::new(TestScorer::new());
2166 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2168 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2169 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2170 duration_since_epoch(), 3600).unwrap())
2172 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2173 assert_eq!(htlc_msgs.len(), 2);
2174 check_added_monitors!(nodes[0], 2);
2178 fn immediate_retry_on_failure() {
2179 // Tests that we can/will retry immediately after a failure
2180 let chanmon_cfgs = create_chanmon_cfgs(2);
2181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2183 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2185 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2186 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
2187 let chans = nodes[0].node.list_usable_channels();
2188 let mut route = Route {
2191 pubkey: nodes[1].node.get_our_node_id(),
2192 node_features: NodeFeatures::known(),
2193 short_channel_id: chans[0].short_channel_id.unwrap(),
2194 channel_features: ChannelFeatures::known(),
2195 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2196 cltv_expiry_delta: 100,
2199 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2201 let router = ManualRouter(RefCell::new(VecDeque::new()));
2202 router.expect_find_route(Ok(route.clone()));
2203 // On retry, split the payment across both channels.
2204 route.paths.push(route.paths[0].clone());
2205 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2206 route.paths[0][0].fee_msat = 50_000_000;
2207 route.paths[1][0].fee_msat = 50_000_001;
2208 router.expect_find_route(Ok(route.clone()));
2210 let event_handler = |_: &_| { panic!(); };
2211 let scorer = RefCell::new(TestScorer::new());
2212 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2214 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2215 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2216 duration_since_epoch(), 3600).unwrap())
2218 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2219 assert_eq!(htlc_msgs.len(), 2);
2220 check_added_monitors!(nodes[0], 2);
2224 fn no_extra_retries_on_back_to_back_fail() {
2225 // In a previous release, we had a race where we may exceed the payment retry count if we
2226 // get two failures in a row with the second having `all_paths_failed` set.
2227 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2228 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2229 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2230 // pending which we will see later. Thus, when we previously removed the retry tracking map
2231 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2232 // retry entry even though more events for the same payment were still pending. This led to
2233 // us retrying a payment again even though we'd already given up on it.
2235 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2236 // is used to remove the payment retry counter entries instead. This tests for the specific
2237 // excess-retry case while also testing `PaymentFailed` generation.
2239 let chanmon_cfgs = create_chanmon_cfgs(3);
2240 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2241 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2242 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2244 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
2245 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
2247 let mut route = Route {
2250 pubkey: nodes[1].node.get_our_node_id(),
2251 node_features: NodeFeatures::known(),
2252 short_channel_id: chan_1_scid,
2253 channel_features: ChannelFeatures::known(),
2255 cltv_expiry_delta: 100,
2257 pubkey: nodes[2].node.get_our_node_id(),
2258 node_features: NodeFeatures::known(),
2259 short_channel_id: chan_2_scid,
2260 channel_features: ChannelFeatures::known(),
2261 fee_msat: 100_000_000,
2262 cltv_expiry_delta: 100,
2265 pubkey: nodes[1].node.get_our_node_id(),
2266 node_features: NodeFeatures::known(),
2267 short_channel_id: chan_1_scid,
2268 channel_features: ChannelFeatures::known(),
2270 cltv_expiry_delta: 100,
2272 pubkey: nodes[2].node.get_our_node_id(),
2273 node_features: NodeFeatures::known(),
2274 short_channel_id: chan_2_scid,
2275 channel_features: ChannelFeatures::known(),
2276 fee_msat: 100_000_000,
2277 cltv_expiry_delta: 100,
2280 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2282 let router = ManualRouter(RefCell::new(VecDeque::new()));
2283 router.expect_find_route(Ok(route.clone()));
2284 // On retry, we'll only be asked for one path
2285 route.paths.remove(1);
2286 router.expect_find_route(Ok(route.clone()));
2288 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2289 let event_handler = |event: &Event| {
2290 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2291 event_checker(event);
2293 let scorer = RefCell::new(TestScorer::new());
2294 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2296 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2297 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2298 duration_since_epoch(), 3600).unwrap())
2300 let htlc_updates = SendEvent::from_node(&nodes[0]);
2301 check_added_monitors!(nodes[0], 1);
2302 assert_eq!(htlc_updates.msgs.len(), 1);
2304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2305 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2306 check_added_monitors!(nodes[1], 1);
2307 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2309 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2310 check_added_monitors!(nodes[0], 1);
2311 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2313 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2314 check_added_monitors!(nodes[0], 1);
2315 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2317 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2318 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2319 check_added_monitors!(nodes[1], 1);
2320 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2322 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2323 check_added_monitors!(nodes[1], 1);
2324 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2326 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2327 check_added_monitors!(nodes[0], 1);
2329 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2330 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2331 check_added_monitors!(nodes[0], 1);
2332 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2334 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2335 check_added_monitors!(nodes[1], 1);
2336 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2338 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2339 check_added_monitors!(nodes[1], 1);
2340 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2342 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2343 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2344 check_added_monitors!(nodes[0], 1);
2346 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2347 check_added_monitors!(nodes[0], 1);
2348 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2350 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2351 check_added_monitors!(nodes[1], 1);
2352 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2353 check_added_monitors!(nodes[1], 1);
2354 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2356 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2357 check_added_monitors!(nodes[0], 1);
2359 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2360 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2361 // with it set. The first event will use up the only retry we are allowed, with the second
2362 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2363 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2364 // if the final HTLC failed.
2365 expected_events.borrow_mut().push_back(&|ev: &Event| {
2366 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
2367 assert!(!rejected_by_dest);
2368 assert!(all_paths_failed);
2369 } else { panic!("Unexpected event"); }
2371 nodes[0].node.process_pending_events(&invoice_payer);
2372 assert!(expected_events.borrow().is_empty());
2374 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2375 check_added_monitors!(nodes[0], 1);
2377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2378 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2379 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2380 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2381 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2383 expected_events.borrow_mut().push_back(&|ev: &Event| {
2384 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
2385 assert!(!rejected_by_dest);
2386 assert!(all_paths_failed);
2387 } else { panic!("Unexpected event"); }
2389 expected_events.borrow_mut().push_back(&|ev: &Event| {
2390 if let Event::PaymentFailed { .. } = ev {
2391 } else { panic!("Unexpected event"); }
2393 nodes[0].node.process_pending_events(&invoice_payer);
2394 assert!(expected_events.borrow().is_empty());