1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, 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,
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::*;
143 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
144 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
145 use lightning::ln::msgs::LightningError;
146 use lightning::routing::gossip::NodeId;
147 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters};
148 use lightning::util::errors::APIError;
149 use lightning::util::events::{Event, EventHandler};
150 use lightning::util::logger::Logger;
151 use crate::time_utils::Time;
152 use crate::sync::Mutex;
154 use secp256k1::PublicKey;
157 use core::fmt::{Debug, Display, Formatter};
158 use core::ops::Deref;
159 use core::time::Duration;
160 #[cfg(feature = "std")]
161 use std::time::SystemTime;
163 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
165 /// See [module-level documentation] for details.
167 /// [module-level documentation]: crate::payment
168 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
170 #[cfg(not(feature = "no-std"))]
171 type ConfiguredTime = std::time::Instant;
172 #[cfg(feature = "no-std")]
173 use crate::time_utils;
174 #[cfg(feature = "no-std")]
175 type ConfiguredTime = time_utils::Eternity;
177 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
178 pub struct InvoicePayerUsingTime<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time>
187 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
188 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
192 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
193 /// currently being made, or have outstanding paths that need retrying.
194 struct PaymentInfo<T: Time> {
195 attempts: PaymentAttempts<T>,
196 paths: Vec<Vec<RouteHop>>,
199 impl<T: Time> PaymentInfo<T> {
202 attempts: PaymentAttempts::new(),
208 /// Storing minimal payment attempts information required for determining if a outbound payment can
210 #[derive(Clone, Copy)]
211 struct PaymentAttempts<T: Time> {
212 /// This count will be incremented only after the result of the attempt is known. When it's 0,
213 /// it means the result of the first attempt is now known yet.
215 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
216 first_attempted_at: T
219 impl<T: Time> PaymentAttempts<T> {
223 first_attempted_at: T::now()
228 impl<T: Time> Display for PaymentAttempts<T> {
229 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
230 #[cfg(feature = "no-std")]
231 return write!( f, "attempts: {}", self.count);
232 #[cfg(not(feature = "no-std"))]
235 "attempts: {}, duration: {}s",
237 T::now().duration_since(self.first_attempted_at).as_secs()
242 /// A trait defining behavior of an [`Invoice`] payer.
244 /// Returns the payer's node id.
245 fn node_id(&self) -> PublicKey;
247 /// Returns the payer's channels.
248 fn first_hops(&self) -> Vec<ChannelDetails>;
250 /// Sends a payment over the Lightning Network using the given [`Route`].
252 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
253 ) -> Result<PaymentId, PaymentSendFailure>;
255 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
256 fn send_spontaneous_payment(
257 &self, route: &Route, payment_preimage: PaymentPreimage
258 ) -> Result<PaymentId, PaymentSendFailure>;
260 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
261 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
263 /// Signals that no further retries for the given payment will occur.
264 fn abandon_payment(&self, payment_id: PaymentId);
267 /// A trait defining behavior for routing an [`Invoice`] payment.
269 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
271 &self, payer: &PublicKey, route_params: &RouteParameters,
272 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
273 ) -> Result<Route, LightningError>;
274 /// Lets the router know that payment through a specific path has failed.
275 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
276 /// Lets the router know that payment through a specific path was successful.
277 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
278 /// Lets the router know that a payment probe was successful.
279 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
280 /// Lets the router know that a payment probe failed.
281 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
284 /// Strategies available to retry payment path failures for an [`Invoice`].
286 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
288 /// Max number of attempts to retry payment.
290 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
291 /// payments, if this is less than the total number of paths, we will never even retry all of the
294 #[cfg(feature = "std")]
295 /// Time elapsed before abandoning retries for a payment.
300 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
301 match (self, attempts) {
302 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
303 max_retry_count >= &count
305 #[cfg(feature = "std")]
306 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
307 *max_duration >= T::now().duration_since(*first_attempted_at),
312 /// An error that may occur when making a payment.
313 #[derive(Clone, Debug)]
314 pub enum PaymentError {
315 /// An error resulting from the provided [`Invoice`] or payment hash.
316 Invoice(&'static str),
317 /// An error occurring when finding a route.
318 Routing(LightningError),
319 /// An error occurring when sending a payment.
320 Sending(PaymentSendFailure),
323 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
328 /// Creates an invoice payer that retries failed payment paths.
330 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
331 /// `retry` has been exceeded for a given [`Invoice`].
333 payer: P, router: R, logger: L, event_handler: E, retry: Retry
340 payment_cache: Mutex::new(HashMap::new()),
345 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
347 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
348 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
350 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
351 if invoice.amount_milli_satoshis().is_none() {
352 Err(PaymentError::Invoice("amount missing"))
354 self.pay_invoice_using_amount(invoice, None)
358 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
359 /// case a retry is needed.
361 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
362 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
364 pub fn pay_zero_value_invoice(
365 &self, invoice: &Invoice, amount_msats: u64
366 ) -> Result<PaymentId, PaymentError> {
367 if invoice.amount_milli_satoshis().is_some() {
368 Err(PaymentError::Invoice("amount unexpected"))
370 self.pay_invoice_using_amount(invoice, Some(amount_msats))
374 fn pay_invoice_using_amount(
375 &self, invoice: &Invoice, amount_msats: Option<u64>
376 ) -> Result<PaymentId, PaymentError> {
377 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
379 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
380 match self.payment_cache.lock().unwrap().entry(payment_hash) {
381 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
382 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
385 let payment_secret = Some(invoice.payment_secret().clone());
386 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
387 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
388 .with_route_hints(invoice.route_hints());
389 if let Some(features) = invoice.features() {
390 payment_params = payment_params.with_features(features.clone());
392 let route_params = RouteParameters {
394 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
395 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
398 let send_payment = |route: &Route| {
399 self.payer.send_payment(route, payment_hash, &payment_secret)
402 self.pay_internal(&route_params, payment_hash, send_payment)
403 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
406 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
407 /// case a retry is needed.
409 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
410 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
412 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
413 final_cltv_expiry_delta: u32
414 ) -> Result<PaymentId, PaymentError> {
415 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
416 match self.payment_cache.lock().unwrap().entry(payment_hash) {
417 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
418 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
421 let route_params = RouteParameters {
422 payment_params: PaymentParameters::for_keysend(pubkey),
423 final_value_msat: amount_msats,
424 final_cltv_expiry_delta,
427 let send_payment = |route: &Route| {
428 self.payer.send_spontaneous_payment(route, payment_preimage)
430 self.pay_internal(&route_params, payment_hash, send_payment)
431 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
434 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
435 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
436 ) -> Result<PaymentId, PaymentError> {
437 #[cfg(feature = "std")] {
438 if has_expired(params) {
439 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
440 return Err(PaymentError::Invoice("Invoice expired prior to send"));
444 let payer = self.payer.node_id();
445 let first_hops = self.payer.first_hops();
446 let inflight_htlcs = self.create_inflight_map();
447 let route = self.router.find_route(
448 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
449 ).map_err(|e| PaymentError::Routing(e))?;
451 match send_payment(&route) {
453 for path in route.paths {
454 self.process_path_inflight_htlcs(payment_hash, path);
459 PaymentSendFailure::ParameterError(_) => Err(e),
460 PaymentSendFailure::PathParameterError(_) => Err(e),
461 PaymentSendFailure::AllFailedRetrySafe(_) => {
462 let mut payment_cache = self.payment_cache.lock().unwrap();
463 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
464 payment_info.attempts.count += 1;
465 if self.retry.is_retryable_now(&payment_info.attempts) {
466 core::mem::drop(payment_cache);
467 Ok(self.pay_internal(params, payment_hash, send_payment)?)
472 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
473 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
474 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
475 // means that we are still waiting for our channel monitor update to be completed.
476 for (result, path) in results.iter().zip(route.paths.into_iter()) {
478 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
479 self.process_path_inflight_htlcs(payment_hash, path);
485 if let Some(retry_data) = failed_paths_retry {
486 // Some paths were sent, even if we failed to send the full MPP value our
487 // recipient may misbehave and claim the funds, at which point we have to
488 // consider the payment sent, so return `Ok()` here, ignoring any retry
490 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
493 // This may happen if we send a payment and some paths fail, but
494 // only due to a temporary monitor failure or the like, implying
495 // they're really in-flight, but we haven't sent the initial
496 // HTLC-Add messages yet.
501 }.map_err(|e| PaymentError::Sending(e))
504 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
505 // that are pending retry.
506 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
507 self.payment_cache.lock().unwrap().entry(payment_hash)
508 .or_insert_with(|| PaymentInfo::new())
512 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
513 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
514 self.payment_cache.lock().unwrap().entry(payment_hash)
515 .and_modify(|payment_info| {
516 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
517 payment_info.paths.swap_remove(idx);
523 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
524 ) -> Result<(), ()> {
525 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
526 .and_modify(|info| info.attempts.count += 1 )
527 .or_insert_with(|| PaymentInfo {
528 attempts: PaymentAttempts {
530 first_attempted_at: T::now(),
535 if !self.retry.is_retryable_now(&attempts) {
536 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
540 #[cfg(feature = "std")] {
541 if has_expired(params) {
542 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
547 let payer = self.payer.node_id();
548 let first_hops = self.payer.first_hops();
549 let inflight_htlcs = self.create_inflight_map();
551 let route = self.router.find_route(
552 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
556 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
560 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
562 for path in route.unwrap().paths.into_iter() {
563 self.process_path_inflight_htlcs(payment_hash, path);
567 Err(PaymentSendFailure::ParameterError(_)) |
568 Err(PaymentSendFailure::PathParameterError(_)) => {
569 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
572 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
573 self.retry_payment(payment_id, payment_hash, params)
575 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
576 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
577 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
578 // means that we are still waiting for our channel monitor update to complete.
579 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
581 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
582 self.process_path_inflight_htlcs(payment_hash, path);
588 if let Some(retry) = failed_paths_retry {
589 // Always return Ok for the same reason as noted in pay_internal.
590 let _ = self.retry_payment(payment_id, payment_hash, &retry);
597 /// Removes the payment cached by the given payment hash.
599 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
600 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
601 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
602 self.payment_cache.lock().unwrap().remove(payment_hash);
605 /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
606 /// channel id and direction to the amount being sent through it.
608 /// This function should be called whenever we need information about currently used up liquidity
610 fn create_inflight_map(&self) -> InFlightHtlcs {
611 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
612 // Make an attempt at finding existing payment information from `payment_cache`. If it
613 // does not exist, it probably is a fresh payment and we can just return an empty
615 for payment_info in self.payment_cache.lock().unwrap().values() {
616 for path in &payment_info.paths {
617 if path.is_empty() { break };
618 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
619 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
620 // the router excludes the payer node. In the following lines, the payer's information is
621 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
622 // in our sliding window of two.
623 let our_node_id: PublicKey = self.payer.node_id();
624 let reversed_hops_with_payer = path.iter().rev().skip(1)
625 .map(|hop| hop.pubkey)
626 .chain(core::iter::once(our_node_id));
627 let mut cumulative_msat = 0;
629 // Taking the reversed vector from above, we zip it with just the reversed hops list to
630 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
631 // the total amount sent.
632 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
633 cumulative_msat += next_hop.fee_msat;
635 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
636 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
637 .or_insert(cumulative_msat);
642 InFlightHtlcs::new(total_inflight_map)
646 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
647 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
650 #[cfg(feature = "std")]
651 fn has_expired(route_params: &RouteParameters) -> bool {
652 if let Some(expiry_time) = route_params.payment_params.expiry_time {
653 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
657 impl<P: Deref, R: Router, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
662 fn handle_event(&self, event: &Event) {
664 Event::PaymentPathFailed { payment_hash, path, .. }
665 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
666 | Event::ProbeSuccessful { payment_hash, path, .. }
667 | Event::ProbeFailed { payment_hash, path, .. } => {
668 self.remove_path_inflight_htlcs(*payment_hash, path);
674 Event::PaymentPathFailed {
675 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
677 if let Some(short_channel_id) = short_channel_id {
678 let path = path.iter().collect::<Vec<_>>();
679 self.router.notify_payment_path_failed(&path, *short_channel_id)
682 if payment_id.is_none() {
683 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
684 } else if *payment_failed_permanently {
685 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
686 self.payer.abandon_payment(payment_id.unwrap());
687 } else if retry.is_none() {
688 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
689 self.payer.abandon_payment(payment_id.unwrap());
690 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
691 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
694 self.payer.abandon_payment(payment_id.unwrap());
697 Event::PaymentFailed { payment_hash, .. } => {
698 self.remove_cached_payment(&payment_hash);
700 Event::PaymentPathSuccessful { path, .. } => {
701 let path = path.iter().collect::<Vec<_>>();
702 self.router.notify_payment_path_successful(&path);
704 Event::PaymentSent { payment_hash, .. } => {
705 let mut payment_cache = self.payment_cache.lock().unwrap();
706 let attempts = payment_cache
707 .remove(payment_hash)
708 .map_or(1, |payment_info| payment_info.attempts.count + 1);
709 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
711 Event::ProbeSuccessful { payment_hash, path, .. } => {
712 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
713 let path = path.iter().collect::<Vec<_>>();
714 self.router.notify_payment_probe_successful(&path);
716 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
717 if let Some(short_channel_id) = short_channel_id {
718 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
719 let path = path.iter().collect::<Vec<_>>();
720 self.router.notify_payment_probe_failed(&path, *short_channel_id);
726 // Delegate to the decorated event handler unless the payment is retried.
727 self.event_handler.handle_event(event)
734 use crate::{InvoiceBuilder, Currency};
735 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
736 use bitcoin_hashes::sha256::Hash as Sha256;
737 use lightning::ln::PaymentPreimage;
738 use lightning::ln::channelmanager;
739 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
740 use lightning::ln::functional_test_utils::*;
741 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
742 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
743 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop};
744 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
745 use lightning::util::test_utils::TestLogger;
746 use lightning::util::errors::APIError;
747 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
748 use secp256k1::{SecretKey, PublicKey, Secp256k1};
749 use std::cell::RefCell;
750 use std::collections::VecDeque;
751 use std::ops::DerefMut;
752 use std::time::{SystemTime, Duration};
753 use crate::time_utils::tests::SinceEpoch;
754 use crate::DEFAULT_EXPIRY_TIME;
755 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
757 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
758 let payment_hash = Sha256::hash(&payment_preimage.0);
759 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
761 InvoiceBuilder::new(Currency::Bitcoin)
762 .description("test".into())
763 .payment_hash(payment_hash)
764 .payment_secret(PaymentSecret([0; 32]))
765 .duration_since_epoch(duration_since_epoch())
766 .min_final_cltv_expiry(144)
767 .amount_milli_satoshis(128)
768 .build_signed(|hash| {
769 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
774 fn duration_since_epoch() -> Duration {
775 #[cfg(feature = "std")]
776 let duration_since_epoch =
777 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
778 #[cfg(not(feature = "std"))]
779 let duration_since_epoch = Duration::from_secs(1234567);
783 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
784 let payment_hash = Sha256::hash(&payment_preimage.0);
785 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
787 InvoiceBuilder::new(Currency::Bitcoin)
788 .description("test".into())
789 .payment_hash(payment_hash)
790 .payment_secret(PaymentSecret([0; 32]))
791 .duration_since_epoch(duration_since_epoch())
792 .min_final_cltv_expiry(144)
793 .build_signed(|hash| {
794 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
799 #[cfg(feature = "std")]
800 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
801 let payment_hash = Sha256::hash(&payment_preimage.0);
802 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
803 let duration = duration_since_epoch()
804 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
806 InvoiceBuilder::new(Currency::Bitcoin)
807 .description("test".into())
808 .payment_hash(payment_hash)
809 .payment_secret(PaymentSecret([0; 32]))
810 .duration_since_epoch(duration)
811 .min_final_cltv_expiry(144)
812 .amount_milli_satoshis(128)
813 .build_signed(|hash| {
814 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
819 fn pubkey() -> PublicKey {
820 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
824 fn pays_invoice_on_first_attempt() {
825 let event_handled = core::cell::RefCell::new(false);
826 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
828 let payment_preimage = PaymentPreimage([1; 32]);
829 let invoice = invoice(payment_preimage);
830 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
831 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
833 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
834 let router = TestRouter::new(TestScorer::new());
835 let logger = TestLogger::new();
837 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
839 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
840 assert_eq!(*payer.attempts.borrow(), 1);
842 invoice_payer.handle_event(&Event::PaymentSent {
843 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
845 assert_eq!(*event_handled.borrow(), true);
846 assert_eq!(*payer.attempts.borrow(), 1);
850 fn pays_invoice_on_retry() {
851 let event_handled = core::cell::RefCell::new(false);
852 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
854 let payment_preimage = PaymentPreimage([1; 32]);
855 let invoice = invoice(payment_preimage);
856 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
857 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
859 let payer = TestPayer::new()
860 .expect_send(Amount::ForInvoice(final_value_msat))
861 .expect_send(Amount::OnRetry(final_value_msat / 2));
862 let router = TestRouter::new(TestScorer::new());
863 let logger = TestLogger::new();
865 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
867 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
868 assert_eq!(*payer.attempts.borrow(), 1);
870 let event = Event::PaymentPathFailed {
873 network_update: None,
874 payment_failed_permanently: false,
875 all_paths_failed: false,
876 path: TestRouter::path_for_value(final_value_msat),
877 short_channel_id: None,
878 retry: Some(TestRouter::retry_for_invoice(&invoice)),
880 invoice_payer.handle_event(&event);
881 assert_eq!(*event_handled.borrow(), false);
882 assert_eq!(*payer.attempts.borrow(), 2);
884 invoice_payer.handle_event(&Event::PaymentSent {
885 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
887 assert_eq!(*event_handled.borrow(), true);
888 assert_eq!(*payer.attempts.borrow(), 2);
892 fn pays_invoice_on_partial_failure() {
893 let event_handler = |_: &_| { panic!() };
895 let payment_preimage = PaymentPreimage([1; 32]);
896 let invoice = invoice(payment_preimage);
897 let retry = TestRouter::retry_for_invoice(&invoice);
898 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
900 let payer = TestPayer::new()
901 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
902 .fails_with_partial_failure(retry, OnAttempt(2), None)
903 .expect_send(Amount::ForInvoice(final_value_msat))
904 .expect_send(Amount::OnRetry(final_value_msat / 2))
905 .expect_send(Amount::OnRetry(final_value_msat / 2));
906 let router = TestRouter::new(TestScorer::new());
907 let logger = TestLogger::new();
909 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
911 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
915 fn retries_payment_path_for_unknown_payment() {
916 let event_handled = core::cell::RefCell::new(false);
917 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
919 let payment_preimage = PaymentPreimage([1; 32]);
920 let invoice = invoice(payment_preimage);
921 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
922 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
924 let payer = TestPayer::new()
925 .expect_send(Amount::OnRetry(final_value_msat / 2))
926 .expect_send(Amount::OnRetry(final_value_msat / 2));
927 let router = TestRouter::new(TestScorer::new());
928 let logger = TestLogger::new();
930 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
932 let payment_id = Some(PaymentId([1; 32]));
933 let event = Event::PaymentPathFailed {
936 network_update: None,
937 payment_failed_permanently: false,
938 all_paths_failed: false,
939 path: TestRouter::path_for_value(final_value_msat),
940 short_channel_id: None,
941 retry: Some(TestRouter::retry_for_invoice(&invoice)),
943 invoice_payer.handle_event(&event);
944 assert_eq!(*event_handled.borrow(), false);
945 assert_eq!(*payer.attempts.borrow(), 1);
947 invoice_payer.handle_event(&event);
948 assert_eq!(*event_handled.borrow(), false);
949 assert_eq!(*payer.attempts.borrow(), 2);
951 invoice_payer.handle_event(&Event::PaymentSent {
952 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
954 assert_eq!(*event_handled.borrow(), true);
955 assert_eq!(*payer.attempts.borrow(), 2);
959 fn fails_paying_invoice_after_max_retry_counts() {
960 let event_handled = core::cell::RefCell::new(false);
961 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
963 let payment_preimage = PaymentPreimage([1; 32]);
964 let invoice = invoice(payment_preimage);
965 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
967 let payer = TestPayer::new()
968 .expect_send(Amount::ForInvoice(final_value_msat))
969 .expect_send(Amount::OnRetry(final_value_msat / 2))
970 .expect_send(Amount::OnRetry(final_value_msat / 2));
971 let router = TestRouter::new(TestScorer::new());
972 let logger = TestLogger::new();
974 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
976 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
977 assert_eq!(*payer.attempts.borrow(), 1);
979 let event = Event::PaymentPathFailed {
981 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
982 network_update: None,
983 payment_failed_permanently: false,
984 all_paths_failed: true,
985 path: TestRouter::path_for_value(final_value_msat),
986 short_channel_id: None,
987 retry: Some(TestRouter::retry_for_invoice(&invoice)),
989 invoice_payer.handle_event(&event);
990 assert_eq!(*event_handled.borrow(), false);
991 assert_eq!(*payer.attempts.borrow(), 2);
993 let event = Event::PaymentPathFailed {
995 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
996 network_update: None,
997 payment_failed_permanently: false,
998 all_paths_failed: false,
999 path: TestRouter::path_for_value(final_value_msat / 2),
1000 short_channel_id: None,
1001 retry: Some(RouteParameters {
1002 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1005 invoice_payer.handle_event(&event);
1006 assert_eq!(*event_handled.borrow(), false);
1007 assert_eq!(*payer.attempts.borrow(), 3);
1009 invoice_payer.handle_event(&event);
1010 assert_eq!(*event_handled.borrow(), true);
1011 assert_eq!(*payer.attempts.borrow(), 3);
1014 #[cfg(feature = "std")]
1016 fn fails_paying_invoice_after_max_retry_timeout() {
1017 let event_handled = core::cell::RefCell::new(false);
1018 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1020 let payment_preimage = PaymentPreimage([1; 32]);
1021 let invoice = invoice(payment_preimage);
1022 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1024 let payer = TestPayer::new()
1025 .expect_send(Amount::ForInvoice(final_value_msat))
1026 .expect_send(Amount::OnRetry(final_value_msat / 2));
1028 let router = TestRouter::new(TestScorer::new());
1029 let logger = TestLogger::new();
1030 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1033 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1035 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1036 assert_eq!(*payer.attempts.borrow(), 1);
1038 let event = Event::PaymentPathFailed {
1040 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1041 network_update: None,
1042 payment_failed_permanently: false,
1043 all_paths_failed: true,
1044 path: TestRouter::path_for_value(final_value_msat),
1045 short_channel_id: None,
1046 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1048 invoice_payer.handle_event(&event);
1049 assert_eq!(*event_handled.borrow(), false);
1050 assert_eq!(*payer.attempts.borrow(), 2);
1052 SinceEpoch::advance(Duration::from_secs(121));
1054 invoice_payer.handle_event(&event);
1055 assert_eq!(*event_handled.borrow(), true);
1056 assert_eq!(*payer.attempts.borrow(), 2);
1060 fn fails_paying_invoice_with_missing_retry_params() {
1061 let event_handled = core::cell::RefCell::new(false);
1062 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1064 let payment_preimage = PaymentPreimage([1; 32]);
1065 let invoice = invoice(payment_preimage);
1066 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1068 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1069 let router = TestRouter::new(TestScorer::new());
1070 let logger = TestLogger::new();
1072 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1074 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1075 assert_eq!(*payer.attempts.borrow(), 1);
1077 let event = Event::PaymentPathFailed {
1079 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1080 network_update: None,
1081 payment_failed_permanently: false,
1082 all_paths_failed: false,
1084 short_channel_id: None,
1087 invoice_payer.handle_event(&event);
1088 assert_eq!(*event_handled.borrow(), true);
1089 assert_eq!(*payer.attempts.borrow(), 1);
1092 // Expiration is checked only in an std environment
1093 #[cfg(feature = "std")]
1095 fn fails_paying_invoice_after_expiration() {
1096 let event_handled = core::cell::RefCell::new(false);
1097 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1099 let payer = TestPayer::new();
1100 let router = TestRouter::new(TestScorer::new());
1101 let logger = TestLogger::new();
1103 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1105 let payment_preimage = PaymentPreimage([1; 32]);
1106 let invoice = expired_invoice(payment_preimage);
1107 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1108 assert_eq!(msg, "Invoice expired prior to send");
1109 } else { panic!("Expected Invoice Error"); }
1112 // Expiration is checked only in an std environment
1113 #[cfg(feature = "std")]
1115 fn fails_retrying_invoice_after_expiration() {
1116 let event_handled = core::cell::RefCell::new(false);
1117 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1119 let payment_preimage = PaymentPreimage([1; 32]);
1120 let invoice = invoice(payment_preimage);
1121 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1123 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1124 let router = TestRouter::new(TestScorer::new());
1125 let logger = TestLogger::new();
1127 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1129 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1130 assert_eq!(*payer.attempts.borrow(), 1);
1132 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1133 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1134 .checked_sub(Duration::from_secs(2)).unwrap()
1135 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1136 let event = Event::PaymentPathFailed {
1138 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1139 network_update: None,
1140 payment_failed_permanently: false,
1141 all_paths_failed: false,
1143 short_channel_id: None,
1144 retry: Some(retry_data),
1146 invoice_payer.handle_event(&event);
1147 assert_eq!(*event_handled.borrow(), true);
1148 assert_eq!(*payer.attempts.borrow(), 1);
1152 fn fails_paying_invoice_after_retry_error() {
1153 let event_handled = core::cell::RefCell::new(false);
1154 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1156 let payment_preimage = PaymentPreimage([1; 32]);
1157 let invoice = invoice(payment_preimage);
1158 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1160 let payer = TestPayer::new()
1161 .fails_on_attempt(2)
1162 .expect_send(Amount::ForInvoice(final_value_msat))
1163 .expect_send(Amount::OnRetry(final_value_msat / 2));
1164 let router = TestRouter::new(TestScorer::new());
1165 let logger = TestLogger::new();
1167 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1169 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1170 assert_eq!(*payer.attempts.borrow(), 1);
1172 let event = Event::PaymentPathFailed {
1174 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1175 network_update: None,
1176 payment_failed_permanently: false,
1177 all_paths_failed: false,
1178 path: TestRouter::path_for_value(final_value_msat / 2),
1179 short_channel_id: None,
1180 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1182 invoice_payer.handle_event(&event);
1183 assert_eq!(*event_handled.borrow(), true);
1184 assert_eq!(*payer.attempts.borrow(), 2);
1188 fn fails_paying_invoice_after_rejected_by_payee() {
1189 let event_handled = core::cell::RefCell::new(false);
1190 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1192 let payment_preimage = PaymentPreimage([1; 32]);
1193 let invoice = invoice(payment_preimage);
1194 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1196 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1197 let router = TestRouter::new(TestScorer::new());
1198 let logger = TestLogger::new();
1200 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1202 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1203 assert_eq!(*payer.attempts.borrow(), 1);
1205 let event = Event::PaymentPathFailed {
1207 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1208 network_update: None,
1209 payment_failed_permanently: true,
1210 all_paths_failed: false,
1212 short_channel_id: None,
1213 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1215 invoice_payer.handle_event(&event);
1216 assert_eq!(*event_handled.borrow(), true);
1217 assert_eq!(*payer.attempts.borrow(), 1);
1221 fn fails_repaying_invoice_with_pending_payment() {
1222 let event_handled = core::cell::RefCell::new(false);
1223 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1225 let payment_preimage = PaymentPreimage([1; 32]);
1226 let invoice = invoice(payment_preimage);
1227 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1229 let payer = TestPayer::new()
1230 .expect_send(Amount::ForInvoice(final_value_msat))
1231 .expect_send(Amount::ForInvoice(final_value_msat));
1232 let router = TestRouter::new(TestScorer::new());
1233 let logger = TestLogger::new();
1235 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1237 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1239 // Cannot repay an invoice pending payment.
1240 match invoice_payer.pay_invoice(&invoice) {
1241 Err(PaymentError::Invoice("payment pending")) => {},
1242 Err(_) => panic!("unexpected error"),
1243 Ok(_) => panic!("expected invoice error"),
1246 // Can repay an invoice once cleared from cache.
1247 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1248 invoice_payer.remove_cached_payment(&payment_hash);
1249 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1251 // Cannot retry paying an invoice if cleared from cache.
1252 invoice_payer.remove_cached_payment(&payment_hash);
1253 let event = Event::PaymentPathFailed {
1256 network_update: None,
1257 payment_failed_permanently: false,
1258 all_paths_failed: false,
1260 short_channel_id: None,
1261 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1263 invoice_payer.handle_event(&event);
1264 assert_eq!(*event_handled.borrow(), true);
1268 fn fails_paying_invoice_with_routing_errors() {
1269 let payer = TestPayer::new();
1270 let router = FailingRouter {};
1271 let logger = TestLogger::new();
1273 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1275 let payment_preimage = PaymentPreimage([1; 32]);
1276 let invoice = invoice(payment_preimage);
1277 match invoice_payer.pay_invoice(&invoice) {
1278 Err(PaymentError::Routing(_)) => {},
1279 Err(_) => panic!("unexpected error"),
1280 Ok(_) => panic!("expected routing error"),
1285 fn fails_paying_invoice_with_sending_errors() {
1286 let payment_preimage = PaymentPreimage([1; 32]);
1287 let invoice = invoice(payment_preimage);
1288 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1290 let payer = TestPayer::new()
1291 .fails_on_attempt(1)
1292 .expect_send(Amount::ForInvoice(final_value_msat));
1293 let router = TestRouter::new(TestScorer::new());
1294 let logger = TestLogger::new();
1296 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1298 match invoice_payer.pay_invoice(&invoice) {
1299 Err(PaymentError::Sending(_)) => {},
1300 Err(_) => panic!("unexpected error"),
1301 Ok(_) => panic!("expected sending error"),
1306 fn pays_zero_value_invoice_using_amount() {
1307 let event_handled = core::cell::RefCell::new(false);
1308 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1310 let payment_preimage = PaymentPreimage([1; 32]);
1311 let invoice = zero_value_invoice(payment_preimage);
1312 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1313 let final_value_msat = 100;
1315 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1316 let router = TestRouter::new(TestScorer::new());
1317 let logger = TestLogger::new();
1319 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1322 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1323 assert_eq!(*payer.attempts.borrow(), 1);
1325 invoice_payer.handle_event(&Event::PaymentSent {
1326 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1328 assert_eq!(*event_handled.borrow(), true);
1329 assert_eq!(*payer.attempts.borrow(), 1);
1333 fn fails_paying_zero_value_invoice_with_amount() {
1334 let event_handled = core::cell::RefCell::new(false);
1335 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1337 let payer = TestPayer::new();
1338 let router = TestRouter::new(TestScorer::new());
1339 let logger = TestLogger::new();
1341 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1343 let payment_preimage = PaymentPreimage([1; 32]);
1344 let invoice = invoice(payment_preimage);
1346 // Cannot repay an invoice pending payment.
1347 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1348 Err(PaymentError::Invoice("amount unexpected")) => {},
1349 Err(_) => panic!("unexpected error"),
1350 Ok(_) => panic!("expected invoice error"),
1355 fn pays_pubkey_with_amount() {
1356 let event_handled = core::cell::RefCell::new(false);
1357 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1359 let pubkey = pubkey();
1360 let payment_preimage = PaymentPreimage([1; 32]);
1361 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1362 let final_value_msat = 100;
1363 let final_cltv_expiry_delta = 42;
1365 let payer = TestPayer::new()
1366 .expect_send(Amount::Spontaneous(final_value_msat))
1367 .expect_send(Amount::OnRetry(final_value_msat));
1368 let router = TestRouter::new(TestScorer::new());
1369 let logger = TestLogger::new();
1371 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1373 let payment_id = Some(invoice_payer.pay_pubkey(
1374 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1376 assert_eq!(*payer.attempts.borrow(), 1);
1378 let retry = RouteParameters {
1379 payment_params: PaymentParameters::for_keysend(pubkey),
1381 final_cltv_expiry_delta,
1383 let event = Event::PaymentPathFailed {
1386 network_update: None,
1387 payment_failed_permanently: false,
1388 all_paths_failed: false,
1390 short_channel_id: None,
1393 invoice_payer.handle_event(&event);
1394 assert_eq!(*event_handled.borrow(), false);
1395 assert_eq!(*payer.attempts.borrow(), 2);
1397 invoice_payer.handle_event(&Event::PaymentSent {
1398 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1400 assert_eq!(*event_handled.borrow(), true);
1401 assert_eq!(*payer.attempts.borrow(), 2);
1405 fn scores_failed_channel() {
1406 let event_handled = core::cell::RefCell::new(false);
1407 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1409 let payment_preimage = PaymentPreimage([1; 32]);
1410 let invoice = invoice(payment_preimage);
1411 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1412 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1413 let path = TestRouter::path_for_value(final_value_msat);
1414 let short_channel_id = Some(path[0].short_channel_id);
1416 // Expect that scorer is given short_channel_id upon handling the event.
1417 let payer = TestPayer::new()
1418 .expect_send(Amount::ForInvoice(final_value_msat))
1419 .expect_send(Amount::OnRetry(final_value_msat / 2));
1420 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1421 path: path.clone(), short_channel_id: path[0].short_channel_id,
1423 let router = TestRouter::new(scorer);
1424 let logger = TestLogger::new();
1426 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1428 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1429 let event = Event::PaymentPathFailed {
1432 network_update: None,
1433 payment_failed_permanently: false,
1434 all_paths_failed: false,
1437 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1439 invoice_payer.handle_event(&event);
1443 fn scores_successful_channels() {
1444 let event_handled = core::cell::RefCell::new(false);
1445 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1447 let payment_preimage = PaymentPreimage([1; 32]);
1448 let invoice = invoice(payment_preimage);
1449 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1450 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1451 let route = TestRouter::route_for_value(final_value_msat);
1453 // Expect that scorer is given short_channel_id upon handling the event.
1454 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1455 let scorer = TestScorer::new()
1456 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1457 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1458 let router = TestRouter::new(scorer);
1459 let logger = TestLogger::new();
1461 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1463 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1464 let event = Event::PaymentPathSuccessful {
1465 payment_id, payment_hash, path: route.paths[0].clone()
1467 invoice_payer.handle_event(&event);
1468 let event = Event::PaymentPathSuccessful {
1469 payment_id, payment_hash, path: route.paths[1].clone()
1471 invoice_payer.handle_event(&event);
1475 fn generates_correct_inflight_map_data() {
1476 let event_handled = core::cell::RefCell::new(false);
1477 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1479 let payment_preimage = PaymentPreimage([1; 32]);
1480 let invoice = invoice(payment_preimage);
1481 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1482 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1484 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1485 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1486 let route = TestRouter::route_for_value(final_value_msat);
1487 let router = TestRouter::new(TestScorer::new());
1488 let logger = TestLogger::new();
1490 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1492 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1494 let inflight_map = invoice_payer.create_inflight_map();
1496 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1497 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1498 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1500 // Second path check
1501 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1502 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1504 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1505 payment_id, payment_hash, path: route.paths[0].clone()
1508 let inflight_map = invoice_payer.create_inflight_map();
1510 assert_eq!(inflight_map.0.get(&(0, false)), None);
1511 assert_eq!(inflight_map.0.get(&(1, true)), None);
1512 assert_eq!(inflight_map.0.get(&(2, false)), None);
1514 // Second path should still be inflight
1515 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1516 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1520 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1521 // First, let's just send a payment through, but only make sure one of the path completes
1522 let event_handled = core::cell::RefCell::new(false);
1523 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1525 let payment_preimage = PaymentPreimage([1; 32]);
1526 let payment_invoice = invoice(payment_preimage);
1527 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1528 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1530 let payer = TestPayer::new()
1531 .expect_send(Amount::ForInvoice(final_value_msat))
1532 .expect_send(Amount::ForInvoice(final_value_msat));
1533 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1534 let route = TestRouter::route_for_value(final_value_msat);
1535 let scorer = TestScorer::new()
1536 // 1st invoice, 1st path
1537 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1538 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1539 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1540 // 1st invoice, 2nd path
1541 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1542 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1543 // 2nd invoice, 1st path
1544 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1545 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1546 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1547 // 2nd invoice, 2nd path
1548 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1549 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1550 let router = TestRouter::new(scorer);
1551 let logger = TestLogger::new();
1553 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1555 // Succeed 1st path, leave 2nd path inflight
1556 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1557 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1558 payment_id, payment_hash, path: route.paths[0].clone()
1561 // Let's pay a second invoice that will be using the same path. This should trigger the
1562 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1563 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1564 // have 64 msats inflight for paths considering the channel with scid of 1.
1565 let payment_preimage_2 = PaymentPreimage([2; 32]);
1566 let payment_invoice_2 = invoice(payment_preimage_2);
1567 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1571 fn considers_inflight_htlcs_between_retries() {
1572 // First, let's just send a payment through, but only make sure one of the path completes
1573 let event_handled = core::cell::RefCell::new(false);
1574 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1576 let payment_preimage = PaymentPreimage([1; 32]);
1577 let payment_invoice = invoice(payment_preimage);
1578 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1579 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1581 let payer = TestPayer::new()
1582 .expect_send(Amount::ForInvoice(final_value_msat))
1583 .expect_send(Amount::OnRetry(final_value_msat / 2))
1584 .expect_send(Amount::OnRetry(final_value_msat / 4));
1585 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1586 let scorer = TestScorer::new()
1587 // 1st invoice, 1st path
1588 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1589 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1590 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1591 // 1st invoice, 2nd path
1592 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1593 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1594 // Retry 1, 1st path
1595 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1596 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1597 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1598 // Retry 1, 2nd path
1599 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1600 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1601 // Retry 2, 1st path
1602 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1603 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1604 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1605 // Retry 2, 2nd path
1606 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1607 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1608 let router = TestRouter::new(scorer);
1609 let logger = TestLogger::new();
1611 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1613 // Fail 1st path, leave 2nd path inflight
1614 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1615 invoice_payer.handle_event(&Event::PaymentPathFailed {
1618 network_update: None,
1619 payment_failed_permanently: false,
1620 all_paths_failed: false,
1621 path: TestRouter::path_for_value(final_value_msat),
1622 short_channel_id: None,
1623 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1626 // Fails again the 1st path of our retry
1627 invoice_payer.handle_event(&Event::PaymentPathFailed {
1630 network_update: None,
1631 payment_failed_permanently: false,
1632 all_paths_failed: false,
1633 path: TestRouter::path_for_value(final_value_msat / 2),
1634 short_channel_id: None,
1635 retry: Some(RouteParameters {
1636 final_value_msat: final_value_msat / 4,
1637 ..TestRouter::retry_for_invoice(&payment_invoice)
1643 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1644 let event_handled = core::cell::RefCell::new(false);
1645 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1647 let payment_preimage = PaymentPreimage([1; 32]);
1648 let invoice_to_pay = invoice(payment_preimage);
1649 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1651 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1652 let payer = TestPayer::new()
1653 .fails_with_partial_failure(
1654 retry.clone(), OnAttempt(1),
1656 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1658 .expect_send(Amount::ForInvoice(final_value_msat));
1660 let router = TestRouter::new(TestScorer::new());
1661 let logger = TestLogger::new();
1663 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1665 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1666 let inflight_map = invoice_payer.create_inflight_map();
1668 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1669 // inflight map because retries are disabled.
1670 assert_eq!(inflight_map.0.len(), 2);
1674 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1675 let event_handled = core::cell::RefCell::new(false);
1676 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1678 let payment_preimage = PaymentPreimage([1; 32]);
1679 let invoice_to_pay = invoice(payment_preimage);
1680 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1682 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1683 let payer = TestPayer::new()
1684 .fails_with_partial_failure(
1685 retry.clone(), OnAttempt(1),
1687 Ok(()), Err(MonitorUpdateInProgress)
1689 .expect_send(Amount::ForInvoice(final_value_msat));
1691 let router = TestRouter::new(TestScorer::new());
1692 let logger = TestLogger::new();
1694 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1696 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1697 let inflight_map = invoice_payer.create_inflight_map();
1699 // All paths successful, hence we check of the existence of all 5 hops.
1700 assert_eq!(inflight_map.0.len(), 5);
1704 scorer: RefCell<TestScorer>,
1708 fn new(scorer: TestScorer) -> Self {
1709 TestRouter { scorer: RefCell::new(scorer) }
1712 fn route_for_value(final_value_msat: u64) -> Route {
1717 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1718 channel_features: ChannelFeatures::empty(),
1719 node_features: NodeFeatures::empty(),
1720 short_channel_id: 0,
1722 cltv_expiry_delta: 0
1725 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1726 channel_features: ChannelFeatures::empty(),
1727 node_features: NodeFeatures::empty(),
1728 short_channel_id: 1,
1730 cltv_expiry_delta: 0
1733 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1734 channel_features: ChannelFeatures::empty(),
1735 node_features: NodeFeatures::empty(),
1736 short_channel_id: 2,
1737 fee_msat: final_value_msat / 2,
1738 cltv_expiry_delta: 0
1743 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1744 channel_features: ChannelFeatures::empty(),
1745 node_features: NodeFeatures::empty(),
1746 short_channel_id: 3,
1748 cltv_expiry_delta: 144
1751 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1752 channel_features: ChannelFeatures::empty(),
1753 node_features: NodeFeatures::empty(),
1754 short_channel_id: 4,
1755 fee_msat: final_value_msat / 2,
1756 cltv_expiry_delta: 144
1760 payment_params: None,
1764 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1765 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1768 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1769 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1770 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1771 .with_route_hints(invoice.route_hints());
1772 if let Some(features) = invoice.features() {
1773 payment_params = payment_params.with_features(features.clone());
1775 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1779 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1784 impl Router for TestRouter {
1786 &self, payer: &PublicKey, route_params: &RouteParameters,
1787 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1788 ) -> Result<Route, LightningError> {
1789 // Simulate calling the Scorer just as you would in find_route
1790 let route = Self::route_for_value(route_params.final_value_msat);
1791 let mut locked_scorer = self.scorer.lock();
1792 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1793 for path in route.paths {
1794 let mut aggregate_msat = 0u64;
1795 for (idx, hop) in path.iter().rev().enumerate() {
1796 aggregate_msat += hop.fee_msat;
1797 let usage = ChannelUsage {
1798 amount_msat: aggregate_msat,
1799 inflight_htlc_msat: 0,
1800 effective_capacity: EffectiveCapacity::Unknown,
1803 // Since the path is reversed, the last element in our iteration is the first
1805 if idx == path.len() - 1 {
1806 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1808 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1814 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1818 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1819 self.scorer.lock().payment_path_failed(path, short_channel_id);
1822 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1823 self.scorer.lock().payment_path_successful(path);
1826 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1827 self.scorer.lock().probe_successful(path);
1830 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1831 self.scorer.lock().probe_failed(path, short_channel_id);
1835 struct FailingRouter;
1837 impl Router for FailingRouter {
1839 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1840 _inflight_htlcs: InFlightHtlcs,
1841 ) -> Result<Route, LightningError> {
1842 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1845 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1847 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1849 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1851 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1855 event_expectations: Option<VecDeque<TestResult>>,
1856 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1861 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1862 PaymentSuccess { path: Vec<RouteHop> },
1868 event_expectations: None,
1869 scorer_expectations: RefCell::new(None),
1873 fn expect(mut self, expectation: TestResult) -> Self {
1874 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1878 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1879 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1885 impl lightning::util::ser::Writeable for TestScorer {
1886 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1889 impl Score for TestScorer {
1890 fn channel_penalty_msat(
1891 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1893 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1894 match scorer_expectations.pop_front() {
1895 Some(expectation) => {
1896 assert_eq!(expectation.amount_msat, usage.amount_msat);
1897 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1905 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1906 if let Some(expectations) = &mut self.event_expectations {
1907 match expectations.pop_front() {
1908 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1909 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1910 assert_eq!(actual_short_channel_id, short_channel_id);
1912 Some(TestResult::PaymentSuccess { path }) => {
1913 panic!("Unexpected successful payment path: {:?}", path)
1915 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1920 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1921 if let Some(expectations) = &mut self.event_expectations {
1922 match expectations.pop_front() {
1923 Some(TestResult::PaymentFailure { path, .. }) => {
1924 panic!("Unexpected payment path failure: {:?}", path)
1926 Some(TestResult::PaymentSuccess { path }) => {
1927 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1929 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1934 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1935 if let Some(expectations) = &mut self.event_expectations {
1936 match expectations.pop_front() {
1937 Some(TestResult::PaymentFailure { path, .. }) => {
1938 panic!("Unexpected failed payment path: {:?}", path)
1940 Some(TestResult::PaymentSuccess { path }) => {
1941 panic!("Unexpected successful payment path: {:?}", path)
1943 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1947 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1948 if let Some(expectations) = &mut self.event_expectations {
1949 match expectations.pop_front() {
1950 Some(TestResult::PaymentFailure { path, .. }) => {
1951 panic!("Unexpected payment path failure: {:?}", path)
1953 Some(TestResult::PaymentSuccess { path }) => {
1954 panic!("Unexpected successful payment path: {:?}", path)
1956 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1962 impl Drop for TestScorer {
1963 fn drop(&mut self) {
1964 if std::thread::panicking() {
1968 if let Some(event_expectations) = &self.event_expectations {
1969 if !event_expectations.is_empty() {
1970 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1974 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1975 if !scorer_expectations.is_empty() {
1976 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1983 expectations: core::cell::RefCell<VecDeque<Amount>>,
1984 attempts: core::cell::RefCell<usize>,
1985 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1988 #[derive(Clone, Debug, PartialEq, Eq)]
1995 struct OnAttempt(usize);
2000 expectations: core::cell::RefCell::new(VecDeque::new()),
2001 attempts: core::cell::RefCell::new(0),
2002 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2006 fn expect_send(self, value_msat: Amount) -> Self {
2007 self.expectations.borrow_mut().push_back(value_msat);
2011 fn fails_on_attempt(self, attempt: usize) -> Self {
2012 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2013 self.fails_with(failure, OnAttempt(attempt))
2016 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2017 self.fails_with(PaymentSendFailure::PartialFailure {
2018 results: results.unwrap_or(vec![]),
2019 failed_paths_retry: Some(retry),
2020 payment_id: PaymentId([1; 32]),
2024 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2025 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2029 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2030 let mut attempts = self.attempts.borrow_mut();
2033 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2034 Some(failure) => Err(failure),
2035 None => Ok(PaymentId([1; 32])),
2039 fn check_value_msats(&self, actual_value_msats: Amount) {
2040 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2041 if let Some(expected_value_msats) = expected_value_msats {
2042 assert_eq!(actual_value_msats, expected_value_msats);
2044 panic!("Unexpected amount: {:?}", actual_value_msats);
2049 impl Drop for TestPayer {
2050 fn drop(&mut self) {
2051 if std::thread::panicking() {
2055 if !self.expectations.borrow().is_empty() {
2056 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2061 impl Payer for TestPayer {
2062 fn node_id(&self) -> PublicKey {
2063 let secp_ctx = Secp256k1::new();
2064 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2067 fn first_hops(&self) -> Vec<ChannelDetails> {
2072 &self, route: &Route, _payment_hash: PaymentHash,
2073 _payment_secret: &Option<PaymentSecret>
2074 ) -> Result<PaymentId, PaymentSendFailure> {
2075 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2076 self.check_attempts()
2079 fn send_spontaneous_payment(
2080 &self, route: &Route, _payment_preimage: PaymentPreimage,
2081 ) -> Result<PaymentId, PaymentSendFailure> {
2082 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2083 self.check_attempts()
2087 &self, route: &Route, _payment_id: PaymentId
2088 ) -> Result<(), PaymentSendFailure> {
2089 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2090 self.check_attempts().map(|_| ())
2093 fn abandon_payment(&self, _payment_id: PaymentId) { }
2096 // *** Full Featured Functional Tests with a Real ChannelManager ***
2097 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2099 impl Router for ManualRouter {
2101 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2102 _inflight_htlcs: InFlightHtlcs
2103 ) -> Result<Route, LightningError> {
2104 self.0.borrow_mut().pop_front().unwrap()
2107 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2109 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2111 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2113 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2116 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2117 self.0.borrow_mut().push_back(result);
2120 impl Drop for ManualRouter {
2121 fn drop(&mut self) {
2122 if std::thread::panicking() {
2125 assert!(self.0.borrow_mut().is_empty());
2130 fn retry_multi_path_single_failed_payment() {
2131 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2132 let chanmon_cfgs = create_chanmon_cfgs(2);
2133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2137 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2138 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2139 let chans = nodes[0].node.list_usable_channels();
2140 let mut route = Route {
2143 pubkey: nodes[1].node.get_our_node_id(),
2144 node_features: channelmanager::provided_node_features(),
2145 short_channel_id: chans[0].short_channel_id.unwrap(),
2146 channel_features: channelmanager::provided_channel_features(),
2148 cltv_expiry_delta: 100,
2151 pubkey: nodes[1].node.get_our_node_id(),
2152 node_features: channelmanager::provided_node_features(),
2153 short_channel_id: chans[1].short_channel_id.unwrap(),
2154 channel_features: channelmanager::provided_channel_features(),
2155 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2156 cltv_expiry_delta: 100,
2159 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2161 let router = ManualRouter(RefCell::new(VecDeque::new()));
2162 router.expect_find_route(Ok(route.clone()));
2163 // On retry, split the payment across both channels.
2164 route.paths[0][0].fee_msat = 50_000_001;
2165 route.paths[1][0].fee_msat = 50_000_000;
2166 router.expect_find_route(Ok(route.clone()));
2168 let event_handler = |_: &_| { panic!(); };
2169 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2171 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2172 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2173 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2175 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2176 assert_eq!(htlc_msgs.len(), 2);
2177 check_added_monitors!(nodes[0], 2);
2181 fn immediate_retry_on_failure() {
2182 // Tests that we can/will retry immediately after a failure
2183 let chanmon_cfgs = create_chanmon_cfgs(2);
2184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2186 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2188 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2189 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2190 let chans = nodes[0].node.list_usable_channels();
2191 let mut route = Route {
2194 pubkey: nodes[1].node.get_our_node_id(),
2195 node_features: channelmanager::provided_node_features(),
2196 short_channel_id: chans[0].short_channel_id.unwrap(),
2197 channel_features: channelmanager::provided_channel_features(),
2198 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2199 cltv_expiry_delta: 100,
2202 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2204 let router = ManualRouter(RefCell::new(VecDeque::new()));
2205 router.expect_find_route(Ok(route.clone()));
2206 // On retry, split the payment across both channels.
2207 route.paths.push(route.paths[0].clone());
2208 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2209 route.paths[0][0].fee_msat = 50_000_000;
2210 route.paths[1][0].fee_msat = 50_000_001;
2211 router.expect_find_route(Ok(route.clone()));
2213 let event_handler = |_: &_| { panic!(); };
2214 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2216 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2217 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2218 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2220 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2221 assert_eq!(htlc_msgs.len(), 2);
2222 check_added_monitors!(nodes[0], 2);
2226 fn no_extra_retries_on_back_to_back_fail() {
2227 // In a previous release, we had a race where we may exceed the payment retry count if we
2228 // get two failures in a row with the second having `all_paths_failed` set.
2229 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2230 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2231 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2232 // pending which we will see later. Thus, when we previously removed the retry tracking map
2233 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2234 // retry entry even though more events for the same payment were still pending. This led to
2235 // us retrying a payment again even though we'd already given up on it.
2237 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2238 // is used to remove the payment retry counter entries instead. This tests for the specific
2239 // excess-retry case while also testing `PaymentFailed` generation.
2241 let chanmon_cfgs = create_chanmon_cfgs(3);
2242 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2243 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2244 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2246 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;
2247 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;
2249 let mut route = Route {
2252 pubkey: nodes[1].node.get_our_node_id(),
2253 node_features: channelmanager::provided_node_features(),
2254 short_channel_id: chan_1_scid,
2255 channel_features: channelmanager::provided_channel_features(),
2257 cltv_expiry_delta: 100,
2259 pubkey: nodes[2].node.get_our_node_id(),
2260 node_features: channelmanager::provided_node_features(),
2261 short_channel_id: chan_2_scid,
2262 channel_features: channelmanager::provided_channel_features(),
2263 fee_msat: 100_000_000,
2264 cltv_expiry_delta: 100,
2267 pubkey: nodes[1].node.get_our_node_id(),
2268 node_features: channelmanager::provided_node_features(),
2269 short_channel_id: chan_1_scid,
2270 channel_features: channelmanager::provided_channel_features(),
2272 cltv_expiry_delta: 100,
2274 pubkey: nodes[2].node.get_our_node_id(),
2275 node_features: channelmanager::provided_node_features(),
2276 short_channel_id: chan_2_scid,
2277 channel_features: channelmanager::provided_channel_features(),
2278 fee_msat: 100_000_000,
2279 cltv_expiry_delta: 100,
2282 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2284 let router = ManualRouter(RefCell::new(VecDeque::new()));
2285 router.expect_find_route(Ok(route.clone()));
2286 // On retry, we'll only be asked for one path
2287 route.paths.remove(1);
2288 router.expect_find_route(Ok(route.clone()));
2290 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2291 let event_handler = |event: &Event| {
2292 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2293 event_checker(event);
2295 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2297 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2298 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2299 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2301 let htlc_updates = SendEvent::from_node(&nodes[0]);
2302 check_added_monitors!(nodes[0], 1);
2303 assert_eq!(htlc_updates.msgs.len(), 1);
2305 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2306 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2307 check_added_monitors!(nodes[1], 1);
2308 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2310 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2311 check_added_monitors!(nodes[0], 1);
2312 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2314 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2315 check_added_monitors!(nodes[0], 1);
2316 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2320 check_added_monitors!(nodes[1], 1);
2321 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2323 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2324 check_added_monitors!(nodes[1], 1);
2325 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2327 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2328 check_added_monitors!(nodes[0], 1);
2330 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2331 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2332 check_added_monitors!(nodes[0], 1);
2333 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2335 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2336 check_added_monitors!(nodes[1], 1);
2337 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2339 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2340 check_added_monitors!(nodes[1], 1);
2341 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2343 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2344 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2345 check_added_monitors!(nodes[0], 1);
2347 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2348 check_added_monitors!(nodes[0], 1);
2349 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2351 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2352 check_added_monitors!(nodes[1], 1);
2353 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2354 check_added_monitors!(nodes[1], 1);
2355 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2358 check_added_monitors!(nodes[0], 1);
2360 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2361 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2362 // with it set. The first event will use up the only retry we are allowed, with the second
2363 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2364 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2365 // if the final HTLC failed.
2366 expected_events.borrow_mut().push_back(&|ev: &Event| {
2367 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2368 assert!(!payment_failed_permanently);
2369 assert!(all_paths_failed);
2370 } else { panic!("Unexpected event"); }
2372 nodes[0].node.process_pending_events(&invoice_payer);
2373 assert!(expected_events.borrow().is_empty());
2375 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2376 check_added_monitors!(nodes[0], 1);
2378 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2379 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2380 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2381 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2382 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2384 expected_events.borrow_mut().push_back(&|ev: &Event| {
2385 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2386 assert!(!payment_failed_permanently);
2387 assert!(all_paths_failed);
2388 } else { panic!("Unexpected event"); }
2390 expected_events.borrow_mut().push_back(&|ev: &Event| {
2391 if let Event::PaymentFailed { .. } = ev {
2392 } else { panic!("Unexpected event"); }
2394 nodes[0].node.process_pending_events(&invoice_payer);
2395 assert!(expected_events.borrow().is_empty());