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 `MonitorUpdateInProgress`, 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::MonitorUpdateInProgress) => {
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 `MonitorUpdateInProgress`, 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::MonitorUpdateInProgress) => {
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, payment_failed_permanently, 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 *payment_failed_permanently {
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::channelmanager;
784 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
785 use lightning::ln::functional_test_utils::*;
786 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
787 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
788 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
789 use lightning::routing::scoring::ChannelUsage;
790 use lightning::util::test_utils::TestLogger;
791 use lightning::util::errors::APIError;
792 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
793 use secp256k1::{SecretKey, PublicKey, Secp256k1};
794 use std::cell::RefCell;
795 use std::collections::VecDeque;
796 use std::time::{SystemTime, Duration};
797 use time_utils::tests::SinceEpoch;
798 use DEFAULT_EXPIRY_TIME;
799 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
801 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
802 let payment_hash = Sha256::hash(&payment_preimage.0);
803 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
805 InvoiceBuilder::new(Currency::Bitcoin)
806 .description("test".into())
807 .payment_hash(payment_hash)
808 .payment_secret(PaymentSecret([0; 32]))
809 .duration_since_epoch(duration_since_epoch())
810 .min_final_cltv_expiry(144)
811 .amount_milli_satoshis(128)
812 .build_signed(|hash| {
813 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
818 fn duration_since_epoch() -> Duration {
819 #[cfg(feature = "std")]
820 let duration_since_epoch =
821 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
822 #[cfg(not(feature = "std"))]
823 let duration_since_epoch = Duration::from_secs(1234567);
827 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
828 let payment_hash = Sha256::hash(&payment_preimage.0);
829 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
831 InvoiceBuilder::new(Currency::Bitcoin)
832 .description("test".into())
833 .payment_hash(payment_hash)
834 .payment_secret(PaymentSecret([0; 32]))
835 .duration_since_epoch(duration_since_epoch())
836 .min_final_cltv_expiry(144)
837 .build_signed(|hash| {
838 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
843 #[cfg(feature = "std")]
844 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
845 let payment_hash = Sha256::hash(&payment_preimage.0);
846 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
847 let duration = duration_since_epoch()
848 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
850 InvoiceBuilder::new(Currency::Bitcoin)
851 .description("test".into())
852 .payment_hash(payment_hash)
853 .payment_secret(PaymentSecret([0; 32]))
854 .duration_since_epoch(duration)
855 .min_final_cltv_expiry(144)
856 .amount_milli_satoshis(128)
857 .build_signed(|hash| {
858 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
863 fn pubkey() -> PublicKey {
864 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
868 fn pays_invoice_on_first_attempt() {
869 let event_handled = core::cell::RefCell::new(false);
870 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
872 let payment_preimage = PaymentPreimage([1; 32]);
873 let invoice = invoice(payment_preimage);
874 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
875 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
877 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
878 let router = TestRouter {};
879 let scorer = RefCell::new(TestScorer::new());
880 let logger = TestLogger::new();
882 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
884 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
885 assert_eq!(*payer.attempts.borrow(), 1);
887 invoice_payer.handle_event(&Event::PaymentSent {
888 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
890 assert_eq!(*event_handled.borrow(), true);
891 assert_eq!(*payer.attempts.borrow(), 1);
895 fn pays_invoice_on_retry() {
896 let event_handled = core::cell::RefCell::new(false);
897 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
899 let payment_preimage = PaymentPreimage([1; 32]);
900 let invoice = invoice(payment_preimage);
901 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
902 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
904 let payer = TestPayer::new()
905 .expect_send(Amount::ForInvoice(final_value_msat))
906 .expect_send(Amount::OnRetry(final_value_msat / 2));
907 let router = TestRouter {};
908 let scorer = RefCell::new(TestScorer::new());
909 let logger = TestLogger::new();
911 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
913 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
914 assert_eq!(*payer.attempts.borrow(), 1);
916 let event = Event::PaymentPathFailed {
919 network_update: None,
920 payment_failed_permanently: false,
921 all_paths_failed: false,
922 path: TestRouter::path_for_value(final_value_msat),
923 short_channel_id: None,
924 retry: Some(TestRouter::retry_for_invoice(&invoice)),
926 invoice_payer.handle_event(&event);
927 assert_eq!(*event_handled.borrow(), false);
928 assert_eq!(*payer.attempts.borrow(), 2);
930 invoice_payer.handle_event(&Event::PaymentSent {
931 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
933 assert_eq!(*event_handled.borrow(), true);
934 assert_eq!(*payer.attempts.borrow(), 2);
938 fn pays_invoice_on_partial_failure() {
939 let event_handler = |_: &_| { panic!() };
941 let payment_preimage = PaymentPreimage([1; 32]);
942 let invoice = invoice(payment_preimage);
943 let retry = TestRouter::retry_for_invoice(&invoice);
944 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
946 let payer = TestPayer::new()
947 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
948 .fails_with_partial_failure(retry, OnAttempt(2), None)
949 .expect_send(Amount::ForInvoice(final_value_msat))
950 .expect_send(Amount::OnRetry(final_value_msat / 2))
951 .expect_send(Amount::OnRetry(final_value_msat / 2));
952 let router = TestRouter {};
953 let scorer = RefCell::new(TestScorer::new());
954 let logger = TestLogger::new();
956 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
958 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
962 fn retries_payment_path_for_unknown_payment() {
963 let event_handled = core::cell::RefCell::new(false);
964 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
966 let payment_preimage = PaymentPreimage([1; 32]);
967 let invoice = invoice(payment_preimage);
968 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
969 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
971 let payer = TestPayer::new()
972 .expect_send(Amount::OnRetry(final_value_msat / 2))
973 .expect_send(Amount::OnRetry(final_value_msat / 2));
974 let router = TestRouter {};
975 let scorer = RefCell::new(TestScorer::new());
976 let logger = TestLogger::new();
978 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
980 let payment_id = Some(PaymentId([1; 32]));
981 let event = Event::PaymentPathFailed {
984 network_update: None,
985 payment_failed_permanently: false,
986 all_paths_failed: false,
987 path: TestRouter::path_for_value(final_value_msat),
988 short_channel_id: None,
989 retry: Some(TestRouter::retry_for_invoice(&invoice)),
991 invoice_payer.handle_event(&event);
992 assert_eq!(*event_handled.borrow(), false);
993 assert_eq!(*payer.attempts.borrow(), 1);
995 invoice_payer.handle_event(&event);
996 assert_eq!(*event_handled.borrow(), false);
997 assert_eq!(*payer.attempts.borrow(), 2);
999 invoice_payer.handle_event(&Event::PaymentSent {
1000 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1002 assert_eq!(*event_handled.borrow(), true);
1003 assert_eq!(*payer.attempts.borrow(), 2);
1007 fn fails_paying_invoice_after_max_retry_counts() {
1008 let event_handled = core::cell::RefCell::new(false);
1009 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1011 let payment_preimage = PaymentPreimage([1; 32]);
1012 let invoice = invoice(payment_preimage);
1013 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1015 let payer = TestPayer::new()
1016 .expect_send(Amount::ForInvoice(final_value_msat))
1017 .expect_send(Amount::OnRetry(final_value_msat / 2))
1018 .expect_send(Amount::OnRetry(final_value_msat / 2));
1019 let router = TestRouter {};
1020 let scorer = RefCell::new(TestScorer::new());
1021 let logger = TestLogger::new();
1023 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1025 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1026 assert_eq!(*payer.attempts.borrow(), 1);
1028 let event = Event::PaymentPathFailed {
1030 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1031 network_update: None,
1032 payment_failed_permanently: false,
1033 all_paths_failed: true,
1034 path: TestRouter::path_for_value(final_value_msat),
1035 short_channel_id: None,
1036 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1038 invoice_payer.handle_event(&event);
1039 assert_eq!(*event_handled.borrow(), false);
1040 assert_eq!(*payer.attempts.borrow(), 2);
1042 let event = Event::PaymentPathFailed {
1044 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1045 network_update: None,
1046 payment_failed_permanently: false,
1047 all_paths_failed: false,
1048 path: TestRouter::path_for_value(final_value_msat / 2),
1049 short_channel_id: None,
1050 retry: Some(RouteParameters {
1051 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1054 invoice_payer.handle_event(&event);
1055 assert_eq!(*event_handled.borrow(), false);
1056 assert_eq!(*payer.attempts.borrow(), 3);
1058 invoice_payer.handle_event(&event);
1059 assert_eq!(*event_handled.borrow(), true);
1060 assert_eq!(*payer.attempts.borrow(), 3);
1063 #[cfg(feature = "std")]
1065 fn fails_paying_invoice_after_max_retry_timeout() {
1066 let event_handled = core::cell::RefCell::new(false);
1067 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1069 let payment_preimage = PaymentPreimage([1; 32]);
1070 let invoice = invoice(payment_preimage);
1071 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1073 let payer = TestPayer::new()
1074 .expect_send(Amount::ForInvoice(final_value_msat))
1075 .expect_send(Amount::OnRetry(final_value_msat / 2));
1077 let router = TestRouter {};
1078 let scorer = RefCell::new(TestScorer::new());
1079 let logger = TestLogger::new();
1080 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
1083 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1085 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1086 assert_eq!(*payer.attempts.borrow(), 1);
1088 let event = Event::PaymentPathFailed {
1090 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1091 network_update: None,
1092 payment_failed_permanently: false,
1093 all_paths_failed: true,
1094 path: TestRouter::path_for_value(final_value_msat),
1095 short_channel_id: None,
1096 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1098 invoice_payer.handle_event(&event);
1099 assert_eq!(*event_handled.borrow(), false);
1100 assert_eq!(*payer.attempts.borrow(), 2);
1102 SinceEpoch::advance(Duration::from_secs(121));
1104 invoice_payer.handle_event(&event);
1105 assert_eq!(*event_handled.borrow(), true);
1106 assert_eq!(*payer.attempts.borrow(), 2);
1110 fn fails_paying_invoice_with_missing_retry_params() {
1111 let event_handled = core::cell::RefCell::new(false);
1112 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1114 let payment_preimage = PaymentPreimage([1; 32]);
1115 let invoice = invoice(payment_preimage);
1116 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1118 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1119 let router = TestRouter {};
1120 let scorer = RefCell::new(TestScorer::new());
1121 let logger = TestLogger::new();
1123 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1125 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1126 assert_eq!(*payer.attempts.borrow(), 1);
1128 let event = Event::PaymentPathFailed {
1130 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1131 network_update: None,
1132 payment_failed_permanently: false,
1133 all_paths_failed: false,
1135 short_channel_id: None,
1138 invoice_payer.handle_event(&event);
1139 assert_eq!(*event_handled.borrow(), true);
1140 assert_eq!(*payer.attempts.borrow(), 1);
1143 // Expiration is checked only in an std environment
1144 #[cfg(feature = "std")]
1146 fn fails_paying_invoice_after_expiration() {
1147 let event_handled = core::cell::RefCell::new(false);
1148 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1150 let payer = TestPayer::new();
1151 let router = TestRouter {};
1152 let scorer = RefCell::new(TestScorer::new());
1153 let logger = TestLogger::new();
1155 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1157 let payment_preimage = PaymentPreimage([1; 32]);
1158 let invoice = expired_invoice(payment_preimage);
1159 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1160 assert_eq!(msg, "Invoice expired prior to send");
1161 } else { panic!("Expected Invoice Error"); }
1164 // Expiration is checked only in an std environment
1165 #[cfg(feature = "std")]
1167 fn fails_retrying_invoice_after_expiration() {
1168 let event_handled = core::cell::RefCell::new(false);
1169 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1171 let payment_preimage = PaymentPreimage([1; 32]);
1172 let invoice = invoice(payment_preimage);
1173 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1175 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1176 let router = TestRouter {};
1177 let scorer = RefCell::new(TestScorer::new());
1178 let logger = TestLogger::new();
1180 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1182 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1183 assert_eq!(*payer.attempts.borrow(), 1);
1185 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1186 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1187 .checked_sub(Duration::from_secs(2)).unwrap()
1188 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1189 let event = Event::PaymentPathFailed {
1191 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1192 network_update: None,
1193 payment_failed_permanently: false,
1194 all_paths_failed: false,
1196 short_channel_id: None,
1197 retry: Some(retry_data),
1199 invoice_payer.handle_event(&event);
1200 assert_eq!(*event_handled.borrow(), true);
1201 assert_eq!(*payer.attempts.borrow(), 1);
1205 fn fails_paying_invoice_after_retry_error() {
1206 let event_handled = core::cell::RefCell::new(false);
1207 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1209 let payment_preimage = PaymentPreimage([1; 32]);
1210 let invoice = invoice(payment_preimage);
1211 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1213 let payer = TestPayer::new()
1214 .fails_on_attempt(2)
1215 .expect_send(Amount::ForInvoice(final_value_msat))
1216 .expect_send(Amount::OnRetry(final_value_msat / 2));
1217 let router = TestRouter {};
1218 let scorer = RefCell::new(TestScorer::new());
1219 let logger = TestLogger::new();
1221 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1223 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1224 assert_eq!(*payer.attempts.borrow(), 1);
1226 let event = Event::PaymentPathFailed {
1228 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1229 network_update: None,
1230 payment_failed_permanently: false,
1231 all_paths_failed: false,
1232 path: TestRouter::path_for_value(final_value_msat / 2),
1233 short_channel_id: None,
1234 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1236 invoice_payer.handle_event(&event);
1237 assert_eq!(*event_handled.borrow(), true);
1238 assert_eq!(*payer.attempts.borrow(), 2);
1242 fn fails_paying_invoice_after_rejected_by_payee() {
1243 let event_handled = core::cell::RefCell::new(false);
1244 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1246 let payment_preimage = PaymentPreimage([1; 32]);
1247 let invoice = invoice(payment_preimage);
1248 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1250 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1251 let router = TestRouter {};
1252 let scorer = RefCell::new(TestScorer::new());
1253 let logger = TestLogger::new();
1255 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1257 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1258 assert_eq!(*payer.attempts.borrow(), 1);
1260 let event = Event::PaymentPathFailed {
1262 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1263 network_update: None,
1264 payment_failed_permanently: true,
1265 all_paths_failed: false,
1267 short_channel_id: None,
1268 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1270 invoice_payer.handle_event(&event);
1271 assert_eq!(*event_handled.borrow(), true);
1272 assert_eq!(*payer.attempts.borrow(), 1);
1276 fn fails_repaying_invoice_with_pending_payment() {
1277 let event_handled = core::cell::RefCell::new(false);
1278 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1280 let payment_preimage = PaymentPreimage([1; 32]);
1281 let invoice = invoice(payment_preimage);
1282 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1284 let payer = TestPayer::new()
1285 .expect_send(Amount::ForInvoice(final_value_msat))
1286 .expect_send(Amount::ForInvoice(final_value_msat));
1287 let router = TestRouter {};
1288 let scorer = RefCell::new(TestScorer::new());
1289 let logger = TestLogger::new();
1291 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1293 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1295 // Cannot repay an invoice pending payment.
1296 match invoice_payer.pay_invoice(&invoice) {
1297 Err(PaymentError::Invoice("payment pending")) => {},
1298 Err(_) => panic!("unexpected error"),
1299 Ok(_) => panic!("expected invoice error"),
1302 // Can repay an invoice once cleared from cache.
1303 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1304 invoice_payer.remove_cached_payment(&payment_hash);
1305 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1307 // Cannot retry paying an invoice if cleared from cache.
1308 invoice_payer.remove_cached_payment(&payment_hash);
1309 let event = Event::PaymentPathFailed {
1312 network_update: None,
1313 payment_failed_permanently: false,
1314 all_paths_failed: false,
1316 short_channel_id: None,
1317 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1319 invoice_payer.handle_event(&event);
1320 assert_eq!(*event_handled.borrow(), true);
1324 fn fails_paying_invoice_with_routing_errors() {
1325 let payer = TestPayer::new();
1326 let router = FailingRouter {};
1327 let scorer = RefCell::new(TestScorer::new());
1328 let logger = TestLogger::new();
1330 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1332 let payment_preimage = PaymentPreimage([1; 32]);
1333 let invoice = invoice(payment_preimage);
1334 match invoice_payer.pay_invoice(&invoice) {
1335 Err(PaymentError::Routing(_)) => {},
1336 Err(_) => panic!("unexpected error"),
1337 Ok(_) => panic!("expected routing error"),
1342 fn fails_paying_invoice_with_sending_errors() {
1343 let payment_preimage = PaymentPreimage([1; 32]);
1344 let invoice = invoice(payment_preimage);
1345 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1347 let payer = TestPayer::new()
1348 .fails_on_attempt(1)
1349 .expect_send(Amount::ForInvoice(final_value_msat));
1350 let router = TestRouter {};
1351 let scorer = RefCell::new(TestScorer::new());
1352 let logger = TestLogger::new();
1354 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1356 match invoice_payer.pay_invoice(&invoice) {
1357 Err(PaymentError::Sending(_)) => {},
1358 Err(_) => panic!("unexpected error"),
1359 Ok(_) => panic!("expected sending error"),
1364 fn pays_zero_value_invoice_using_amount() {
1365 let event_handled = core::cell::RefCell::new(false);
1366 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1368 let payment_preimage = PaymentPreimage([1; 32]);
1369 let invoice = zero_value_invoice(payment_preimage);
1370 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1371 let final_value_msat = 100;
1373 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1374 let router = TestRouter {};
1375 let scorer = RefCell::new(TestScorer::new());
1376 let logger = TestLogger::new();
1378 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1381 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1382 assert_eq!(*payer.attempts.borrow(), 1);
1384 invoice_payer.handle_event(&Event::PaymentSent {
1385 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1387 assert_eq!(*event_handled.borrow(), true);
1388 assert_eq!(*payer.attempts.borrow(), 1);
1392 fn fails_paying_zero_value_invoice_with_amount() {
1393 let event_handled = core::cell::RefCell::new(false);
1394 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1396 let payer = TestPayer::new();
1397 let router = TestRouter {};
1398 let scorer = RefCell::new(TestScorer::new());
1399 let logger = TestLogger::new();
1401 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1403 let payment_preimage = PaymentPreimage([1; 32]);
1404 let invoice = invoice(payment_preimage);
1406 // Cannot repay an invoice pending payment.
1407 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1408 Err(PaymentError::Invoice("amount unexpected")) => {},
1409 Err(_) => panic!("unexpected error"),
1410 Ok(_) => panic!("expected invoice error"),
1415 fn pays_pubkey_with_amount() {
1416 let event_handled = core::cell::RefCell::new(false);
1417 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1419 let pubkey = pubkey();
1420 let payment_preimage = PaymentPreimage([1; 32]);
1421 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1422 let final_value_msat = 100;
1423 let final_cltv_expiry_delta = 42;
1425 let payer = TestPayer::new()
1426 .expect_send(Amount::Spontaneous(final_value_msat))
1427 .expect_send(Amount::OnRetry(final_value_msat));
1428 let router = TestRouter {};
1429 let scorer = RefCell::new(TestScorer::new());
1430 let logger = TestLogger::new();
1432 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1434 let payment_id = Some(invoice_payer.pay_pubkey(
1435 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1437 assert_eq!(*payer.attempts.borrow(), 1);
1439 let retry = RouteParameters {
1440 payment_params: PaymentParameters::for_keysend(pubkey),
1442 final_cltv_expiry_delta,
1444 let event = Event::PaymentPathFailed {
1447 network_update: None,
1448 payment_failed_permanently: false,
1449 all_paths_failed: false,
1451 short_channel_id: None,
1454 invoice_payer.handle_event(&event);
1455 assert_eq!(*event_handled.borrow(), false);
1456 assert_eq!(*payer.attempts.borrow(), 2);
1458 invoice_payer.handle_event(&Event::PaymentSent {
1459 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1461 assert_eq!(*event_handled.borrow(), true);
1462 assert_eq!(*payer.attempts.borrow(), 2);
1466 fn scores_failed_channel() {
1467 let event_handled = core::cell::RefCell::new(false);
1468 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1470 let payment_preimage = PaymentPreimage([1; 32]);
1471 let invoice = invoice(payment_preimage);
1472 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1473 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1474 let path = TestRouter::path_for_value(final_value_msat);
1475 let short_channel_id = Some(path[0].short_channel_id);
1477 // Expect that scorer is given short_channel_id upon handling the event.
1478 let payer = TestPayer::new()
1479 .expect_send(Amount::ForInvoice(final_value_msat))
1480 .expect_send(Amount::OnRetry(final_value_msat / 2));
1481 let router = TestRouter {};
1482 let scorer = RefCell::new(TestScorer::new().expect(TestResult::PaymentFailure {
1483 path: path.clone(), short_channel_id: path[0].short_channel_id,
1485 let logger = TestLogger::new();
1487 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1489 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1490 let event = Event::PaymentPathFailed {
1493 network_update: None,
1494 payment_failed_permanently: false,
1495 all_paths_failed: false,
1498 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1500 invoice_payer.handle_event(&event);
1504 fn scores_successful_channels() {
1505 let event_handled = core::cell::RefCell::new(false);
1506 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1508 let payment_preimage = PaymentPreimage([1; 32]);
1509 let invoice = invoice(payment_preimage);
1510 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1511 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1512 let route = TestRouter::route_for_value(final_value_msat);
1514 // Expect that scorer is given short_channel_id upon handling the event.
1515 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1516 let router = TestRouter {};
1517 let scorer = RefCell::new(TestScorer::new()
1518 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1519 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() })
1521 let logger = TestLogger::new();
1523 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1525 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1526 let event = Event::PaymentPathSuccessful {
1527 payment_id, payment_hash, path: route.paths[0].clone()
1529 invoice_payer.handle_event(&event);
1530 let event = Event::PaymentPathSuccessful {
1531 payment_id, payment_hash, path: route.paths[1].clone()
1533 invoice_payer.handle_event(&event);
1537 fn generates_correct_inflight_map_data() {
1538 let event_handled = core::cell::RefCell::new(false);
1539 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1541 let payment_preimage = PaymentPreimage([1; 32]);
1542 let invoice = invoice(payment_preimage);
1543 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1544 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1546 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1547 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1548 let route = TestRouter::route_for_value(final_value_msat);
1549 let router = TestRouter {};
1550 let scorer = RefCell::new(TestScorer::new());
1551 let logger = TestLogger::new();
1553 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1555 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1557 let inflight_map = invoice_payer.create_inflight_map();
1559 assert_eq!(inflight_map.get(&(0, false)).unwrap().clone(), 94);
1560 assert_eq!(inflight_map.get(&(1, true)).unwrap().clone(), 84);
1561 assert_eq!(inflight_map.get(&(2, false)).unwrap().clone(), 64);
1563 // Second path check
1564 assert_eq!(inflight_map.get(&(3, false)).unwrap().clone(), 74);
1565 assert_eq!(inflight_map.get(&(4, false)).unwrap().clone(), 64);
1567 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1568 payment_id, payment_hash, path: route.paths[0].clone()
1571 let inflight_map = invoice_payer.create_inflight_map();
1573 assert_eq!(inflight_map.get(&(0, false)), None);
1574 assert_eq!(inflight_map.get(&(1, true)), None);
1575 assert_eq!(inflight_map.get(&(2, false)), None);
1577 // Second path should still be inflight
1578 assert_eq!(inflight_map.get(&(3, false)).unwrap().clone(), 74);
1579 assert_eq!(inflight_map.get(&(4, false)).unwrap().clone(), 64)
1583 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1584 // First, let's just send a payment through, but only make sure one of the path completes
1585 let event_handled = core::cell::RefCell::new(false);
1586 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1588 let payment_preimage = PaymentPreimage([1; 32]);
1589 let payment_invoice = invoice(payment_preimage);
1590 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1591 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1593 let payer = TestPayer::new()
1594 .expect_send(Amount::ForInvoice(final_value_msat))
1595 .expect_send(Amount::ForInvoice(final_value_msat));
1596 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1597 let route = TestRouter::route_for_value(final_value_msat);
1598 let router = TestRouter {};
1599 let scorer = RefCell::new(TestScorer::new()
1600 // 1st invoice, 1st path
1601 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1602 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1603 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1604 // 1st invoice, 2nd path
1605 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1606 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1607 // 2nd invoice, 1st path
1608 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1609 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1610 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1611 // 2nd invoice, 2nd path
1612 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1613 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } )
1615 let logger = TestLogger::new();
1617 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1619 // Succeed 1st path, leave 2nd path inflight
1620 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1621 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1622 payment_id, payment_hash, path: route.paths[0].clone()
1625 // Let's pay a second invoice that will be using the same path. This should trigger the
1626 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1627 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1628 // have 64 msats inflight for paths considering the channel with scid of 1.
1629 let payment_preimage_2 = PaymentPreimage([2; 32]);
1630 let payment_invoice_2 = invoice(payment_preimage_2);
1631 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1635 fn considers_inflight_htlcs_between_retries() {
1636 // First, let's just send a payment through, but only make sure one of the path completes
1637 let event_handled = core::cell::RefCell::new(false);
1638 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1640 let payment_preimage = PaymentPreimage([1; 32]);
1641 let payment_invoice = invoice(payment_preimage);
1642 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1643 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1645 let payer = TestPayer::new()
1646 .expect_send(Amount::ForInvoice(final_value_msat))
1647 .expect_send(Amount::OnRetry(final_value_msat / 2))
1648 .expect_send(Amount::OnRetry(final_value_msat / 4));
1649 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1650 let router = TestRouter {};
1651 let scorer = RefCell::new(TestScorer::new()
1652 // 1st invoice, 1st path
1653 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1654 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1655 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1656 // 1st invoice, 2nd path
1657 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1658 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1659 // Retry 1, 1st path
1660 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1661 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1662 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1663 // Retry 1, 2nd path
1664 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1665 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1666 // Retry 2, 1st path
1667 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1668 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1669 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1670 // Retry 2, 2nd path
1671 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1672 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1674 let logger = TestLogger::new();
1676 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1678 // Fail 1st path, leave 2nd path inflight
1679 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1680 invoice_payer.handle_event(&Event::PaymentPathFailed {
1683 network_update: None,
1684 payment_failed_permanently: false,
1685 all_paths_failed: false,
1686 path: TestRouter::path_for_value(final_value_msat),
1687 short_channel_id: None,
1688 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1691 // Fails again the 1st path of our retry
1692 invoice_payer.handle_event(&Event::PaymentPathFailed {
1695 network_update: None,
1696 payment_failed_permanently: false,
1697 all_paths_failed: false,
1698 path: TestRouter::path_for_value(final_value_msat / 2),
1699 short_channel_id: None,
1700 retry: Some(RouteParameters {
1701 final_value_msat: final_value_msat / 4,
1702 ..TestRouter::retry_for_invoice(&payment_invoice)
1708 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1709 let event_handled = core::cell::RefCell::new(false);
1710 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1712 let payment_preimage = PaymentPreimage([1; 32]);
1713 let invoice_to_pay = invoice(payment_preimage);
1714 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1716 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1717 let payer = TestPayer::new()
1718 .fails_with_partial_failure(
1719 retry.clone(), OnAttempt(1),
1721 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1723 .expect_send(Amount::ForInvoice(final_value_msat));
1725 let router = TestRouter {};
1726 let scorer = RefCell::new(TestScorer::new());
1727 let logger = TestLogger::new();
1729 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1731 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1732 let inflight_map = invoice_payer.create_inflight_map();
1734 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1735 // inflight map because retries are disabled.
1736 assert_eq!(inflight_map.len(), 2);
1740 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1741 let event_handled = core::cell::RefCell::new(false);
1742 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1744 let payment_preimage = PaymentPreimage([1; 32]);
1745 let invoice_to_pay = invoice(payment_preimage);
1746 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1748 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1749 let payer = TestPayer::new()
1750 .fails_with_partial_failure(
1751 retry.clone(), OnAttempt(1),
1753 Ok(()), Err(MonitorUpdateInProgress)
1755 .expect_send(Amount::ForInvoice(final_value_msat));
1757 let router = TestRouter {};
1758 let scorer = RefCell::new(TestScorer::new());
1759 let logger = TestLogger::new();
1761 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1763 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1764 let inflight_map = invoice_payer.create_inflight_map();
1766 // All paths successful, hence we check of the existence of all 5 hops.
1767 assert_eq!(inflight_map.len(), 5);
1773 fn route_for_value(final_value_msat: u64) -> Route {
1778 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1779 channel_features: ChannelFeatures::empty(),
1780 node_features: NodeFeatures::empty(),
1781 short_channel_id: 0,
1783 cltv_expiry_delta: 0
1786 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1787 channel_features: ChannelFeatures::empty(),
1788 node_features: NodeFeatures::empty(),
1789 short_channel_id: 1,
1791 cltv_expiry_delta: 0
1794 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1795 channel_features: ChannelFeatures::empty(),
1796 node_features: NodeFeatures::empty(),
1797 short_channel_id: 2,
1798 fee_msat: final_value_msat / 2,
1799 cltv_expiry_delta: 0
1804 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1805 channel_features: ChannelFeatures::empty(),
1806 node_features: NodeFeatures::empty(),
1807 short_channel_id: 3,
1809 cltv_expiry_delta: 144
1812 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1813 channel_features: ChannelFeatures::empty(),
1814 node_features: NodeFeatures::empty(),
1815 short_channel_id: 4,
1816 fee_msat: final_value_msat / 2,
1817 cltv_expiry_delta: 144
1821 payment_params: None,
1825 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1826 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1829 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1830 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1831 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1832 .with_route_hints(invoice.route_hints());
1833 if let Some(features) = invoice.features() {
1834 payment_params = payment_params.with_features(features.clone());
1836 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1840 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1845 impl Router for TestRouter {
1846 fn find_route<S: Score>(
1847 &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1848 _first_hops: Option<&[&ChannelDetails]>, scorer: &S
1849 ) -> Result<Route, LightningError> {
1850 // Simulate calling the Scorer just as you would in find_route
1851 let route = Self::route_for_value(route_params.final_value_msat);
1852 for path in route.paths {
1853 let mut aggregate_msat = 0u64;
1854 for (idx, hop) in path.iter().rev().enumerate() {
1855 aggregate_msat += hop.fee_msat;
1856 let usage = ChannelUsage {
1857 amount_msat: aggregate_msat,
1858 inflight_htlc_msat: 0,
1859 effective_capacity: EffectiveCapacity::Unknown,
1862 // Since the path is reversed, the last element in our iteration is the first
1864 if idx == path.len() - 1 {
1865 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1867 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1873 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1878 struct FailingRouter;
1880 impl Router for FailingRouter {
1881 fn find_route<S: Score>(
1882 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1883 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1884 ) -> Result<Route, LightningError> {
1885 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1890 event_expectations: Option<VecDeque<TestResult>>,
1891 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1896 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1897 PaymentSuccess { path: Vec<RouteHop> },
1903 event_expectations: None,
1904 scorer_expectations: RefCell::new(None),
1908 fn expect(mut self, expectation: TestResult) -> Self {
1909 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1913 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1914 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1920 impl lightning::util::ser::Writeable for TestScorer {
1921 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1924 impl Score for TestScorer {
1925 fn channel_penalty_msat(
1926 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1928 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1929 match scorer_expectations.pop_front() {
1930 Some(expectation) => {
1931 assert_eq!(expectation.amount_msat, usage.amount_msat);
1932 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1940 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1941 if let Some(expectations) = &mut self.event_expectations {
1942 match expectations.pop_front() {
1943 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1944 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1945 assert_eq!(actual_short_channel_id, short_channel_id);
1947 Some(TestResult::PaymentSuccess { path }) => {
1948 panic!("Unexpected successful payment path: {:?}", path)
1950 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1955 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1956 if let Some(expectations) = &mut self.event_expectations {
1957 match expectations.pop_front() {
1958 Some(TestResult::PaymentFailure { path, .. }) => {
1959 panic!("Unexpected payment path failure: {:?}", path)
1961 Some(TestResult::PaymentSuccess { path }) => {
1962 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1964 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1969 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1970 if let Some(expectations) = &mut self.event_expectations {
1971 match expectations.pop_front() {
1972 Some(TestResult::PaymentFailure { path, .. }) => {
1973 panic!("Unexpected failed payment path: {:?}", path)
1975 Some(TestResult::PaymentSuccess { path }) => {
1976 panic!("Unexpected successful payment path: {:?}", path)
1978 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1982 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1983 if let Some(expectations) = &mut self.event_expectations {
1984 match expectations.pop_front() {
1985 Some(TestResult::PaymentFailure { path, .. }) => {
1986 panic!("Unexpected payment path failure: {:?}", path)
1988 Some(TestResult::PaymentSuccess { path }) => {
1989 panic!("Unexpected successful payment path: {:?}", path)
1991 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1997 impl Drop for TestScorer {
1998 fn drop(&mut self) {
1999 if std::thread::panicking() {
2003 if let Some(event_expectations) = &self.event_expectations {
2004 if !event_expectations.is_empty() {
2005 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2009 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2010 if !scorer_expectations.is_empty() {
2011 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2018 expectations: core::cell::RefCell<VecDeque<Amount>>,
2019 attempts: core::cell::RefCell<usize>,
2020 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2023 #[derive(Clone, Debug, PartialEq, Eq)]
2030 struct OnAttempt(usize);
2035 expectations: core::cell::RefCell::new(VecDeque::new()),
2036 attempts: core::cell::RefCell::new(0),
2037 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2041 fn expect_send(self, value_msat: Amount) -> Self {
2042 self.expectations.borrow_mut().push_back(value_msat);
2046 fn fails_on_attempt(self, attempt: usize) -> Self {
2047 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2048 self.fails_with(failure, OnAttempt(attempt))
2051 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2052 self.fails_with(PaymentSendFailure::PartialFailure {
2053 results: results.unwrap_or(vec![]),
2054 failed_paths_retry: Some(retry),
2055 payment_id: PaymentId([1; 32]),
2059 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2060 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2064 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2065 let mut attempts = self.attempts.borrow_mut();
2068 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2069 Some(failure) => Err(failure),
2070 None => Ok(PaymentId([1; 32])),
2074 fn check_value_msats(&self, actual_value_msats: Amount) {
2075 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2076 if let Some(expected_value_msats) = expected_value_msats {
2077 assert_eq!(actual_value_msats, expected_value_msats);
2079 panic!("Unexpected amount: {:?}", actual_value_msats);
2084 impl Drop for TestPayer {
2085 fn drop(&mut self) {
2086 if std::thread::panicking() {
2090 if !self.expectations.borrow().is_empty() {
2091 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2096 impl Payer for TestPayer {
2097 fn node_id(&self) -> PublicKey {
2098 let secp_ctx = Secp256k1::new();
2099 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2102 fn first_hops(&self) -> Vec<ChannelDetails> {
2107 &self, route: &Route, _payment_hash: PaymentHash,
2108 _payment_secret: &Option<PaymentSecret>
2109 ) -> Result<PaymentId, PaymentSendFailure> {
2110 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2111 self.check_attempts()
2114 fn send_spontaneous_payment(
2115 &self, route: &Route, _payment_preimage: PaymentPreimage,
2116 ) -> Result<PaymentId, PaymentSendFailure> {
2117 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2118 self.check_attempts()
2122 &self, route: &Route, _payment_id: PaymentId
2123 ) -> Result<(), PaymentSendFailure> {
2124 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2125 self.check_attempts().map(|_| ())
2128 fn abandon_payment(&self, _payment_id: PaymentId) { }
2131 // *** Full Featured Functional Tests with a Real ChannelManager ***
2132 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2134 impl Router for ManualRouter {
2135 fn find_route<S: Score>(
2136 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
2137 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
2138 ) -> Result<Route, LightningError> {
2139 self.0.borrow_mut().pop_front().unwrap()
2143 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2144 self.0.borrow_mut().push_back(result);
2147 impl Drop for ManualRouter {
2148 fn drop(&mut self) {
2149 if std::thread::panicking() {
2152 assert!(self.0.borrow_mut().is_empty());
2157 fn retry_multi_path_single_failed_payment() {
2158 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2159 let chanmon_cfgs = create_chanmon_cfgs(2);
2160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2162 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2164 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2165 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2166 let chans = nodes[0].node.list_usable_channels();
2167 let mut route = Route {
2170 pubkey: nodes[1].node.get_our_node_id(),
2171 node_features: channelmanager::provided_node_features(),
2172 short_channel_id: chans[0].short_channel_id.unwrap(),
2173 channel_features: channelmanager::provided_channel_features(),
2175 cltv_expiry_delta: 100,
2178 pubkey: nodes[1].node.get_our_node_id(),
2179 node_features: channelmanager::provided_node_features(),
2180 short_channel_id: chans[1].short_channel_id.unwrap(),
2181 channel_features: channelmanager::provided_channel_features(),
2182 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2183 cltv_expiry_delta: 100,
2186 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2188 let router = ManualRouter(RefCell::new(VecDeque::new()));
2189 router.expect_find_route(Ok(route.clone()));
2190 // On retry, split the payment across both channels.
2191 route.paths[0][0].fee_msat = 50_000_001;
2192 route.paths[1][0].fee_msat = 50_000_000;
2193 router.expect_find_route(Ok(route.clone()));
2195 let event_handler = |_: &_| { panic!(); };
2196 let scorer = RefCell::new(TestScorer::new());
2197 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2199 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2200 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2201 duration_since_epoch(), 3600).unwrap())
2203 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2204 assert_eq!(htlc_msgs.len(), 2);
2205 check_added_monitors!(nodes[0], 2);
2209 fn immediate_retry_on_failure() {
2210 // Tests that we can/will retry immediately after a failure
2211 let chanmon_cfgs = create_chanmon_cfgs(2);
2212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2214 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2216 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2217 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2218 let chans = nodes[0].node.list_usable_channels();
2219 let mut route = Route {
2222 pubkey: nodes[1].node.get_our_node_id(),
2223 node_features: channelmanager::provided_node_features(),
2224 short_channel_id: chans[0].short_channel_id.unwrap(),
2225 channel_features: channelmanager::provided_channel_features(),
2226 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2227 cltv_expiry_delta: 100,
2230 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2232 let router = ManualRouter(RefCell::new(VecDeque::new()));
2233 router.expect_find_route(Ok(route.clone()));
2234 // On retry, split the payment across both channels.
2235 route.paths.push(route.paths[0].clone());
2236 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2237 route.paths[0][0].fee_msat = 50_000_000;
2238 route.paths[1][0].fee_msat = 50_000_001;
2239 router.expect_find_route(Ok(route.clone()));
2241 let event_handler = |_: &_| { panic!(); };
2242 let scorer = RefCell::new(TestScorer::new());
2243 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2245 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2246 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2247 duration_since_epoch(), 3600).unwrap())
2249 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2250 assert_eq!(htlc_msgs.len(), 2);
2251 check_added_monitors!(nodes[0], 2);
2255 fn no_extra_retries_on_back_to_back_fail() {
2256 // In a previous release, we had a race where we may exceed the payment retry count if we
2257 // get two failures in a row with the second having `all_paths_failed` set.
2258 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2259 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2260 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2261 // pending which we will see later. Thus, when we previously removed the retry tracking map
2262 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2263 // retry entry even though more events for the same payment were still pending. This led to
2264 // us retrying a payment again even though we'd already given up on it.
2266 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2267 // is used to remove the payment retry counter entries instead. This tests for the specific
2268 // excess-retry case while also testing `PaymentFailed` generation.
2270 let chanmon_cfgs = create_chanmon_cfgs(3);
2271 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2272 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2273 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2275 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;
2276 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;
2278 let mut route = Route {
2281 pubkey: nodes[1].node.get_our_node_id(),
2282 node_features: channelmanager::provided_node_features(),
2283 short_channel_id: chan_1_scid,
2284 channel_features: channelmanager::provided_channel_features(),
2286 cltv_expiry_delta: 100,
2288 pubkey: nodes[2].node.get_our_node_id(),
2289 node_features: channelmanager::provided_node_features(),
2290 short_channel_id: chan_2_scid,
2291 channel_features: channelmanager::provided_channel_features(),
2292 fee_msat: 100_000_000,
2293 cltv_expiry_delta: 100,
2296 pubkey: nodes[1].node.get_our_node_id(),
2297 node_features: channelmanager::provided_node_features(),
2298 short_channel_id: chan_1_scid,
2299 channel_features: channelmanager::provided_channel_features(),
2301 cltv_expiry_delta: 100,
2303 pubkey: nodes[2].node.get_our_node_id(),
2304 node_features: channelmanager::provided_node_features(),
2305 short_channel_id: chan_2_scid,
2306 channel_features: channelmanager::provided_channel_features(),
2307 fee_msat: 100_000_000,
2308 cltv_expiry_delta: 100,
2311 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2313 let router = ManualRouter(RefCell::new(VecDeque::new()));
2314 router.expect_find_route(Ok(route.clone()));
2315 // On retry, we'll only be asked for one path
2316 route.paths.remove(1);
2317 router.expect_find_route(Ok(route.clone()));
2319 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2320 let event_handler = |event: &Event| {
2321 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2322 event_checker(event);
2324 let scorer = RefCell::new(TestScorer::new());
2325 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
2327 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2328 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
2329 duration_since_epoch(), 3600).unwrap())
2331 let htlc_updates = SendEvent::from_node(&nodes[0]);
2332 check_added_monitors!(nodes[0], 1);
2333 assert_eq!(htlc_updates.msgs.len(), 1);
2335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2336 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2337 check_added_monitors!(nodes[1], 1);
2338 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2340 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2341 check_added_monitors!(nodes[0], 1);
2342 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2344 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2345 check_added_monitors!(nodes[0], 1);
2346 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2348 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2349 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2350 check_added_monitors!(nodes[1], 1);
2351 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2353 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2354 check_added_monitors!(nodes[1], 1);
2355 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2358 check_added_monitors!(nodes[0], 1);
2360 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2361 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2362 check_added_monitors!(nodes[0], 1);
2363 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2365 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2366 check_added_monitors!(nodes[1], 1);
2367 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2369 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2370 check_added_monitors!(nodes[1], 1);
2371 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2373 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2374 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2375 check_added_monitors!(nodes[0], 1);
2377 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2378 check_added_monitors!(nodes[0], 1);
2379 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2381 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2382 check_added_monitors!(nodes[1], 1);
2383 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2384 check_added_monitors!(nodes[1], 1);
2385 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2387 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2388 check_added_monitors!(nodes[0], 1);
2390 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2391 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2392 // with it set. The first event will use up the only retry we are allowed, with the second
2393 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2394 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2395 // if the final HTLC failed.
2396 expected_events.borrow_mut().push_back(&|ev: &Event| {
2397 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2398 assert!(!payment_failed_permanently);
2399 assert!(all_paths_failed);
2400 } else { panic!("Unexpected event"); }
2402 nodes[0].node.process_pending_events(&invoice_payer);
2403 assert!(expected_events.borrow().is_empty());
2405 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2406 check_added_monitors!(nodes[0], 1);
2408 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2409 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2410 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2411 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2412 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2414 expected_events.borrow_mut().push_back(&|ev: &Event| {
2415 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2416 assert!(!payment_failed_permanently);
2417 assert!(all_paths_failed);
2418 } else { panic!("Unexpected event"); }
2420 expected_events.borrow_mut().push_back(&|ev: &Event| {
2421 if let Event::PaymentFailed { .. } = ev {
2422 } else { panic!("Unexpected event"); }
2424 nodes[0].node.process_pending_events(&invoice_payer);
2425 assert!(expected_events.borrow().is_empty());