1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InFlightHtlcs, InvoicePayer, Payer, Retry, Router};
48 //! # use secp256k1::PublicKey;
49 //! # use std::cell::RefCell;
50 //! # use std::ops::Deref;
52 //! # struct FakeEventProvider {}
53 //! # impl EventsProvider for FakeEventProvider {
54 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
57 //! # struct FakePayer {}
58 //! # impl Payer for FakePayer {
59 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
60 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
61 //! # fn send_payment(
62 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
63 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
64 //! # fn send_spontaneous_payment(
65 //! # &self, route: &Route, payment_preimage: PaymentPreimage
66 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
67 //! # fn retry_payment(
68 //! # &self, route: &Route, payment_id: PaymentId
69 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
70 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
73 //! # struct FakeRouter {}
74 //! # impl Router for FakeRouter {
76 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
77 //! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
78 //! # ) -> Result<Route, LightningError> { unimplemented!() }
80 //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
81 //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() }
82 //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() }
83 //! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
86 //! # struct FakeScorer {}
87 //! # impl Writeable for FakeScorer {
88 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
90 //! # impl Score for FakeScorer {
91 //! # fn channel_penalty_msat(
92 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
94 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
95 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
96 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
97 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
100 //! # struct FakeLogger {}
101 //! # impl Logger for FakeLogger {
102 //! # fn log(&self, record: &Record) { unimplemented!() }
106 //! let event_handler = |event: &Event| {
108 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
109 //! Event::PaymentSent { .. } => println!("payment successful"),
113 //! # let payer = FakePayer {};
114 //! # let router = FakeRouter {};
115 //! # let scorer = RefCell::new(FakeScorer {});
116 //! # let logger = FakeLogger {};
117 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
119 //! let invoice = "...";
120 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
121 //! invoice_payer.pay_invoice(&invoice).unwrap();
123 //! # let event_provider = FakeEventProvider {};
125 //! event_provider.process_pending_events(&invoice_payer);
133 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
134 //! as updates to the network graph or changes to channel scores should be applied prior to
135 //! retries, typically by way of composing [`EventHandler`]s accordingly.
139 use bitcoin_hashes::Hash;
140 use bitcoin_hashes::sha256::Hash as Sha256;
142 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::router::{PaymentParameters, Route, RouteHop, RouteParameters};
149 use lightning::util::errors::APIError;
150 use lightning::util::events::{Event, EventHandler};
151 use lightning::util::logger::Logger;
152 use lightning::util::ser::Writeable;
153 use crate::time_utils::Time;
154 use crate::sync::Mutex;
156 use secp256k1::PublicKey;
159 use core::fmt::{Debug, Display, Formatter};
160 use core::ops::Deref;
161 use core::time::Duration;
162 #[cfg(feature = "std")]
163 use std::time::SystemTime;
165 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
167 /// See [module-level documentation] for details.
169 /// [module-level documentation]: crate::payment
170 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
172 #[cfg(not(feature = "no-std"))]
173 type ConfiguredTime = std::time::Instant;
174 #[cfg(feature = "no-std")]
175 use crate::time_utils;
176 #[cfg(feature = "no-std")]
177 type ConfiguredTime = time_utils::Eternity;
179 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
180 pub struct InvoicePayerUsingTime<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time>
189 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
190 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
194 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
195 /// currently being made, or have outstanding paths that need retrying.
196 struct PaymentInfo<T: Time> {
197 attempts: PaymentAttempts<T>,
198 paths: Vec<Vec<RouteHop>>,
201 impl<T: Time> PaymentInfo<T> {
204 attempts: PaymentAttempts::new(),
210 /// Storing minimal payment attempts information required for determining if a outbound payment can
212 #[derive(Clone, Copy)]
213 struct PaymentAttempts<T: Time> {
214 /// This count will be incremented only after the result of the attempt is known. When it's 0,
215 /// it means the result of the first attempt is now known yet.
217 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
218 first_attempted_at: T
221 impl<T: Time> PaymentAttempts<T> {
225 first_attempted_at: T::now()
230 impl<T: Time> Display for PaymentAttempts<T> {
231 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
232 #[cfg(feature = "no-std")]
233 return write!( f, "attempts: {}", self.count);
234 #[cfg(not(feature = "no-std"))]
237 "attempts: {}, duration: {}s",
239 T::now().duration_since(self.first_attempted_at).as_secs()
244 /// A trait defining behavior of an [`Invoice`] payer.
246 /// Returns the payer's node id.
247 fn node_id(&self) -> PublicKey;
249 /// Returns the payer's channels.
250 fn first_hops(&self) -> Vec<ChannelDetails>;
252 /// Sends a payment over the Lightning Network using the given [`Route`].
254 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
255 ) -> Result<PaymentId, PaymentSendFailure>;
257 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
258 fn send_spontaneous_payment(
259 &self, route: &Route, payment_preimage: PaymentPreimage
260 ) -> Result<PaymentId, PaymentSendFailure>;
262 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
263 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
265 /// Signals that no further retries for the given payment will occur.
266 fn abandon_payment(&self, payment_id: PaymentId);
269 /// A trait defining behavior for routing an [`Invoice`] payment.
271 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
273 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
274 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
275 ) -> Result<Route, LightningError>;
276 /// Lets the router know that payment through a specific path has failed.
277 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
278 /// Lets the router know that payment through a specific path was successful.
279 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
280 /// Lets the router know that a payment probe was successful.
281 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
282 /// Lets the router know that a payment probe failed.
283 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
286 /// Strategies available to retry payment path failures for an [`Invoice`].
288 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
290 /// Max number of attempts to retry payment.
292 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
293 /// payments, if this is less than the total number of paths, we will never even retry all of the
296 #[cfg(feature = "std")]
297 /// Time elapsed before abandoning retries for a payment.
302 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
303 match (self, attempts) {
304 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
305 max_retry_count >= &count
307 #[cfg(feature = "std")]
308 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
309 *max_duration >= T::now().duration_since(*first_attempted_at),
314 /// An error that may occur when making a payment.
315 #[derive(Clone, Debug)]
316 pub enum PaymentError {
317 /// An error resulting from the provided [`Invoice`] or payment hash.
318 Invoice(&'static str),
319 /// An error occurring when finding a route.
320 Routing(LightningError),
321 /// An error occurring when sending a payment.
322 Sending(PaymentSendFailure),
325 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
330 /// Creates an invoice payer that retries failed payment paths.
332 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
333 /// `retry` has been exceeded for a given [`Invoice`].
335 payer: P, router: R, logger: L, event_handler: E, retry: Retry
342 payment_cache: Mutex::new(HashMap::new()),
347 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
349 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
350 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
352 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
353 if invoice.amount_milli_satoshis().is_none() {
354 Err(PaymentError::Invoice("amount missing"))
356 self.pay_invoice_using_amount(invoice, None)
360 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
361 /// case a retry is needed.
363 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
364 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
366 pub fn pay_zero_value_invoice(
367 &self, invoice: &Invoice, amount_msats: u64
368 ) -> Result<PaymentId, PaymentError> {
369 if invoice.amount_milli_satoshis().is_some() {
370 Err(PaymentError::Invoice("amount unexpected"))
372 self.pay_invoice_using_amount(invoice, Some(amount_msats))
376 fn pay_invoice_using_amount(
377 &self, invoice: &Invoice, amount_msats: Option<u64>
378 ) -> Result<PaymentId, PaymentError> {
379 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
381 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
382 match self.payment_cache.lock().unwrap().entry(payment_hash) {
383 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
384 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
387 let payment_secret = Some(invoice.payment_secret().clone());
388 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
389 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
390 .with_route_hints(invoice.route_hints());
391 if let Some(features) = invoice.features() {
392 payment_params = payment_params.with_features(features.clone());
394 let route_params = RouteParameters {
396 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
397 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
400 let send_payment = |route: &Route| {
401 self.payer.send_payment(route, payment_hash, &payment_secret)
404 self.pay_internal(&route_params, payment_hash, send_payment)
405 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
408 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
409 /// case a retry is needed.
411 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
412 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
414 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
415 final_cltv_expiry_delta: u32
416 ) -> Result<PaymentId, PaymentError> {
417 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
418 match self.payment_cache.lock().unwrap().entry(payment_hash) {
419 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
420 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
423 let route_params = RouteParameters {
424 payment_params: PaymentParameters::for_keysend(pubkey),
425 final_value_msat: amount_msats,
426 final_cltv_expiry_delta,
429 let send_payment = |route: &Route| {
430 self.payer.send_spontaneous_payment(route, payment_preimage)
432 self.pay_internal(&route_params, payment_hash, send_payment)
433 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
436 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
437 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
438 ) -> Result<PaymentId, PaymentError> {
439 #[cfg(feature = "std")] {
440 if has_expired(params) {
441 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
442 return Err(PaymentError::Invoice("Invoice expired prior to send"));
446 let payer = self.payer.node_id();
447 let first_hops = self.payer.first_hops();
448 let inflight_htlcs = self.create_inflight_map();
449 let route = self.router.find_route(
450 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
452 ).map_err(|e| PaymentError::Routing(e))?;
454 match send_payment(&route) {
456 for path in route.paths {
457 self.process_path_inflight_htlcs(payment_hash, path);
462 PaymentSendFailure::ParameterError(_) => Err(e),
463 PaymentSendFailure::PathParameterError(_) => Err(e),
464 PaymentSendFailure::AllFailedRetrySafe(_) => {
465 let mut payment_cache = self.payment_cache.lock().unwrap();
466 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
467 payment_info.attempts.count += 1;
468 if self.retry.is_retryable_now(&payment_info.attempts) {
469 core::mem::drop(payment_cache);
470 Ok(self.pay_internal(params, payment_hash, send_payment)?)
475 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
476 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
477 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
478 // means that we are still waiting for our channel monitor update to be completed.
479 for (result, path) in results.iter().zip(route.paths.into_iter()) {
481 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
482 self.process_path_inflight_htlcs(payment_hash, path);
488 if let Some(retry_data) = failed_paths_retry {
489 // Some paths were sent, even if we failed to send the full MPP value our
490 // recipient may misbehave and claim the funds, at which point we have to
491 // consider the payment sent, so return `Ok()` here, ignoring any retry
493 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
496 // This may happen if we send a payment and some paths fail, but
497 // only due to a temporary monitor failure or the like, implying
498 // they're really in-flight, but we haven't sent the initial
499 // HTLC-Add messages yet.
504 }.map_err(|e| PaymentError::Sending(e))
507 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
508 // that are pending retry.
509 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
510 self.payment_cache.lock().unwrap().entry(payment_hash)
511 .or_insert_with(|| PaymentInfo::new())
515 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
516 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
517 self.payment_cache.lock().unwrap().entry(payment_hash)
518 .and_modify(|payment_info| {
519 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
520 payment_info.paths.swap_remove(idx);
526 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
527 ) -> Result<(), ()> {
528 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
529 .and_modify(|info| info.attempts.count += 1 )
530 .or_insert_with(|| PaymentInfo {
531 attempts: PaymentAttempts {
533 first_attempted_at: T::now(),
538 if !self.retry.is_retryable_now(&attempts) {
539 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
543 #[cfg(feature = "std")] {
544 if has_expired(params) {
545 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
550 let payer = self.payer.node_id();
551 let first_hops = self.payer.first_hops();
552 let inflight_htlcs = self.create_inflight_map();
554 let route = self.router.find_route(
555 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
560 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
564 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
566 for path in route.unwrap().paths.into_iter() {
567 self.process_path_inflight_htlcs(payment_hash, path);
571 Err(PaymentSendFailure::ParameterError(_)) |
572 Err(PaymentSendFailure::PathParameterError(_)) => {
573 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
576 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
577 self.retry_payment(payment_id, payment_hash, params)
579 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
580 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
581 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
582 // means that we are still waiting for our channel monitor update to complete.
583 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
585 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
586 self.process_path_inflight_htlcs(payment_hash, path);
592 if let Some(retry) = failed_paths_retry {
593 // Always return Ok for the same reason as noted in pay_internal.
594 let _ = self.retry_payment(payment_id, payment_hash, &retry);
601 /// Removes the payment cached by the given payment hash.
603 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
604 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
605 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
606 self.payment_cache.lock().unwrap().remove(payment_hash);
609 /// Given a [`PaymentHash`], this function looks up inflight path attempts in the payment_cache.
610 /// Then, it uses the path information inside the cache to construct a HashMap mapping a channel's
611 /// short channel id and direction to the amount being sent through it.
613 /// This function should be called whenever we need information about currently used up liquidity
615 fn create_inflight_map(&self) -> InFlightHtlcs {
616 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
617 // Make an attempt at finding existing payment information from `payment_cache`. If it
618 // does not exist, it probably is a fresh payment and we can just return an empty
620 for payment_info in self.payment_cache.lock().unwrap().values() {
621 for path in &payment_info.paths {
622 if path.is_empty() { break };
623 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
624 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
625 // the router excludes the payer node. In the following lines, the payer's information is
626 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
627 // in our sliding window of two.
628 let our_node_id: PublicKey = self.payer.node_id();
629 let reversed_hops_with_payer = path.iter().rev().skip(1)
630 .map(|hop| hop.pubkey)
631 .chain(core::iter::once(our_node_id));
632 let mut cumulative_msat = 0;
634 // Taking the reversed vector from above, we zip it with just the reversed hops list to
635 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
636 // the total amount sent.
637 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
638 cumulative_msat += next_hop.fee_msat;
640 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
641 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
642 .or_insert(cumulative_msat);
647 InFlightHtlcs(total_inflight_map)
651 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
652 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
655 #[cfg(feature = "std")]
656 fn has_expired(route_params: &RouteParameters) -> bool {
657 if let Some(expiry_time) = route_params.payment_params.expiry_time {
658 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
662 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
667 fn handle_event(&self, event: &Event) {
669 Event::PaymentPathFailed { payment_hash, path, .. }
670 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
671 | Event::ProbeSuccessful { payment_hash, path, .. }
672 | Event::ProbeFailed { payment_hash, path, .. } => {
673 self.remove_path_inflight_htlcs(*payment_hash, path);
679 Event::PaymentPathFailed {
680 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
682 if let Some(short_channel_id) = short_channel_id {
683 let path = path.iter().collect::<Vec<_>>();
684 self.router.notify_payment_path_failed(&path, *short_channel_id)
687 if payment_id.is_none() {
688 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
689 } else if *payment_failed_permanently {
690 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
691 self.payer.abandon_payment(payment_id.unwrap());
692 } else if retry.is_none() {
693 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
694 self.payer.abandon_payment(payment_id.unwrap());
695 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
696 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
699 self.payer.abandon_payment(payment_id.unwrap());
702 Event::PaymentFailed { payment_hash, .. } => {
703 self.remove_cached_payment(&payment_hash);
705 Event::PaymentPathSuccessful { path, .. } => {
706 let path = path.iter().collect::<Vec<_>>();
707 self.router.notify_payment_path_successful(&path);
709 Event::PaymentSent { payment_hash, .. } => {
710 let mut payment_cache = self.payment_cache.lock().unwrap();
711 let attempts = payment_cache
712 .remove(payment_hash)
713 .map_or(1, |payment_info| payment_info.attempts.count + 1);
714 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
716 Event::ProbeSuccessful { payment_hash, path, .. } => {
717 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
718 let path = path.iter().collect::<Vec<_>>();
719 self.router.notify_payment_probe_successful(&path);
721 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
722 if let Some(short_channel_id) = short_channel_id {
723 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
724 let path = path.iter().collect::<Vec<_>>();
725 self.router.notify_payment_probe_failed(&path, *short_channel_id);
731 // Delegate to the decorated event handler unless the payment is retried.
732 self.event_handler.handle_event(event)
736 /// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
737 /// is traveling in. The direction boolean is determined by checking if the HTLC source's public
738 /// key is less than its destination. See [`InFlightHtlcs::used_liquidity_msat`] for more
740 pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
743 /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
745 pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
746 self.0.get(&(channel_scid, source < target)).map(|v| *v)
750 impl Writeable for InFlightHtlcs {
751 fn write<W: lightning::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
754 impl lightning::util::ser::Readable for InFlightHtlcs {
755 fn read<R: io::Read>(reader: &mut R) -> Result<Self, lightning::ln::msgs::DecodeError> {
756 let infight_map: HashMap<(u64, bool), u64> = lightning::util::ser::Readable::read(reader)?;
757 Ok(Self(infight_map))
764 use crate::{InvoiceBuilder, Currency};
765 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
766 use bitcoin_hashes::sha256::Hash as Sha256;
767 use lightning::ln::PaymentPreimage;
768 use lightning::ln::channelmanager;
769 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
770 use lightning::ln::functional_test_utils::*;
771 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
772 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
773 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
774 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
775 use lightning::util::test_utils::TestLogger;
776 use lightning::util::errors::APIError;
777 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
778 use secp256k1::{SecretKey, PublicKey, Secp256k1};
779 use std::cell::RefCell;
780 use std::collections::VecDeque;
781 use std::ops::DerefMut;
782 use std::time::{SystemTime, Duration};
783 use crate::time_utils::tests::SinceEpoch;
784 use crate::DEFAULT_EXPIRY_TIME;
785 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
787 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
788 let payment_hash = Sha256::hash(&payment_preimage.0);
789 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
791 InvoiceBuilder::new(Currency::Bitcoin)
792 .description("test".into())
793 .payment_hash(payment_hash)
794 .payment_secret(PaymentSecret([0; 32]))
795 .duration_since_epoch(duration_since_epoch())
796 .min_final_cltv_expiry(144)
797 .amount_milli_satoshis(128)
798 .build_signed(|hash| {
799 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
804 fn duration_since_epoch() -> Duration {
805 #[cfg(feature = "std")]
806 let duration_since_epoch =
807 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
808 #[cfg(not(feature = "std"))]
809 let duration_since_epoch = Duration::from_secs(1234567);
813 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
814 let payment_hash = Sha256::hash(&payment_preimage.0);
815 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
817 InvoiceBuilder::new(Currency::Bitcoin)
818 .description("test".into())
819 .payment_hash(payment_hash)
820 .payment_secret(PaymentSecret([0; 32]))
821 .duration_since_epoch(duration_since_epoch())
822 .min_final_cltv_expiry(144)
823 .build_signed(|hash| {
824 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
829 #[cfg(feature = "std")]
830 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
831 let payment_hash = Sha256::hash(&payment_preimage.0);
832 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
833 let duration = duration_since_epoch()
834 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
836 InvoiceBuilder::new(Currency::Bitcoin)
837 .description("test".into())
838 .payment_hash(payment_hash)
839 .payment_secret(PaymentSecret([0; 32]))
840 .duration_since_epoch(duration)
841 .min_final_cltv_expiry(144)
842 .amount_milli_satoshis(128)
843 .build_signed(|hash| {
844 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
849 fn pubkey() -> PublicKey {
850 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
854 fn pays_invoice_on_first_attempt() {
855 let event_handled = core::cell::RefCell::new(false);
856 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
858 let payment_preimage = PaymentPreimage([1; 32]);
859 let invoice = invoice(payment_preimage);
860 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
861 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
863 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
864 let router = TestRouter::new(TestScorer::new());
865 let logger = TestLogger::new();
867 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
869 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
870 assert_eq!(*payer.attempts.borrow(), 1);
872 invoice_payer.handle_event(&Event::PaymentSent {
873 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
875 assert_eq!(*event_handled.borrow(), true);
876 assert_eq!(*payer.attempts.borrow(), 1);
880 fn pays_invoice_on_retry() {
881 let event_handled = core::cell::RefCell::new(false);
882 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
884 let payment_preimage = PaymentPreimage([1; 32]);
885 let invoice = invoice(payment_preimage);
886 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
887 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
889 let payer = TestPayer::new()
890 .expect_send(Amount::ForInvoice(final_value_msat))
891 .expect_send(Amount::OnRetry(final_value_msat / 2));
892 let router = TestRouter::new(TestScorer::new());
893 let logger = TestLogger::new();
895 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
897 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
898 assert_eq!(*payer.attempts.borrow(), 1);
900 let event = Event::PaymentPathFailed {
903 network_update: None,
904 payment_failed_permanently: false,
905 all_paths_failed: false,
906 path: TestRouter::path_for_value(final_value_msat),
907 short_channel_id: None,
908 retry: Some(TestRouter::retry_for_invoice(&invoice)),
910 invoice_payer.handle_event(&event);
911 assert_eq!(*event_handled.borrow(), false);
912 assert_eq!(*payer.attempts.borrow(), 2);
914 invoice_payer.handle_event(&Event::PaymentSent {
915 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
917 assert_eq!(*event_handled.borrow(), true);
918 assert_eq!(*payer.attempts.borrow(), 2);
922 fn pays_invoice_on_partial_failure() {
923 let event_handler = |_: &_| { panic!() };
925 let payment_preimage = PaymentPreimage([1; 32]);
926 let invoice = invoice(payment_preimage);
927 let retry = TestRouter::retry_for_invoice(&invoice);
928 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
930 let payer = TestPayer::new()
931 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
932 .fails_with_partial_failure(retry, OnAttempt(2), None)
933 .expect_send(Amount::ForInvoice(final_value_msat))
934 .expect_send(Amount::OnRetry(final_value_msat / 2))
935 .expect_send(Amount::OnRetry(final_value_msat / 2));
936 let router = TestRouter::new(TestScorer::new());
937 let logger = TestLogger::new();
939 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
941 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
945 fn retries_payment_path_for_unknown_payment() {
946 let event_handled = core::cell::RefCell::new(false);
947 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
949 let payment_preimage = PaymentPreimage([1; 32]);
950 let invoice = invoice(payment_preimage);
951 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
952 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
954 let payer = TestPayer::new()
955 .expect_send(Amount::OnRetry(final_value_msat / 2))
956 .expect_send(Amount::OnRetry(final_value_msat / 2));
957 let router = TestRouter::new(TestScorer::new());
958 let logger = TestLogger::new();
960 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
962 let payment_id = Some(PaymentId([1; 32]));
963 let event = Event::PaymentPathFailed {
966 network_update: None,
967 payment_failed_permanently: false,
968 all_paths_failed: false,
969 path: TestRouter::path_for_value(final_value_msat),
970 short_channel_id: None,
971 retry: Some(TestRouter::retry_for_invoice(&invoice)),
973 invoice_payer.handle_event(&event);
974 assert_eq!(*event_handled.borrow(), false);
975 assert_eq!(*payer.attempts.borrow(), 1);
977 invoice_payer.handle_event(&event);
978 assert_eq!(*event_handled.borrow(), false);
979 assert_eq!(*payer.attempts.borrow(), 2);
981 invoice_payer.handle_event(&Event::PaymentSent {
982 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
984 assert_eq!(*event_handled.borrow(), true);
985 assert_eq!(*payer.attempts.borrow(), 2);
989 fn fails_paying_invoice_after_max_retry_counts() {
990 let event_handled = core::cell::RefCell::new(false);
991 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
993 let payment_preimage = PaymentPreimage([1; 32]);
994 let invoice = invoice(payment_preimage);
995 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
997 let payer = TestPayer::new()
998 .expect_send(Amount::ForInvoice(final_value_msat))
999 .expect_send(Amount::OnRetry(final_value_msat / 2))
1000 .expect_send(Amount::OnRetry(final_value_msat / 2));
1001 let router = TestRouter::new(TestScorer::new());
1002 let logger = TestLogger::new();
1004 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1006 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1007 assert_eq!(*payer.attempts.borrow(), 1);
1009 let event = Event::PaymentPathFailed {
1011 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1012 network_update: None,
1013 payment_failed_permanently: false,
1014 all_paths_failed: true,
1015 path: TestRouter::path_for_value(final_value_msat),
1016 short_channel_id: None,
1017 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1019 invoice_payer.handle_event(&event);
1020 assert_eq!(*event_handled.borrow(), false);
1021 assert_eq!(*payer.attempts.borrow(), 2);
1023 let event = Event::PaymentPathFailed {
1025 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1026 network_update: None,
1027 payment_failed_permanently: false,
1028 all_paths_failed: false,
1029 path: TestRouter::path_for_value(final_value_msat / 2),
1030 short_channel_id: None,
1031 retry: Some(RouteParameters {
1032 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1035 invoice_payer.handle_event(&event);
1036 assert_eq!(*event_handled.borrow(), false);
1037 assert_eq!(*payer.attempts.borrow(), 3);
1039 invoice_payer.handle_event(&event);
1040 assert_eq!(*event_handled.borrow(), true);
1041 assert_eq!(*payer.attempts.borrow(), 3);
1044 #[cfg(feature = "std")]
1046 fn fails_paying_invoice_after_max_retry_timeout() {
1047 let event_handled = core::cell::RefCell::new(false);
1048 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1050 let payment_preimage = PaymentPreimage([1; 32]);
1051 let invoice = invoice(payment_preimage);
1052 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1054 let payer = TestPayer::new()
1055 .expect_send(Amount::ForInvoice(final_value_msat))
1056 .expect_send(Amount::OnRetry(final_value_msat / 2));
1058 let router = TestRouter::new(TestScorer::new());
1059 let logger = TestLogger::new();
1060 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1063 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1065 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1066 assert_eq!(*payer.attempts.borrow(), 1);
1068 let event = Event::PaymentPathFailed {
1070 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1071 network_update: None,
1072 payment_failed_permanently: false,
1073 all_paths_failed: true,
1074 path: TestRouter::path_for_value(final_value_msat),
1075 short_channel_id: None,
1076 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1078 invoice_payer.handle_event(&event);
1079 assert_eq!(*event_handled.borrow(), false);
1080 assert_eq!(*payer.attempts.borrow(), 2);
1082 SinceEpoch::advance(Duration::from_secs(121));
1084 invoice_payer.handle_event(&event);
1085 assert_eq!(*event_handled.borrow(), true);
1086 assert_eq!(*payer.attempts.borrow(), 2);
1090 fn fails_paying_invoice_with_missing_retry_params() {
1091 let event_handled = core::cell::RefCell::new(false);
1092 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1094 let payment_preimage = PaymentPreimage([1; 32]);
1095 let invoice = invoice(payment_preimage);
1096 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1098 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1099 let router = TestRouter::new(TestScorer::new());
1100 let logger = TestLogger::new();
1102 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1104 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1105 assert_eq!(*payer.attempts.borrow(), 1);
1107 let event = Event::PaymentPathFailed {
1109 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1110 network_update: None,
1111 payment_failed_permanently: false,
1112 all_paths_failed: false,
1114 short_channel_id: None,
1117 invoice_payer.handle_event(&event);
1118 assert_eq!(*event_handled.borrow(), true);
1119 assert_eq!(*payer.attempts.borrow(), 1);
1122 // Expiration is checked only in an std environment
1123 #[cfg(feature = "std")]
1125 fn fails_paying_invoice_after_expiration() {
1126 let event_handled = core::cell::RefCell::new(false);
1127 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1129 let payer = TestPayer::new();
1130 let router = TestRouter::new(TestScorer::new());
1131 let logger = TestLogger::new();
1133 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1135 let payment_preimage = PaymentPreimage([1; 32]);
1136 let invoice = expired_invoice(payment_preimage);
1137 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1138 assert_eq!(msg, "Invoice expired prior to send");
1139 } else { panic!("Expected Invoice Error"); }
1142 // Expiration is checked only in an std environment
1143 #[cfg(feature = "std")]
1145 fn fails_retrying_invoice_after_expiration() {
1146 let event_handled = core::cell::RefCell::new(false);
1147 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1149 let payment_preimage = PaymentPreimage([1; 32]);
1150 let invoice = invoice(payment_preimage);
1151 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1153 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1154 let router = TestRouter::new(TestScorer::new());
1155 let logger = TestLogger::new();
1157 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1159 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1160 assert_eq!(*payer.attempts.borrow(), 1);
1162 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1163 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1164 .checked_sub(Duration::from_secs(2)).unwrap()
1165 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1166 let event = Event::PaymentPathFailed {
1168 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1169 network_update: None,
1170 payment_failed_permanently: false,
1171 all_paths_failed: false,
1173 short_channel_id: None,
1174 retry: Some(retry_data),
1176 invoice_payer.handle_event(&event);
1177 assert_eq!(*event_handled.borrow(), true);
1178 assert_eq!(*payer.attempts.borrow(), 1);
1182 fn fails_paying_invoice_after_retry_error() {
1183 let event_handled = core::cell::RefCell::new(false);
1184 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1186 let payment_preimage = PaymentPreimage([1; 32]);
1187 let invoice = invoice(payment_preimage);
1188 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1190 let payer = TestPayer::new()
1191 .fails_on_attempt(2)
1192 .expect_send(Amount::ForInvoice(final_value_msat))
1193 .expect_send(Amount::OnRetry(final_value_msat / 2));
1194 let router = TestRouter::new(TestScorer::new());
1195 let logger = TestLogger::new();
1197 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1199 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1200 assert_eq!(*payer.attempts.borrow(), 1);
1202 let event = Event::PaymentPathFailed {
1204 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1205 network_update: None,
1206 payment_failed_permanently: false,
1207 all_paths_failed: false,
1208 path: TestRouter::path_for_value(final_value_msat / 2),
1209 short_channel_id: None,
1210 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1212 invoice_payer.handle_event(&event);
1213 assert_eq!(*event_handled.borrow(), true);
1214 assert_eq!(*payer.attempts.borrow(), 2);
1218 fn fails_paying_invoice_after_rejected_by_payee() {
1219 let event_handled = core::cell::RefCell::new(false);
1220 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1222 let payment_preimage = PaymentPreimage([1; 32]);
1223 let invoice = invoice(payment_preimage);
1224 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1226 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1227 let router = TestRouter::new(TestScorer::new());
1228 let logger = TestLogger::new();
1230 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1232 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1233 assert_eq!(*payer.attempts.borrow(), 1);
1235 let event = Event::PaymentPathFailed {
1237 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1238 network_update: None,
1239 payment_failed_permanently: true,
1240 all_paths_failed: false,
1242 short_channel_id: None,
1243 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1245 invoice_payer.handle_event(&event);
1246 assert_eq!(*event_handled.borrow(), true);
1247 assert_eq!(*payer.attempts.borrow(), 1);
1251 fn fails_repaying_invoice_with_pending_payment() {
1252 let event_handled = core::cell::RefCell::new(false);
1253 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1255 let payment_preimage = PaymentPreimage([1; 32]);
1256 let invoice = invoice(payment_preimage);
1257 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1259 let payer = TestPayer::new()
1260 .expect_send(Amount::ForInvoice(final_value_msat))
1261 .expect_send(Amount::ForInvoice(final_value_msat));
1262 let router = TestRouter::new(TestScorer::new());
1263 let logger = TestLogger::new();
1265 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1267 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1269 // Cannot repay an invoice pending payment.
1270 match invoice_payer.pay_invoice(&invoice) {
1271 Err(PaymentError::Invoice("payment pending")) => {},
1272 Err(_) => panic!("unexpected error"),
1273 Ok(_) => panic!("expected invoice error"),
1276 // Can repay an invoice once cleared from cache.
1277 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1278 invoice_payer.remove_cached_payment(&payment_hash);
1279 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1281 // Cannot retry paying an invoice if cleared from cache.
1282 invoice_payer.remove_cached_payment(&payment_hash);
1283 let event = Event::PaymentPathFailed {
1286 network_update: None,
1287 payment_failed_permanently: false,
1288 all_paths_failed: false,
1290 short_channel_id: None,
1291 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1293 invoice_payer.handle_event(&event);
1294 assert_eq!(*event_handled.borrow(), true);
1298 fn fails_paying_invoice_with_routing_errors() {
1299 let payer = TestPayer::new();
1300 let router = FailingRouter {};
1301 let logger = TestLogger::new();
1303 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1305 let payment_preimage = PaymentPreimage([1; 32]);
1306 let invoice = invoice(payment_preimage);
1307 match invoice_payer.pay_invoice(&invoice) {
1308 Err(PaymentError::Routing(_)) => {},
1309 Err(_) => panic!("unexpected error"),
1310 Ok(_) => panic!("expected routing error"),
1315 fn fails_paying_invoice_with_sending_errors() {
1316 let payment_preimage = PaymentPreimage([1; 32]);
1317 let invoice = invoice(payment_preimage);
1318 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1320 let payer = TestPayer::new()
1321 .fails_on_attempt(1)
1322 .expect_send(Amount::ForInvoice(final_value_msat));
1323 let router = TestRouter::new(TestScorer::new());
1324 let logger = TestLogger::new();
1326 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1328 match invoice_payer.pay_invoice(&invoice) {
1329 Err(PaymentError::Sending(_)) => {},
1330 Err(_) => panic!("unexpected error"),
1331 Ok(_) => panic!("expected sending error"),
1336 fn pays_zero_value_invoice_using_amount() {
1337 let event_handled = core::cell::RefCell::new(false);
1338 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1340 let payment_preimage = PaymentPreimage([1; 32]);
1341 let invoice = zero_value_invoice(payment_preimage);
1342 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1343 let final_value_msat = 100;
1345 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1346 let router = TestRouter::new(TestScorer::new());
1347 let logger = TestLogger::new();
1349 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1352 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1353 assert_eq!(*payer.attempts.borrow(), 1);
1355 invoice_payer.handle_event(&Event::PaymentSent {
1356 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1358 assert_eq!(*event_handled.borrow(), true);
1359 assert_eq!(*payer.attempts.borrow(), 1);
1363 fn fails_paying_zero_value_invoice_with_amount() {
1364 let event_handled = core::cell::RefCell::new(false);
1365 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1367 let payer = TestPayer::new();
1368 let router = TestRouter::new(TestScorer::new());
1369 let logger = TestLogger::new();
1371 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1373 let payment_preimage = PaymentPreimage([1; 32]);
1374 let invoice = invoice(payment_preimage);
1376 // Cannot repay an invoice pending payment.
1377 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1378 Err(PaymentError::Invoice("amount unexpected")) => {},
1379 Err(_) => panic!("unexpected error"),
1380 Ok(_) => panic!("expected invoice error"),
1385 fn pays_pubkey_with_amount() {
1386 let event_handled = core::cell::RefCell::new(false);
1387 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1389 let pubkey = pubkey();
1390 let payment_preimage = PaymentPreimage([1; 32]);
1391 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1392 let final_value_msat = 100;
1393 let final_cltv_expiry_delta = 42;
1395 let payer = TestPayer::new()
1396 .expect_send(Amount::Spontaneous(final_value_msat))
1397 .expect_send(Amount::OnRetry(final_value_msat));
1398 let router = TestRouter::new(TestScorer::new());
1399 let logger = TestLogger::new();
1401 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1403 let payment_id = Some(invoice_payer.pay_pubkey(
1404 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1406 assert_eq!(*payer.attempts.borrow(), 1);
1408 let retry = RouteParameters {
1409 payment_params: PaymentParameters::for_keysend(pubkey),
1411 final_cltv_expiry_delta,
1413 let event = Event::PaymentPathFailed {
1416 network_update: None,
1417 payment_failed_permanently: false,
1418 all_paths_failed: false,
1420 short_channel_id: None,
1423 invoice_payer.handle_event(&event);
1424 assert_eq!(*event_handled.borrow(), false);
1425 assert_eq!(*payer.attempts.borrow(), 2);
1427 invoice_payer.handle_event(&Event::PaymentSent {
1428 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1430 assert_eq!(*event_handled.borrow(), true);
1431 assert_eq!(*payer.attempts.borrow(), 2);
1435 fn scores_failed_channel() {
1436 let event_handled = core::cell::RefCell::new(false);
1437 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1439 let payment_preimage = PaymentPreimage([1; 32]);
1440 let invoice = invoice(payment_preimage);
1441 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1442 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1443 let path = TestRouter::path_for_value(final_value_msat);
1444 let short_channel_id = Some(path[0].short_channel_id);
1446 // Expect that scorer is given short_channel_id upon handling the event.
1447 let payer = TestPayer::new()
1448 .expect_send(Amount::ForInvoice(final_value_msat))
1449 .expect_send(Amount::OnRetry(final_value_msat / 2));
1450 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1451 path: path.clone(), short_channel_id: path[0].short_channel_id,
1453 let router = TestRouter::new(scorer);
1454 let logger = TestLogger::new();
1456 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1458 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1459 let event = Event::PaymentPathFailed {
1462 network_update: None,
1463 payment_failed_permanently: false,
1464 all_paths_failed: false,
1467 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1469 invoice_payer.handle_event(&event);
1473 fn scores_successful_channels() {
1474 let event_handled = core::cell::RefCell::new(false);
1475 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1477 let payment_preimage = PaymentPreimage([1; 32]);
1478 let invoice = invoice(payment_preimage);
1479 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1480 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1481 let route = TestRouter::route_for_value(final_value_msat);
1483 // Expect that scorer is given short_channel_id upon handling the event.
1484 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1485 let scorer = TestScorer::new()
1486 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1487 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1488 let router = TestRouter::new(scorer);
1489 let logger = TestLogger::new();
1491 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1493 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1494 let event = Event::PaymentPathSuccessful {
1495 payment_id, payment_hash, path: route.paths[0].clone()
1497 invoice_payer.handle_event(&event);
1498 let event = Event::PaymentPathSuccessful {
1499 payment_id, payment_hash, path: route.paths[1].clone()
1501 invoice_payer.handle_event(&event);
1505 fn generates_correct_inflight_map_data() {
1506 let event_handled = core::cell::RefCell::new(false);
1507 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1509 let payment_preimage = PaymentPreimage([1; 32]);
1510 let invoice = invoice(payment_preimage);
1511 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1512 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1514 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1515 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1516 let route = TestRouter::route_for_value(final_value_msat);
1517 let router = TestRouter::new(TestScorer::new());
1518 let logger = TestLogger::new();
1520 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1522 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1524 let inflight_map = invoice_payer.create_inflight_map();
1526 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1527 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1528 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1530 // Second path check
1531 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1532 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1534 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1535 payment_id, payment_hash, path: route.paths[0].clone()
1538 let inflight_map = invoice_payer.create_inflight_map();
1540 assert_eq!(inflight_map.0.get(&(0, false)), None);
1541 assert_eq!(inflight_map.0.get(&(1, true)), None);
1542 assert_eq!(inflight_map.0.get(&(2, false)), None);
1544 // Second path should still be inflight
1545 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1546 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1550 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1551 // First, let's just send a payment through, but only make sure one of the path completes
1552 let event_handled = core::cell::RefCell::new(false);
1553 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1555 let payment_preimage = PaymentPreimage([1; 32]);
1556 let payment_invoice = invoice(payment_preimage);
1557 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1558 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1560 let payer = TestPayer::new()
1561 .expect_send(Amount::ForInvoice(final_value_msat))
1562 .expect_send(Amount::ForInvoice(final_value_msat));
1563 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1564 let route = TestRouter::route_for_value(final_value_msat);
1565 let scorer = TestScorer::new()
1566 // 1st invoice, 1st path
1567 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1568 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1569 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1570 // 1st invoice, 2nd path
1571 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1572 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1573 // 2nd invoice, 1st path
1574 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1575 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1576 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1577 // 2nd invoice, 2nd path
1578 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1579 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1580 let router = TestRouter::new(scorer);
1581 let logger = TestLogger::new();
1583 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1585 // Succeed 1st path, leave 2nd path inflight
1586 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1587 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1588 payment_id, payment_hash, path: route.paths[0].clone()
1591 // Let's pay a second invoice that will be using the same path. This should trigger the
1592 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1593 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1594 // have 64 msats inflight for paths considering the channel with scid of 1.
1595 let payment_preimage_2 = PaymentPreimage([2; 32]);
1596 let payment_invoice_2 = invoice(payment_preimage_2);
1597 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1601 fn considers_inflight_htlcs_between_retries() {
1602 // First, let's just send a payment through, but only make sure one of the path completes
1603 let event_handled = core::cell::RefCell::new(false);
1604 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1606 let payment_preimage = PaymentPreimage([1; 32]);
1607 let payment_invoice = invoice(payment_preimage);
1608 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1609 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1611 let payer = TestPayer::new()
1612 .expect_send(Amount::ForInvoice(final_value_msat))
1613 .expect_send(Amount::OnRetry(final_value_msat / 2))
1614 .expect_send(Amount::OnRetry(final_value_msat / 4));
1615 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1616 let scorer = TestScorer::new()
1617 // 1st invoice, 1st path
1618 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1619 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1620 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1621 // 1st invoice, 2nd path
1622 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1623 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1624 // Retry 1, 1st path
1625 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1626 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1627 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1628 // Retry 1, 2nd path
1629 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1630 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1631 // Retry 2, 1st path
1632 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1633 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1634 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1635 // Retry 2, 2nd path
1636 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1637 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1638 let router = TestRouter::new(scorer);
1639 let logger = TestLogger::new();
1641 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1643 // Fail 1st path, leave 2nd path inflight
1644 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1645 invoice_payer.handle_event(&Event::PaymentPathFailed {
1648 network_update: None,
1649 payment_failed_permanently: false,
1650 all_paths_failed: false,
1651 path: TestRouter::path_for_value(final_value_msat),
1652 short_channel_id: None,
1653 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1656 // Fails again the 1st path of our retry
1657 invoice_payer.handle_event(&Event::PaymentPathFailed {
1660 network_update: None,
1661 payment_failed_permanently: false,
1662 all_paths_failed: false,
1663 path: TestRouter::path_for_value(final_value_msat / 2),
1664 short_channel_id: None,
1665 retry: Some(RouteParameters {
1666 final_value_msat: final_value_msat / 4,
1667 ..TestRouter::retry_for_invoice(&payment_invoice)
1673 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1674 let event_handled = core::cell::RefCell::new(false);
1675 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1677 let payment_preimage = PaymentPreimage([1; 32]);
1678 let invoice_to_pay = invoice(payment_preimage);
1679 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1681 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1682 let payer = TestPayer::new()
1683 .fails_with_partial_failure(
1684 retry.clone(), OnAttempt(1),
1686 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1688 .expect_send(Amount::ForInvoice(final_value_msat));
1690 let router = TestRouter::new(TestScorer::new());
1691 let logger = TestLogger::new();
1693 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1695 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1696 let inflight_map = invoice_payer.create_inflight_map();
1698 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1699 // inflight map because retries are disabled.
1700 assert_eq!(inflight_map.0.len(), 2);
1704 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1705 let event_handled = core::cell::RefCell::new(false);
1706 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1708 let payment_preimage = PaymentPreimage([1; 32]);
1709 let invoice_to_pay = invoice(payment_preimage);
1710 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1712 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1713 let payer = TestPayer::new()
1714 .fails_with_partial_failure(
1715 retry.clone(), OnAttempt(1),
1717 Ok(()), Err(MonitorUpdateInProgress)
1719 .expect_send(Amount::ForInvoice(final_value_msat));
1721 let router = TestRouter::new(TestScorer::new());
1722 let logger = TestLogger::new();
1724 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1726 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1727 let inflight_map = invoice_payer.create_inflight_map();
1729 // All paths successful, hence we check of the existence of all 5 hops.
1730 assert_eq!(inflight_map.0.len(), 5);
1734 scorer: RefCell<TestScorer>,
1738 fn new(scorer: TestScorer) -> Self {
1739 TestRouter { scorer: RefCell::new(scorer) }
1742 fn route_for_value(final_value_msat: u64) -> Route {
1747 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1748 channel_features: ChannelFeatures::empty(),
1749 node_features: NodeFeatures::empty(),
1750 short_channel_id: 0,
1752 cltv_expiry_delta: 0
1755 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1756 channel_features: ChannelFeatures::empty(),
1757 node_features: NodeFeatures::empty(),
1758 short_channel_id: 1,
1760 cltv_expiry_delta: 0
1763 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1764 channel_features: ChannelFeatures::empty(),
1765 node_features: NodeFeatures::empty(),
1766 short_channel_id: 2,
1767 fee_msat: final_value_msat / 2,
1768 cltv_expiry_delta: 0
1773 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1774 channel_features: ChannelFeatures::empty(),
1775 node_features: NodeFeatures::empty(),
1776 short_channel_id: 3,
1778 cltv_expiry_delta: 144
1781 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1782 channel_features: ChannelFeatures::empty(),
1783 node_features: NodeFeatures::empty(),
1784 short_channel_id: 4,
1785 fee_msat: final_value_msat / 2,
1786 cltv_expiry_delta: 144
1790 payment_params: None,
1794 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1795 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1798 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1799 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1800 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1801 .with_route_hints(invoice.route_hints());
1802 if let Some(features) = invoice.features() {
1803 payment_params = payment_params.with_features(features.clone());
1805 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1809 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1814 impl Router for TestRouter {
1816 &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1817 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1818 ) -> Result<Route, LightningError> {
1819 // Simulate calling the Scorer just as you would in find_route
1820 let route = Self::route_for_value(route_params.final_value_msat);
1821 let mut locked_scorer = self.scorer.lock();
1822 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1823 for path in route.paths {
1824 let mut aggregate_msat = 0u64;
1825 for (idx, hop) in path.iter().rev().enumerate() {
1826 aggregate_msat += hop.fee_msat;
1827 let usage = ChannelUsage {
1828 amount_msat: aggregate_msat,
1829 inflight_htlc_msat: 0,
1830 effective_capacity: EffectiveCapacity::Unknown,
1833 // Since the path is reversed, the last element in our iteration is the first
1835 if idx == path.len() - 1 {
1836 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1838 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1844 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1848 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1849 self.scorer.lock().payment_path_failed(path, short_channel_id);
1852 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1853 self.scorer.lock().payment_path_successful(path);
1856 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1857 self.scorer.lock().probe_successful(path);
1860 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1861 self.scorer.lock().probe_failed(path, short_channel_id);
1865 struct FailingRouter;
1867 impl Router for FailingRouter {
1869 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1870 _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
1871 ) -> Result<Route, LightningError> {
1872 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1875 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1877 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1879 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1881 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1885 event_expectations: Option<VecDeque<TestResult>>,
1886 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1891 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1892 PaymentSuccess { path: Vec<RouteHop> },
1898 event_expectations: None,
1899 scorer_expectations: RefCell::new(None),
1903 fn expect(mut self, expectation: TestResult) -> Self {
1904 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1908 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1909 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1915 impl lightning::util::ser::Writeable for TestScorer {
1916 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1919 impl Score for TestScorer {
1920 fn channel_penalty_msat(
1921 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1923 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1924 match scorer_expectations.pop_front() {
1925 Some(expectation) => {
1926 assert_eq!(expectation.amount_msat, usage.amount_msat);
1927 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1935 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1936 if let Some(expectations) = &mut self.event_expectations {
1937 match expectations.pop_front() {
1938 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1939 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1940 assert_eq!(actual_short_channel_id, short_channel_id);
1942 Some(TestResult::PaymentSuccess { path }) => {
1943 panic!("Unexpected successful payment path: {:?}", path)
1945 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1950 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1951 if let Some(expectations) = &mut self.event_expectations {
1952 match expectations.pop_front() {
1953 Some(TestResult::PaymentFailure { path, .. }) => {
1954 panic!("Unexpected payment path failure: {:?}", path)
1956 Some(TestResult::PaymentSuccess { path }) => {
1957 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1959 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1964 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1965 if let Some(expectations) = &mut self.event_expectations {
1966 match expectations.pop_front() {
1967 Some(TestResult::PaymentFailure { path, .. }) => {
1968 panic!("Unexpected failed payment path: {:?}", path)
1970 Some(TestResult::PaymentSuccess { path }) => {
1971 panic!("Unexpected successful payment path: {:?}", path)
1973 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1977 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1978 if let Some(expectations) = &mut self.event_expectations {
1979 match expectations.pop_front() {
1980 Some(TestResult::PaymentFailure { path, .. }) => {
1981 panic!("Unexpected payment path failure: {:?}", path)
1983 Some(TestResult::PaymentSuccess { path }) => {
1984 panic!("Unexpected successful payment path: {:?}", path)
1986 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1992 impl Drop for TestScorer {
1993 fn drop(&mut self) {
1994 if std::thread::panicking() {
1998 if let Some(event_expectations) = &self.event_expectations {
1999 if !event_expectations.is_empty() {
2000 panic!("Unsatisfied event expectations: {:?}", event_expectations);
2004 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
2005 if !scorer_expectations.is_empty() {
2006 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
2013 expectations: core::cell::RefCell<VecDeque<Amount>>,
2014 attempts: core::cell::RefCell<usize>,
2015 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2018 #[derive(Clone, Debug, PartialEq, Eq)]
2025 struct OnAttempt(usize);
2030 expectations: core::cell::RefCell::new(VecDeque::new()),
2031 attempts: core::cell::RefCell::new(0),
2032 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2036 fn expect_send(self, value_msat: Amount) -> Self {
2037 self.expectations.borrow_mut().push_back(value_msat);
2041 fn fails_on_attempt(self, attempt: usize) -> Self {
2042 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2043 self.fails_with(failure, OnAttempt(attempt))
2046 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2047 self.fails_with(PaymentSendFailure::PartialFailure {
2048 results: results.unwrap_or(vec![]),
2049 failed_paths_retry: Some(retry),
2050 payment_id: PaymentId([1; 32]),
2054 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2055 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2059 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2060 let mut attempts = self.attempts.borrow_mut();
2063 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2064 Some(failure) => Err(failure),
2065 None => Ok(PaymentId([1; 32])),
2069 fn check_value_msats(&self, actual_value_msats: Amount) {
2070 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2071 if let Some(expected_value_msats) = expected_value_msats {
2072 assert_eq!(actual_value_msats, expected_value_msats);
2074 panic!("Unexpected amount: {:?}", actual_value_msats);
2079 impl Drop for TestPayer {
2080 fn drop(&mut self) {
2081 if std::thread::panicking() {
2085 if !self.expectations.borrow().is_empty() {
2086 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2091 impl Payer for TestPayer {
2092 fn node_id(&self) -> PublicKey {
2093 let secp_ctx = Secp256k1::new();
2094 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2097 fn first_hops(&self) -> Vec<ChannelDetails> {
2102 &self, route: &Route, _payment_hash: PaymentHash,
2103 _payment_secret: &Option<PaymentSecret>
2104 ) -> Result<PaymentId, PaymentSendFailure> {
2105 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2106 self.check_attempts()
2109 fn send_spontaneous_payment(
2110 &self, route: &Route, _payment_preimage: PaymentPreimage,
2111 ) -> Result<PaymentId, PaymentSendFailure> {
2112 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2113 self.check_attempts()
2117 &self, route: &Route, _payment_id: PaymentId
2118 ) -> Result<(), PaymentSendFailure> {
2119 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2120 self.check_attempts().map(|_| ())
2123 fn abandon_payment(&self, _payment_id: PaymentId) { }
2126 // *** Full Featured Functional Tests with a Real ChannelManager ***
2127 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2129 impl Router for ManualRouter {
2131 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
2132 _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs
2133 ) -> Result<Route, LightningError> {
2134 self.0.borrow_mut().pop_front().unwrap()
2137 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2139 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2141 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2143 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2146 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2147 self.0.borrow_mut().push_back(result);
2150 impl Drop for ManualRouter {
2151 fn drop(&mut self) {
2152 if std::thread::panicking() {
2155 assert!(self.0.borrow_mut().is_empty());
2160 fn retry_multi_path_single_failed_payment() {
2161 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2162 let chanmon_cfgs = create_chanmon_cfgs(2);
2163 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2164 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2165 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2167 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2168 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2169 let chans = nodes[0].node.list_usable_channels();
2170 let mut route = Route {
2173 pubkey: nodes[1].node.get_our_node_id(),
2174 node_features: channelmanager::provided_node_features(),
2175 short_channel_id: chans[0].short_channel_id.unwrap(),
2176 channel_features: channelmanager::provided_channel_features(),
2178 cltv_expiry_delta: 100,
2181 pubkey: nodes[1].node.get_our_node_id(),
2182 node_features: channelmanager::provided_node_features(),
2183 short_channel_id: chans[1].short_channel_id.unwrap(),
2184 channel_features: channelmanager::provided_channel_features(),
2185 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2186 cltv_expiry_delta: 100,
2189 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2191 let router = ManualRouter(RefCell::new(VecDeque::new()));
2192 router.expect_find_route(Ok(route.clone()));
2193 // On retry, split the payment across both channels.
2194 route.paths[0][0].fee_msat = 50_000_001;
2195 route.paths[1][0].fee_msat = 50_000_000;
2196 router.expect_find_route(Ok(route.clone()));
2198 let event_handler = |_: &_| { panic!(); };
2199 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2201 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2202 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2203 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2205 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2206 assert_eq!(htlc_msgs.len(), 2);
2207 check_added_monitors!(nodes[0], 2);
2211 fn immediate_retry_on_failure() {
2212 // Tests that we can/will retry immediately after a failure
2213 let chanmon_cfgs = create_chanmon_cfgs(2);
2214 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2215 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2216 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2218 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2219 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2220 let chans = nodes[0].node.list_usable_channels();
2221 let mut route = Route {
2224 pubkey: nodes[1].node.get_our_node_id(),
2225 node_features: channelmanager::provided_node_features(),
2226 short_channel_id: chans[0].short_channel_id.unwrap(),
2227 channel_features: channelmanager::provided_channel_features(),
2228 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2229 cltv_expiry_delta: 100,
2232 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2234 let router = ManualRouter(RefCell::new(VecDeque::new()));
2235 router.expect_find_route(Ok(route.clone()));
2236 // On retry, split the payment across both channels.
2237 route.paths.push(route.paths[0].clone());
2238 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2239 route.paths[0][0].fee_msat = 50_000_000;
2240 route.paths[1][0].fee_msat = 50_000_001;
2241 router.expect_find_route(Ok(route.clone()));
2243 let event_handler = |_: &_| { panic!(); };
2244 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2246 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2247 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2248 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2250 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2251 assert_eq!(htlc_msgs.len(), 2);
2252 check_added_monitors!(nodes[0], 2);
2256 fn no_extra_retries_on_back_to_back_fail() {
2257 // In a previous release, we had a race where we may exceed the payment retry count if we
2258 // get two failures in a row with the second having `all_paths_failed` set.
2259 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2260 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2261 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2262 // pending which we will see later. Thus, when we previously removed the retry tracking map
2263 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2264 // retry entry even though more events for the same payment were still pending. This led to
2265 // us retrying a payment again even though we'd already given up on it.
2267 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2268 // is used to remove the payment retry counter entries instead. This tests for the specific
2269 // excess-retry case while also testing `PaymentFailed` generation.
2271 let chanmon_cfgs = create_chanmon_cfgs(3);
2272 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2273 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2274 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2276 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;
2277 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;
2279 let mut route = Route {
2282 pubkey: nodes[1].node.get_our_node_id(),
2283 node_features: channelmanager::provided_node_features(),
2284 short_channel_id: chan_1_scid,
2285 channel_features: channelmanager::provided_channel_features(),
2287 cltv_expiry_delta: 100,
2289 pubkey: nodes[2].node.get_our_node_id(),
2290 node_features: channelmanager::provided_node_features(),
2291 short_channel_id: chan_2_scid,
2292 channel_features: channelmanager::provided_channel_features(),
2293 fee_msat: 100_000_000,
2294 cltv_expiry_delta: 100,
2297 pubkey: nodes[1].node.get_our_node_id(),
2298 node_features: channelmanager::provided_node_features(),
2299 short_channel_id: chan_1_scid,
2300 channel_features: channelmanager::provided_channel_features(),
2302 cltv_expiry_delta: 100,
2304 pubkey: nodes[2].node.get_our_node_id(),
2305 node_features: channelmanager::provided_node_features(),
2306 short_channel_id: chan_2_scid,
2307 channel_features: channelmanager::provided_channel_features(),
2308 fee_msat: 100_000_000,
2309 cltv_expiry_delta: 100,
2312 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2314 let router = ManualRouter(RefCell::new(VecDeque::new()));
2315 router.expect_find_route(Ok(route.clone()));
2316 // On retry, we'll only be asked for one path
2317 route.paths.remove(1);
2318 router.expect_find_route(Ok(route.clone()));
2320 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2321 let event_handler = |event: &Event| {
2322 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2323 event_checker(event);
2325 let invoice_payer = InvoicePayer::new(nodes[0].node, router, 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, nodes[1].logger, Currency::Bitcoin,
2329 Some(100_010_000), "Invoice".to_string(), 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());