1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] uses its [`Router`] parameterization for optionally notifying scorers upon
19 //! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events.
20 //! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`]
21 //! and [`Event::ProbeSuccessful`].
23 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
24 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
25 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
26 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
27 //! along the events to the user-provided handler.
32 //! # extern crate lightning;
33 //! # extern crate lightning_invoice;
34 //! # extern crate secp256k1;
36 //! # use lightning::io;
37 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
38 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
39 //! # use lightning::ln::msgs::LightningError;
40 //! # use lightning::routing::gossip::NodeId;
41 //! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router};
42 //! # use lightning::routing::scoring::{ChannelUsage, Score};
43 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
44 //! # use lightning::util::logger::{Logger, Record};
45 //! # use lightning::util::ser::{Writeable, Writer};
46 //! # use lightning_invoice::Invoice;
47 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, ScoringRouter};
48 //! # use secp256k1::PublicKey;
49 //! # use std::cell::RefCell;
50 //! # use std::ops::Deref;
52 //! # struct FakeEventProvider {}
53 //! # impl EventsProvider for FakeEventProvider {
54 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
57 //! # struct FakePayer {}
58 //! # impl Payer for FakePayer {
59 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
60 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
61 //! # fn send_payment(
62 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
63 //! # ) -> 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 //! # impl ScoringRouter for FakeRouter {
81 //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
82 //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() }
83 //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() }
84 //! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
101 //! # struct FakeLogger {}
102 //! # impl Logger for FakeLogger {
103 //! # fn log(&self, record: &Record) { unimplemented!() }
107 //! let event_handler = |event: &Event| {
109 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
110 //! Event::PaymentSent { .. } => println!("payment successful"),
114 //! # let payer = FakePayer {};
115 //! # let router = FakeRouter {};
116 //! # let scorer = RefCell::new(FakeScorer {});
117 //! # let logger = FakeLogger {};
118 //! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
120 //! let invoice = "...";
121 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
122 //! invoice_payer.pay_invoice(&invoice).unwrap();
124 //! # let event_provider = FakeEventProvider {};
126 //! event_provider.process_pending_events(&invoice_payer);
134 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
135 //! as updates to the network graph or changes to channel scores should be applied prior to
136 //! retries, typically by way of composing [`EventHandler`]s accordingly.
140 use bitcoin_hashes::Hash;
141 use bitcoin_hashes::sha256::Hash as Sha256;
143 use crate::prelude::*;
144 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
145 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
146 use lightning::ln::msgs::LightningError;
147 use lightning::routing::gossip::NodeId;
148 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router};
149 use lightning::util::errors::APIError;
150 use lightning::util::events::{Event, EventHandler};
151 use lightning::util::logger::Logger;
152 use crate::time_utils::Time;
153 use crate::sync::Mutex;
155 use secp256k1::PublicKey;
158 use core::fmt::{Debug, Display, Formatter};
159 use core::ops::Deref;
160 use core::time::Duration;
161 #[cfg(feature = "std")]
162 use std::time::SystemTime;
164 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
166 /// See [module-level documentation] for details.
168 /// [module-level documentation]: crate::payment
169 pub type InvoicePayer<P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, ConfiguredTime>;
171 #[cfg(not(feature = "no-std"))]
172 type ConfiguredTime = std::time::Instant;
173 #[cfg(feature = "no-std")]
174 use crate::time_utils;
175 #[cfg(feature = "no-std")]
176 type ConfiguredTime = time_utils::Eternity;
178 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
179 pub struct InvoicePayerUsingTime<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time>
188 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
189 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
193 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
194 /// currently being made, or have outstanding paths that need retrying.
195 struct PaymentInfo<T: Time> {
196 attempts: PaymentAttempts<T>,
197 paths: Vec<Vec<RouteHop>>,
200 impl<T: Time> PaymentInfo<T> {
203 attempts: PaymentAttempts::new(),
209 /// Storing minimal payment attempts information required for determining if a outbound payment can
211 #[derive(Clone, Copy)]
212 struct PaymentAttempts<T: Time> {
213 /// This count will be incremented only after the result of the attempt is known. When it's 0,
214 /// it means the result of the first attempt is now known yet.
216 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
217 first_attempted_at: T
220 impl<T: Time> PaymentAttempts<T> {
224 first_attempted_at: T::now()
229 impl<T: Time> Display for PaymentAttempts<T> {
230 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
231 #[cfg(feature = "no-std")]
232 return write!( f, "attempts: {}", self.count);
233 #[cfg(not(feature = "no-std"))]
236 "attempts: {}, duration: {}s",
238 T::now().duration_since(self.first_attempted_at).as_secs()
243 /// A trait defining behavior of an [`Invoice`] payer.
245 /// Returns the payer's node id.
246 fn node_id(&self) -> PublicKey;
248 /// Returns the payer's channels.
249 fn first_hops(&self) -> Vec<ChannelDetails>;
251 /// Sends a payment over the Lightning Network using the given [`Route`].
253 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
254 ) -> Result<PaymentId, PaymentSendFailure>;
256 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
257 fn send_spontaneous_payment(
258 &self, route: &Route, payment_preimage: PaymentPreimage
259 ) -> Result<PaymentId, PaymentSendFailure>;
261 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
262 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
264 /// Signals that no further retries for the given payment will occur.
265 fn abandon_payment(&self, payment_id: PaymentId);
268 /// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
269 /// based on payment and probe success/failure.
271 /// [`Router`]: lightning::routing::router::Router
272 pub trait ScoringRouter: Router {
273 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
274 /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
275 fn find_route_with_id(
276 &self, payer: &PublicKey, route_params: &RouteParameters,
277 first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
278 _payment_hash: PaymentHash, _payment_id: PaymentId
279 ) -> Result<Route, LightningError> {
280 self.find_route(payer, route_params, first_hops, inflight_htlcs)
282 /// Lets the router know that payment through a specific path has failed.
283 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64);
284 /// Lets the router know that payment through a specific path was successful.
285 fn notify_payment_path_successful(&self, path: &[&RouteHop]);
286 /// Lets the router know that a payment probe was successful.
287 fn notify_payment_probe_successful(&self, path: &[&RouteHop]);
288 /// Lets the router know that a payment probe failed.
289 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64);
292 /// Strategies available to retry payment path failures for an [`Invoice`].
294 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
296 /// Max number of attempts to retry payment.
298 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
299 /// payments, if this is less than the total number of paths, we will never even retry all of the
302 #[cfg(feature = "std")]
303 /// Time elapsed before abandoning retries for a payment.
308 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
309 match (self, attempts) {
310 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
311 max_retry_count >= &count
313 #[cfg(feature = "std")]
314 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
315 *max_duration >= T::now().duration_since(*first_attempted_at),
320 /// An error that may occur when making a payment.
321 #[derive(Clone, Debug)]
322 pub enum PaymentError {
323 /// An error resulting from the provided [`Invoice`] or payment hash.
324 Invoice(&'static str),
325 /// An error occurring when finding a route.
326 Routing(LightningError),
327 /// An error occurring when sending a payment.
328 Sending(PaymentSendFailure),
331 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, L, E, T>
336 /// Creates an invoice payer that retries failed payment paths.
338 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
339 /// `retry` has been exceeded for a given [`Invoice`].
341 payer: P, router: R, logger: L, event_handler: E, retry: Retry
348 payment_cache: Mutex::new(HashMap::new()),
353 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
355 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
356 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
358 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
359 if invoice.amount_milli_satoshis().is_none() {
360 Err(PaymentError::Invoice("amount missing"))
362 self.pay_invoice_using_amount(invoice, None)
366 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
367 /// case a retry is needed.
369 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
370 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
372 pub fn pay_zero_value_invoice(
373 &self, invoice: &Invoice, amount_msats: u64
374 ) -> Result<PaymentId, PaymentError> {
375 if invoice.amount_milli_satoshis().is_some() {
376 Err(PaymentError::Invoice("amount unexpected"))
378 self.pay_invoice_using_amount(invoice, Some(amount_msats))
382 fn pay_invoice_using_amount(
383 &self, invoice: &Invoice, amount_msats: Option<u64>
384 ) -> Result<PaymentId, PaymentError> {
385 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
387 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
388 match self.payment_cache.lock().unwrap().entry(payment_hash) {
389 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
390 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
393 let payment_secret = Some(invoice.payment_secret().clone());
394 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
395 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
396 .with_route_hints(invoice.route_hints());
397 if let Some(features) = invoice.features() {
398 payment_params = payment_params.with_features(features.clone());
400 let route_params = RouteParameters {
402 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
403 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
406 let send_payment = |route: &Route| {
407 self.payer.send_payment(route, payment_hash, &payment_secret)
410 self.pay_internal(&route_params, payment_hash, send_payment)
411 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
414 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
415 /// case a retry is needed.
417 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
418 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
420 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
421 final_cltv_expiry_delta: u32
422 ) -> Result<PaymentId, PaymentError> {
423 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
424 match self.payment_cache.lock().unwrap().entry(payment_hash) {
425 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
426 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
429 let route_params = RouteParameters {
430 payment_params: PaymentParameters::for_keysend(pubkey),
431 final_value_msat: amount_msats,
432 final_cltv_expiry_delta,
435 let send_payment = |route: &Route| {
436 self.payer.send_spontaneous_payment(route, payment_preimage)
438 self.pay_internal(&route_params, payment_hash, send_payment)
439 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
442 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
443 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
444 ) -> Result<PaymentId, PaymentError> {
445 #[cfg(feature = "std")] {
446 if has_expired(params) {
447 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
448 return Err(PaymentError::Invoice("Invoice expired prior to send"));
452 let payer = self.payer.node_id();
453 let first_hops = self.payer.first_hops();
454 let inflight_htlcs = self.create_inflight_map();
455 let route = self.router.find_route(
456 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
457 ).map_err(|e| PaymentError::Routing(e))?;
459 match send_payment(&route) {
461 for path in route.paths {
462 self.process_path_inflight_htlcs(payment_hash, path);
467 PaymentSendFailure::ParameterError(_) => Err(e),
468 PaymentSendFailure::PathParameterError(_) => Err(e),
469 PaymentSendFailure::AllFailedRetrySafe(_) => {
470 let mut payment_cache = self.payment_cache.lock().unwrap();
471 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
472 payment_info.attempts.count += 1;
473 if self.retry.is_retryable_now(&payment_info.attempts) {
474 core::mem::drop(payment_cache);
475 Ok(self.pay_internal(params, payment_hash, send_payment)?)
480 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, results } => {
481 // If a `PartialFailure` event returns a result that is an `Ok()`, it means that
482 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
483 // means that we are still waiting for our channel monitor update to be completed.
484 for (result, path) in results.iter().zip(route.paths.into_iter()) {
486 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
487 self.process_path_inflight_htlcs(payment_hash, path);
493 if let Some(retry_data) = failed_paths_retry {
494 // Some paths were sent, even if we failed to send the full MPP value our
495 // recipient may misbehave and claim the funds, at which point we have to
496 // consider the payment sent, so return `Ok()` here, ignoring any retry
498 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
501 // This may happen if we send a payment and some paths fail, but
502 // only due to a temporary monitor failure or the like, implying
503 // they're really in-flight, but we haven't sent the initial
504 // HTLC-Add messages yet.
509 }.map_err(|e| PaymentError::Sending(e))
512 // Takes in a path to have its information stored in `payment_cache`. This is done for paths
513 // that are pending retry.
514 fn process_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: Vec<RouteHop>) {
515 self.payment_cache.lock().unwrap().entry(payment_hash)
516 .or_insert_with(|| PaymentInfo::new())
520 // Find the path we want to remove in `payment_cache`. If it doesn't exist, do nothing.
521 fn remove_path_inflight_htlcs(&self, payment_hash: PaymentHash, path: &Vec<RouteHop>) {
522 self.payment_cache.lock().unwrap().entry(payment_hash)
523 .and_modify(|payment_info| {
524 if let Some(idx) = payment_info.paths.iter().position(|p| p == path) {
525 payment_info.paths.swap_remove(idx);
531 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
532 ) -> Result<(), ()> {
533 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
534 .and_modify(|info| info.attempts.count += 1 )
535 .or_insert_with(|| PaymentInfo {
536 attempts: PaymentAttempts {
538 first_attempted_at: T::now(),
543 if !self.retry.is_retryable_now(&attempts) {
544 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
548 #[cfg(feature = "std")] {
549 if has_expired(params) {
550 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
555 let payer = self.payer.node_id();
556 let first_hops = self.payer.first_hops();
557 let inflight_htlcs = self.create_inflight_map();
559 let route = self.router.find_route(
560 &payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
564 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
568 match self.payer.retry_payment(&route.as_ref().unwrap(), payment_id) {
570 for path in route.unwrap().paths.into_iter() {
571 self.process_path_inflight_htlcs(payment_hash, path);
575 Err(PaymentSendFailure::ParameterError(_)) |
576 Err(PaymentSendFailure::PathParameterError(_)) => {
577 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
580 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
581 self.retry_payment(payment_id, payment_hash, params)
583 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, results, .. }) => {
584 // If a `PartialFailure` error contains a result that is an `Ok()`, it means that
585 // part of our payment is retried. When we receive `MonitorUpdateInProgress`, it
586 // means that we are still waiting for our channel monitor update to complete.
587 for (result, path) in results.iter().zip(route.unwrap().paths.into_iter()) {
589 Ok(_) | Err(APIError::MonitorUpdateInProgress) => {
590 self.process_path_inflight_htlcs(payment_hash, path);
596 if let Some(retry) = failed_paths_retry {
597 // Always return Ok for the same reason as noted in pay_internal.
598 let _ = self.retry_payment(payment_id, payment_hash, &retry);
605 /// Removes the payment cached by the given payment hash.
607 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
608 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
609 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
610 self.payment_cache.lock().unwrap().remove(payment_hash);
613 /// Use path information in the payment_cache to construct a HashMap mapping a channel's short
614 /// channel id and direction to the amount being sent through it.
616 /// This function should be called whenever we need information about currently used up liquidity
618 fn create_inflight_map(&self) -> InFlightHtlcs {
619 let mut total_inflight_map: HashMap<(u64, bool), u64> = HashMap::new();
620 // Make an attempt at finding existing payment information from `payment_cache`. If it
621 // does not exist, it probably is a fresh payment and we can just return an empty
623 for payment_info in self.payment_cache.lock().unwrap().values() {
624 for path in &payment_info.paths {
625 if path.is_empty() { break };
626 // total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
627 // that is held up. However, the `hops` array, which is a path returned by `find_route` in
628 // the router excludes the payer node. In the following lines, the payer's information is
629 // hardcoded with an inflight value of 0 so that we can correctly represent the first hop
630 // in our sliding window of two.
631 let our_node_id: PublicKey = self.payer.node_id();
632 let reversed_hops_with_payer = path.iter().rev().skip(1)
633 .map(|hop| hop.pubkey)
634 .chain(core::iter::once(our_node_id));
635 let mut cumulative_msat = 0;
637 // Taking the reversed vector from above, we zip it with just the reversed hops list to
638 // work "backwards" of the given path, since the last hop's `fee_msat` actually represents
639 // the total amount sent.
640 for (next_hop, prev_hop) in path.iter().rev().zip(reversed_hops_with_payer) {
641 cumulative_msat += next_hop.fee_msat;
643 .entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
644 .and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
645 .or_insert(cumulative_msat);
650 InFlightHtlcs::new(total_inflight_map)
654 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
655 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
658 #[cfg(feature = "std")]
659 fn has_expired(route_params: &RouteParameters) -> bool {
660 if let Some(expiry_time) = route_params.payment_params.expiry_time {
661 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
665 impl<P: Deref, R: ScoringRouter, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, L, E, T>
670 fn handle_event(&self, event: &Event) {
672 Event::PaymentPathFailed { payment_hash, path, .. }
673 | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. }
674 | Event::ProbeSuccessful { payment_hash, path, .. }
675 | Event::ProbeFailed { payment_hash, path, .. } => {
676 self.remove_path_inflight_htlcs(*payment_hash, path);
682 Event::PaymentPathFailed {
683 payment_id, payment_hash, payment_failed_permanently, path, short_channel_id, retry, ..
685 if let Some(short_channel_id) = short_channel_id {
686 let path = path.iter().collect::<Vec<_>>();
687 self.router.notify_payment_path_failed(&path, *short_channel_id)
690 if payment_id.is_none() {
691 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
692 } else if *payment_failed_permanently {
693 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
694 self.payer.abandon_payment(payment_id.unwrap());
695 } else if retry.is_none() {
696 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
697 self.payer.abandon_payment(payment_id.unwrap());
698 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
699 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
702 self.payer.abandon_payment(payment_id.unwrap());
705 Event::PaymentFailed { payment_hash, .. } => {
706 self.remove_cached_payment(&payment_hash);
708 Event::PaymentPathSuccessful { path, .. } => {
709 let path = path.iter().collect::<Vec<_>>();
710 self.router.notify_payment_path_successful(&path);
712 Event::PaymentSent { payment_hash, .. } => {
713 let mut payment_cache = self.payment_cache.lock().unwrap();
714 let attempts = payment_cache
715 .remove(payment_hash)
716 .map_or(1, |payment_info| payment_info.attempts.count + 1);
717 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
719 Event::ProbeSuccessful { payment_hash, path, .. } => {
720 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
721 let path = path.iter().collect::<Vec<_>>();
722 self.router.notify_payment_probe_successful(&path);
724 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
725 if let Some(short_channel_id) = short_channel_id {
726 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
727 let path = path.iter().collect::<Vec<_>>();
728 self.router.notify_payment_probe_failed(&path, *short_channel_id);
734 // Delegate to the decorated event handler unless the payment is retried.
735 self.event_handler.handle_event(event)
742 use crate::{InvoiceBuilder, Currency};
743 use crate::utils::{ScorerAccountingForInFlightHtlcs, create_invoice_from_channelmanager_and_duration_since_epoch};
744 use bitcoin_hashes::sha256::Hash as Sha256;
745 use lightning::ln::PaymentPreimage;
746 use lightning::ln::channelmanager;
747 use lightning::ln::features::{ChannelFeatures, NodeFeatures};
748 use lightning::ln::functional_test_utils::*;
749 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
750 use lightning::routing::gossip::{EffectiveCapacity, NodeId};
751 use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router};
752 use lightning::routing::scoring::{ChannelUsage, LockableScore, Score};
753 use lightning::util::test_utils::TestLogger;
754 use lightning::util::errors::APIError;
755 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
756 use secp256k1::{SecretKey, PublicKey, Secp256k1};
757 use std::cell::RefCell;
758 use std::collections::VecDeque;
759 use std::ops::DerefMut;
760 use std::time::{SystemTime, Duration};
761 use crate::time_utils::tests::SinceEpoch;
762 use crate::DEFAULT_EXPIRY_TIME;
763 use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
765 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
766 let payment_hash = Sha256::hash(&payment_preimage.0);
767 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
769 InvoiceBuilder::new(Currency::Bitcoin)
770 .description("test".into())
771 .payment_hash(payment_hash)
772 .payment_secret(PaymentSecret([0; 32]))
773 .duration_since_epoch(duration_since_epoch())
774 .min_final_cltv_expiry(144)
775 .amount_milli_satoshis(128)
776 .build_signed(|hash| {
777 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
782 fn duration_since_epoch() -> Duration {
783 #[cfg(feature = "std")]
784 let duration_since_epoch =
785 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
786 #[cfg(not(feature = "std"))]
787 let duration_since_epoch = Duration::from_secs(1234567);
791 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
792 let payment_hash = Sha256::hash(&payment_preimage.0);
793 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
795 InvoiceBuilder::new(Currency::Bitcoin)
796 .description("test".into())
797 .payment_hash(payment_hash)
798 .payment_secret(PaymentSecret([0; 32]))
799 .duration_since_epoch(duration_since_epoch())
800 .min_final_cltv_expiry(144)
801 .build_signed(|hash| {
802 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
807 #[cfg(feature = "std")]
808 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
809 let payment_hash = Sha256::hash(&payment_preimage.0);
810 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
811 let duration = duration_since_epoch()
812 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
814 InvoiceBuilder::new(Currency::Bitcoin)
815 .description("test".into())
816 .payment_hash(payment_hash)
817 .payment_secret(PaymentSecret([0; 32]))
818 .duration_since_epoch(duration)
819 .min_final_cltv_expiry(144)
820 .amount_milli_satoshis(128)
821 .build_signed(|hash| {
822 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
827 fn pubkey() -> PublicKey {
828 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
832 fn pays_invoice_on_first_attempt() {
833 let event_handled = core::cell::RefCell::new(false);
834 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
836 let payment_preimage = PaymentPreimage([1; 32]);
837 let invoice = invoice(payment_preimage);
838 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
839 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
841 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
842 let router = TestRouter::new(TestScorer::new());
843 let logger = TestLogger::new();
845 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
847 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
848 assert_eq!(*payer.attempts.borrow(), 1);
850 invoice_payer.handle_event(&Event::PaymentSent {
851 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
853 assert_eq!(*event_handled.borrow(), true);
854 assert_eq!(*payer.attempts.borrow(), 1);
858 fn pays_invoice_on_retry() {
859 let event_handled = core::cell::RefCell::new(false);
860 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
862 let payment_preimage = PaymentPreimage([1; 32]);
863 let invoice = invoice(payment_preimage);
864 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
865 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
867 let payer = TestPayer::new()
868 .expect_send(Amount::ForInvoice(final_value_msat))
869 .expect_send(Amount::OnRetry(final_value_msat / 2));
870 let router = TestRouter::new(TestScorer::new());
871 let logger = TestLogger::new();
873 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
875 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
876 assert_eq!(*payer.attempts.borrow(), 1);
878 let event = Event::PaymentPathFailed {
881 network_update: None,
882 payment_failed_permanently: false,
883 all_paths_failed: false,
884 path: TestRouter::path_for_value(final_value_msat),
885 short_channel_id: None,
886 retry: Some(TestRouter::retry_for_invoice(&invoice)),
888 invoice_payer.handle_event(&event);
889 assert_eq!(*event_handled.borrow(), false);
890 assert_eq!(*payer.attempts.borrow(), 2);
892 invoice_payer.handle_event(&Event::PaymentSent {
893 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
895 assert_eq!(*event_handled.borrow(), true);
896 assert_eq!(*payer.attempts.borrow(), 2);
900 fn pays_invoice_on_partial_failure() {
901 let event_handler = |_: &_| { panic!() };
903 let payment_preimage = PaymentPreimage([1; 32]);
904 let invoice = invoice(payment_preimage);
905 let retry = TestRouter::retry_for_invoice(&invoice);
906 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
908 let payer = TestPayer::new()
909 .fails_with_partial_failure(retry.clone(), OnAttempt(1), None)
910 .fails_with_partial_failure(retry, OnAttempt(2), None)
911 .expect_send(Amount::ForInvoice(final_value_msat))
912 .expect_send(Amount::OnRetry(final_value_msat / 2))
913 .expect_send(Amount::OnRetry(final_value_msat / 2));
914 let router = TestRouter::new(TestScorer::new());
915 let logger = TestLogger::new();
917 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
919 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
923 fn retries_payment_path_for_unknown_payment() {
924 let event_handled = core::cell::RefCell::new(false);
925 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
927 let payment_preimage = PaymentPreimage([1; 32]);
928 let invoice = invoice(payment_preimage);
929 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
930 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
932 let payer = TestPayer::new()
933 .expect_send(Amount::OnRetry(final_value_msat / 2))
934 .expect_send(Amount::OnRetry(final_value_msat / 2));
935 let router = TestRouter::new(TestScorer::new());
936 let logger = TestLogger::new();
938 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
940 let payment_id = Some(PaymentId([1; 32]));
941 let event = Event::PaymentPathFailed {
944 network_update: None,
945 payment_failed_permanently: false,
946 all_paths_failed: false,
947 path: TestRouter::path_for_value(final_value_msat),
948 short_channel_id: None,
949 retry: Some(TestRouter::retry_for_invoice(&invoice)),
951 invoice_payer.handle_event(&event);
952 assert_eq!(*event_handled.borrow(), false);
953 assert_eq!(*payer.attempts.borrow(), 1);
955 invoice_payer.handle_event(&event);
956 assert_eq!(*event_handled.borrow(), false);
957 assert_eq!(*payer.attempts.borrow(), 2);
959 invoice_payer.handle_event(&Event::PaymentSent {
960 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
962 assert_eq!(*event_handled.borrow(), true);
963 assert_eq!(*payer.attempts.borrow(), 2);
967 fn fails_paying_invoice_after_max_retry_counts() {
968 let event_handled = core::cell::RefCell::new(false);
969 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
971 let payment_preimage = PaymentPreimage([1; 32]);
972 let invoice = invoice(payment_preimage);
973 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
975 let payer = TestPayer::new()
976 .expect_send(Amount::ForInvoice(final_value_msat))
977 .expect_send(Amount::OnRetry(final_value_msat / 2))
978 .expect_send(Amount::OnRetry(final_value_msat / 2));
979 let router = TestRouter::new(TestScorer::new());
980 let logger = TestLogger::new();
982 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
984 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
985 assert_eq!(*payer.attempts.borrow(), 1);
987 let event = Event::PaymentPathFailed {
989 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
990 network_update: None,
991 payment_failed_permanently: false,
992 all_paths_failed: true,
993 path: TestRouter::path_for_value(final_value_msat),
994 short_channel_id: None,
995 retry: Some(TestRouter::retry_for_invoice(&invoice)),
997 invoice_payer.handle_event(&event);
998 assert_eq!(*event_handled.borrow(), false);
999 assert_eq!(*payer.attempts.borrow(), 2);
1001 let event = Event::PaymentPathFailed {
1003 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1004 network_update: None,
1005 payment_failed_permanently: false,
1006 all_paths_failed: false,
1007 path: TestRouter::path_for_value(final_value_msat / 2),
1008 short_channel_id: None,
1009 retry: Some(RouteParameters {
1010 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
1013 invoice_payer.handle_event(&event);
1014 assert_eq!(*event_handled.borrow(), false);
1015 assert_eq!(*payer.attempts.borrow(), 3);
1017 invoice_payer.handle_event(&event);
1018 assert_eq!(*event_handled.borrow(), true);
1019 assert_eq!(*payer.attempts.borrow(), 3);
1022 #[cfg(feature = "std")]
1024 fn fails_paying_invoice_after_max_retry_timeout() {
1025 let event_handled = core::cell::RefCell::new(false);
1026 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1028 let payment_preimage = PaymentPreimage([1; 32]);
1029 let invoice = invoice(payment_preimage);
1030 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1032 let payer = TestPayer::new()
1033 .expect_send(Amount::ForInvoice(final_value_msat))
1034 .expect_send(Amount::OnRetry(final_value_msat / 2));
1036 let router = TestRouter::new(TestScorer::new());
1037 let logger = TestLogger::new();
1038 type InvoicePayerUsingSinceEpoch <P, R, L, E> = InvoicePayerUsingTime::<P, R, L, E, SinceEpoch>;
1041 InvoicePayerUsingSinceEpoch::new(&payer, router, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
1043 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1044 assert_eq!(*payer.attempts.borrow(), 1);
1046 let event = Event::PaymentPathFailed {
1048 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1049 network_update: None,
1050 payment_failed_permanently: false,
1051 all_paths_failed: true,
1052 path: TestRouter::path_for_value(final_value_msat),
1053 short_channel_id: None,
1054 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1056 invoice_payer.handle_event(&event);
1057 assert_eq!(*event_handled.borrow(), false);
1058 assert_eq!(*payer.attempts.borrow(), 2);
1060 SinceEpoch::advance(Duration::from_secs(121));
1062 invoice_payer.handle_event(&event);
1063 assert_eq!(*event_handled.borrow(), true);
1064 assert_eq!(*payer.attempts.borrow(), 2);
1068 fn fails_paying_invoice_with_missing_retry_params() {
1069 let event_handled = core::cell::RefCell::new(false);
1070 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1072 let payment_preimage = PaymentPreimage([1; 32]);
1073 let invoice = invoice(payment_preimage);
1074 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1076 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1077 let router = TestRouter::new(TestScorer::new());
1078 let logger = TestLogger::new();
1080 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1082 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1083 assert_eq!(*payer.attempts.borrow(), 1);
1085 let event = Event::PaymentPathFailed {
1087 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1088 network_update: None,
1089 payment_failed_permanently: false,
1090 all_paths_failed: false,
1092 short_channel_id: None,
1095 invoice_payer.handle_event(&event);
1096 assert_eq!(*event_handled.borrow(), true);
1097 assert_eq!(*payer.attempts.borrow(), 1);
1100 // Expiration is checked only in an std environment
1101 #[cfg(feature = "std")]
1103 fn fails_paying_invoice_after_expiration() {
1104 let event_handled = core::cell::RefCell::new(false);
1105 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1107 let payer = TestPayer::new();
1108 let router = TestRouter::new(TestScorer::new());
1109 let logger = TestLogger::new();
1111 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1113 let payment_preimage = PaymentPreimage([1; 32]);
1114 let invoice = expired_invoice(payment_preimage);
1115 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1116 assert_eq!(msg, "Invoice expired prior to send");
1117 } else { panic!("Expected Invoice Error"); }
1120 // Expiration is checked only in an std environment
1121 #[cfg(feature = "std")]
1123 fn fails_retrying_invoice_after_expiration() {
1124 let event_handled = core::cell::RefCell::new(false);
1125 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1127 let payment_preimage = PaymentPreimage([1; 32]);
1128 let invoice = invoice(payment_preimage);
1129 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1131 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1132 let router = TestRouter::new(TestScorer::new());
1133 let logger = TestLogger::new();
1135 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1137 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1138 assert_eq!(*payer.attempts.borrow(), 1);
1140 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1141 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1142 .checked_sub(Duration::from_secs(2)).unwrap()
1143 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1144 let event = Event::PaymentPathFailed {
1146 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1147 network_update: None,
1148 payment_failed_permanently: false,
1149 all_paths_failed: false,
1151 short_channel_id: None,
1152 retry: Some(retry_data),
1154 invoice_payer.handle_event(&event);
1155 assert_eq!(*event_handled.borrow(), true);
1156 assert_eq!(*payer.attempts.borrow(), 1);
1160 fn fails_paying_invoice_after_retry_error() {
1161 let event_handled = core::cell::RefCell::new(false);
1162 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1164 let payment_preimage = PaymentPreimage([1; 32]);
1165 let invoice = invoice(payment_preimage);
1166 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1168 let payer = TestPayer::new()
1169 .fails_on_attempt(2)
1170 .expect_send(Amount::ForInvoice(final_value_msat))
1171 .expect_send(Amount::OnRetry(final_value_msat / 2));
1172 let router = TestRouter::new(TestScorer::new());
1173 let logger = TestLogger::new();
1175 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1177 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1178 assert_eq!(*payer.attempts.borrow(), 1);
1180 let event = Event::PaymentPathFailed {
1182 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1183 network_update: None,
1184 payment_failed_permanently: false,
1185 all_paths_failed: false,
1186 path: TestRouter::path_for_value(final_value_msat / 2),
1187 short_channel_id: None,
1188 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1190 invoice_payer.handle_event(&event);
1191 assert_eq!(*event_handled.borrow(), true);
1192 assert_eq!(*payer.attempts.borrow(), 2);
1196 fn fails_paying_invoice_after_rejected_by_payee() {
1197 let event_handled = core::cell::RefCell::new(false);
1198 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1200 let payment_preimage = PaymentPreimage([1; 32]);
1201 let invoice = invoice(payment_preimage);
1202 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1204 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1205 let router = TestRouter::new(TestScorer::new());
1206 let logger = TestLogger::new();
1208 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1210 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1211 assert_eq!(*payer.attempts.borrow(), 1);
1213 let event = Event::PaymentPathFailed {
1215 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1216 network_update: None,
1217 payment_failed_permanently: true,
1218 all_paths_failed: false,
1220 short_channel_id: None,
1221 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1223 invoice_payer.handle_event(&event);
1224 assert_eq!(*event_handled.borrow(), true);
1225 assert_eq!(*payer.attempts.borrow(), 1);
1229 fn fails_repaying_invoice_with_pending_payment() {
1230 let event_handled = core::cell::RefCell::new(false);
1231 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1233 let payment_preimage = PaymentPreimage([1; 32]);
1234 let invoice = invoice(payment_preimage);
1235 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1237 let payer = TestPayer::new()
1238 .expect_send(Amount::ForInvoice(final_value_msat))
1239 .expect_send(Amount::ForInvoice(final_value_msat));
1240 let router = TestRouter::new(TestScorer::new());
1241 let logger = TestLogger::new();
1243 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1245 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1247 // Cannot repay an invoice pending payment.
1248 match invoice_payer.pay_invoice(&invoice) {
1249 Err(PaymentError::Invoice("payment pending")) => {},
1250 Err(_) => panic!("unexpected error"),
1251 Ok(_) => panic!("expected invoice error"),
1254 // Can repay an invoice once cleared from cache.
1255 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1256 invoice_payer.remove_cached_payment(&payment_hash);
1257 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1259 // Cannot retry paying an invoice if cleared from cache.
1260 invoice_payer.remove_cached_payment(&payment_hash);
1261 let event = Event::PaymentPathFailed {
1264 network_update: None,
1265 payment_failed_permanently: false,
1266 all_paths_failed: false,
1268 short_channel_id: None,
1269 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1271 invoice_payer.handle_event(&event);
1272 assert_eq!(*event_handled.borrow(), true);
1276 fn fails_paying_invoice_with_routing_errors() {
1277 let payer = TestPayer::new();
1278 let router = FailingRouter {};
1279 let logger = TestLogger::new();
1281 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1283 let payment_preimage = PaymentPreimage([1; 32]);
1284 let invoice = invoice(payment_preimage);
1285 match invoice_payer.pay_invoice(&invoice) {
1286 Err(PaymentError::Routing(_)) => {},
1287 Err(_) => panic!("unexpected error"),
1288 Ok(_) => panic!("expected routing error"),
1293 fn fails_paying_invoice_with_sending_errors() {
1294 let payment_preimage = PaymentPreimage([1; 32]);
1295 let invoice = invoice(payment_preimage);
1296 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1298 let payer = TestPayer::new()
1299 .fails_on_attempt(1)
1300 .expect_send(Amount::ForInvoice(final_value_msat));
1301 let router = TestRouter::new(TestScorer::new());
1302 let logger = TestLogger::new();
1304 InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0));
1306 match invoice_payer.pay_invoice(&invoice) {
1307 Err(PaymentError::Sending(_)) => {},
1308 Err(_) => panic!("unexpected error"),
1309 Ok(_) => panic!("expected sending error"),
1314 fn pays_zero_value_invoice_using_amount() {
1315 let event_handled = core::cell::RefCell::new(false);
1316 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1318 let payment_preimage = PaymentPreimage([1; 32]);
1319 let invoice = zero_value_invoice(payment_preimage);
1320 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1321 let final_value_msat = 100;
1323 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1324 let router = TestRouter::new(TestScorer::new());
1325 let logger = TestLogger::new();
1327 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1330 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1331 assert_eq!(*payer.attempts.borrow(), 1);
1333 invoice_payer.handle_event(&Event::PaymentSent {
1334 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1336 assert_eq!(*event_handled.borrow(), true);
1337 assert_eq!(*payer.attempts.borrow(), 1);
1341 fn fails_paying_zero_value_invoice_with_amount() {
1342 let event_handled = core::cell::RefCell::new(false);
1343 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1345 let payer = TestPayer::new();
1346 let router = TestRouter::new(TestScorer::new());
1347 let logger = TestLogger::new();
1349 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1351 let payment_preimage = PaymentPreimage([1; 32]);
1352 let invoice = invoice(payment_preimage);
1354 // Cannot repay an invoice pending payment.
1355 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1356 Err(PaymentError::Invoice("amount unexpected")) => {},
1357 Err(_) => panic!("unexpected error"),
1358 Ok(_) => panic!("expected invoice error"),
1363 fn pays_pubkey_with_amount() {
1364 let event_handled = core::cell::RefCell::new(false);
1365 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1367 let pubkey = pubkey();
1368 let payment_preimage = PaymentPreimage([1; 32]);
1369 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1370 let final_value_msat = 100;
1371 let final_cltv_expiry_delta = 42;
1373 let payer = TestPayer::new()
1374 .expect_send(Amount::Spontaneous(final_value_msat))
1375 .expect_send(Amount::OnRetry(final_value_msat));
1376 let router = TestRouter::new(TestScorer::new());
1377 let logger = TestLogger::new();
1379 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1381 let payment_id = Some(invoice_payer.pay_pubkey(
1382 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1384 assert_eq!(*payer.attempts.borrow(), 1);
1386 let retry = RouteParameters {
1387 payment_params: PaymentParameters::for_keysend(pubkey),
1389 final_cltv_expiry_delta,
1391 let event = Event::PaymentPathFailed {
1394 network_update: None,
1395 payment_failed_permanently: false,
1396 all_paths_failed: false,
1398 short_channel_id: None,
1401 invoice_payer.handle_event(&event);
1402 assert_eq!(*event_handled.borrow(), false);
1403 assert_eq!(*payer.attempts.borrow(), 2);
1405 invoice_payer.handle_event(&Event::PaymentSent {
1406 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1408 assert_eq!(*event_handled.borrow(), true);
1409 assert_eq!(*payer.attempts.borrow(), 2);
1413 fn scores_failed_channel() {
1414 let event_handled = core::cell::RefCell::new(false);
1415 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1417 let payment_preimage = PaymentPreimage([1; 32]);
1418 let invoice = invoice(payment_preimage);
1419 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1420 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1421 let path = TestRouter::path_for_value(final_value_msat);
1422 let short_channel_id = Some(path[0].short_channel_id);
1424 // Expect that scorer is given short_channel_id upon handling the event.
1425 let payer = TestPayer::new()
1426 .expect_send(Amount::ForInvoice(final_value_msat))
1427 .expect_send(Amount::OnRetry(final_value_msat / 2));
1428 let scorer = TestScorer::new().expect(TestResult::PaymentFailure {
1429 path: path.clone(), short_channel_id: path[0].short_channel_id,
1431 let router = TestRouter::new(scorer);
1432 let logger = TestLogger::new();
1434 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1436 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1437 let event = Event::PaymentPathFailed {
1440 network_update: None,
1441 payment_failed_permanently: false,
1442 all_paths_failed: false,
1445 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1447 invoice_payer.handle_event(&event);
1451 fn scores_successful_channels() {
1452 let event_handled = core::cell::RefCell::new(false);
1453 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1455 let payment_preimage = PaymentPreimage([1; 32]);
1456 let invoice = invoice(payment_preimage);
1457 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1458 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1459 let route = TestRouter::route_for_value(final_value_msat);
1461 // Expect that scorer is given short_channel_id upon handling the event.
1462 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1463 let scorer = TestScorer::new()
1464 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1465 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() });
1466 let router = TestRouter::new(scorer);
1467 let logger = TestLogger::new();
1469 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1471 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1472 let event = Event::PaymentPathSuccessful {
1473 payment_id, payment_hash, path: route.paths[0].clone()
1475 invoice_payer.handle_event(&event);
1476 let event = Event::PaymentPathSuccessful {
1477 payment_id, payment_hash, path: route.paths[1].clone()
1479 invoice_payer.handle_event(&event);
1483 fn generates_correct_inflight_map_data() {
1484 let event_handled = core::cell::RefCell::new(false);
1485 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1487 let payment_preimage = PaymentPreimage([1; 32]);
1488 let invoice = invoice(payment_preimage);
1489 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1490 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1492 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1493 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1494 let route = TestRouter::route_for_value(final_value_msat);
1495 let router = TestRouter::new(TestScorer::new());
1496 let logger = TestLogger::new();
1498 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1500 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1502 let inflight_map = invoice_payer.create_inflight_map();
1504 assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1505 assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1506 assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1508 // Second path check
1509 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1510 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1512 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1513 payment_id, payment_hash, path: route.paths[0].clone()
1516 let inflight_map = invoice_payer.create_inflight_map();
1518 assert_eq!(inflight_map.0.get(&(0, false)), None);
1519 assert_eq!(inflight_map.0.get(&(1, true)), None);
1520 assert_eq!(inflight_map.0.get(&(2, false)), None);
1522 // Second path should still be inflight
1523 assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1524 assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1528 fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1529 // First, let's just send a payment through, but only make sure one of the path completes
1530 let event_handled = core::cell::RefCell::new(false);
1531 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1533 let payment_preimage = PaymentPreimage([1; 32]);
1534 let payment_invoice = invoice(payment_preimage);
1535 let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
1536 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1538 let payer = TestPayer::new()
1539 .expect_send(Amount::ForInvoice(final_value_msat))
1540 .expect_send(Amount::ForInvoice(final_value_msat));
1541 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1542 let route = TestRouter::route_for_value(final_value_msat);
1543 let scorer = TestScorer::new()
1544 // 1st invoice, 1st path
1545 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1546 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1547 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1548 // 1st invoice, 2nd path
1549 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1550 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1551 // 2nd invoice, 1st path
1552 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1553 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1554 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1555 // 2nd invoice, 2nd path
1556 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1557 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
1558 let router = TestRouter::new(scorer);
1559 let logger = TestLogger::new();
1561 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1563 // Succeed 1st path, leave 2nd path inflight
1564 let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1565 invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1566 payment_id, payment_hash, path: route.paths[0].clone()
1569 // Let's pay a second invoice that will be using the same path. This should trigger the
1570 // assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1571 // Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1572 // have 64 msats inflight for paths considering the channel with scid of 1.
1573 let payment_preimage_2 = PaymentPreimage([2; 32]);
1574 let payment_invoice_2 = invoice(payment_preimage_2);
1575 invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
1579 fn considers_inflight_htlcs_between_retries() {
1580 // First, let's just send a payment through, but only make sure one of the path completes
1581 let event_handled = core::cell::RefCell::new(false);
1582 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1584 let payment_preimage = PaymentPreimage([1; 32]);
1585 let payment_invoice = invoice(payment_preimage);
1586 let payment_hash = PaymentHash(payment_invoice.payment_hash().clone().into_inner());
1587 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1589 let payer = TestPayer::new()
1590 .expect_send(Amount::ForInvoice(final_value_msat))
1591 .expect_send(Amount::OnRetry(final_value_msat / 2))
1592 .expect_send(Amount::OnRetry(final_value_msat / 4));
1593 let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1594 let scorer = TestScorer::new()
1595 // 1st invoice, 1st path
1596 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1597 .expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1598 .expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1599 // 1st invoice, 2nd path
1600 .expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1601 .expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1602 // Retry 1, 1st path
1603 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1604 .expect_usage(ChannelUsage { amount_msat: 52, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1605 .expect_usage(ChannelUsage { amount_msat: 62, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1606 // Retry 1, 2nd path
1607 .expect_usage(ChannelUsage { amount_msat: 32, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1608 .expect_usage(ChannelUsage { amount_msat: 42, inflight_htlc_msat: 64 + 10, effective_capacity: EffectiveCapacity::Unknown } )
1609 // Retry 2, 1st path
1610 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1611 .expect_usage(ChannelUsage { amount_msat: 36, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1612 .expect_usage(ChannelUsage { amount_msat: 46, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1613 // Retry 2, 2nd path
1614 .expect_usage(ChannelUsage { amount_msat: 16, inflight_htlc_msat: 64 + 32, effective_capacity: EffectiveCapacity::Unknown } )
1615 .expect_usage(ChannelUsage { amount_msat: 26, inflight_htlc_msat: 74 + 32 + 10, effective_capacity: EffectiveCapacity::Unknown } );
1616 let router = TestRouter::new(scorer);
1617 let logger = TestLogger::new();
1619 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2));
1621 // Fail 1st path, leave 2nd path inflight
1622 let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1623 invoice_payer.handle_event(&Event::PaymentPathFailed {
1626 network_update: None,
1627 payment_failed_permanently: false,
1628 all_paths_failed: false,
1629 path: TestRouter::path_for_value(final_value_msat),
1630 short_channel_id: None,
1631 retry: Some(TestRouter::retry_for_invoice(&payment_invoice)),
1634 // Fails again the 1st path of our retry
1635 invoice_payer.handle_event(&Event::PaymentPathFailed {
1638 network_update: None,
1639 payment_failed_permanently: false,
1640 all_paths_failed: false,
1641 path: TestRouter::path_for_value(final_value_msat / 2),
1642 short_channel_id: None,
1643 retry: Some(RouteParameters {
1644 final_value_msat: final_value_msat / 4,
1645 ..TestRouter::retry_for_invoice(&payment_invoice)
1651 fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1652 let event_handled = core::cell::RefCell::new(false);
1653 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1655 let payment_preimage = PaymentPreimage([1; 32]);
1656 let invoice_to_pay = invoice(payment_preimage);
1657 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1659 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1660 let payer = TestPayer::new()
1661 .fails_with_partial_failure(
1662 retry.clone(), OnAttempt(1),
1664 Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1666 .expect_send(Amount::ForInvoice(final_value_msat));
1668 let router = TestRouter::new(TestScorer::new());
1669 let logger = TestLogger::new();
1671 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1673 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1674 let inflight_map = invoice_payer.create_inflight_map();
1676 // Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1677 // inflight map because retries are disabled.
1678 assert_eq!(inflight_map.0.len(), 2);
1682 fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1683 let event_handled = core::cell::RefCell::new(false);
1684 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1686 let payment_preimage = PaymentPreimage([1; 32]);
1687 let invoice_to_pay = invoice(payment_preimage);
1688 let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1690 let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1691 let payer = TestPayer::new()
1692 .fails_with_partial_failure(
1693 retry.clone(), OnAttempt(1),
1695 Ok(()), Err(MonitorUpdateInProgress)
1697 .expect_send(Amount::ForInvoice(final_value_msat));
1699 let router = TestRouter::new(TestScorer::new());
1700 let logger = TestLogger::new();
1702 InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1704 invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1705 let inflight_map = invoice_payer.create_inflight_map();
1707 // All paths successful, hence we check of the existence of all 5 hops.
1708 assert_eq!(inflight_map.0.len(), 5);
1712 scorer: RefCell<TestScorer>,
1716 fn new(scorer: TestScorer) -> Self {
1717 TestRouter { scorer: RefCell::new(scorer) }
1720 fn route_for_value(final_value_msat: u64) -> Route {
1725 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1726 channel_features: ChannelFeatures::empty(),
1727 node_features: NodeFeatures::empty(),
1728 short_channel_id: 0,
1730 cltv_expiry_delta: 0
1733 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1734 channel_features: ChannelFeatures::empty(),
1735 node_features: NodeFeatures::empty(),
1736 short_channel_id: 1,
1738 cltv_expiry_delta: 0
1741 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1742 channel_features: ChannelFeatures::empty(),
1743 node_features: NodeFeatures::empty(),
1744 short_channel_id: 2,
1745 fee_msat: final_value_msat / 2,
1746 cltv_expiry_delta: 0
1751 pubkey: PublicKey::from_slice(&hex::decode("029e03a901b85534ff1e92c43c74431f7ce72046060fcf7a95c37e148f78c77255").unwrap()[..]).unwrap(),
1752 channel_features: ChannelFeatures::empty(),
1753 node_features: NodeFeatures::empty(),
1754 short_channel_id: 3,
1756 cltv_expiry_delta: 144
1759 pubkey: PublicKey::from_slice(&hex::decode("027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007").unwrap()[..]).unwrap(),
1760 channel_features: ChannelFeatures::empty(),
1761 node_features: NodeFeatures::empty(),
1762 short_channel_id: 4,
1763 fee_msat: final_value_msat / 2,
1764 cltv_expiry_delta: 144
1768 payment_params: None,
1772 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1773 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1776 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1777 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1778 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1779 .with_route_hints(invoice.route_hints());
1780 if let Some(features) = invoice.features() {
1781 payment_params = payment_params.with_features(features.clone());
1783 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1787 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1792 impl Router for TestRouter {
1794 &self, payer: &PublicKey, route_params: &RouteParameters,
1795 _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
1796 ) -> Result<Route, LightningError> {
1797 // Simulate calling the Scorer just as you would in find_route
1798 let route = Self::route_for_value(route_params.final_value_msat);
1799 let mut locked_scorer = self.scorer.lock();
1800 let scorer = ScorerAccountingForInFlightHtlcs::new(locked_scorer.deref_mut(), inflight_htlcs);
1801 for path in route.paths {
1802 let mut aggregate_msat = 0u64;
1803 for (idx, hop) in path.iter().rev().enumerate() {
1804 aggregate_msat += hop.fee_msat;
1805 let usage = ChannelUsage {
1806 amount_msat: aggregate_msat,
1807 inflight_htlc_msat: 0,
1808 effective_capacity: EffectiveCapacity::Unknown,
1811 // Since the path is reversed, the last element in our iteration is the first
1813 if idx == path.len() - 1 {
1814 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(payer), &NodeId::from_pubkey(&hop.pubkey), usage);
1816 scorer.channel_penalty_msat(hop.short_channel_id, &NodeId::from_pubkey(&path[idx + 1].pubkey), &NodeId::from_pubkey(&hop.pubkey), usage);
1822 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1827 impl ScoringRouter for TestRouter {
1828 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1829 self.scorer.lock().payment_path_failed(path, short_channel_id);
1832 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
1833 self.scorer.lock().payment_path_successful(path);
1836 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
1837 self.scorer.lock().probe_successful(path);
1840 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
1841 self.scorer.lock().probe_failed(path, short_channel_id);
1845 struct FailingRouter;
1847 impl Router for FailingRouter {
1849 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
1850 _inflight_htlcs: InFlightHtlcs,
1851 ) -> Result<Route, LightningError> {
1852 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1856 impl ScoringRouter for FailingRouter {
1857 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1859 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
1861 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
1863 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
1867 event_expectations: Option<VecDeque<TestResult>>,
1868 scorer_expectations: RefCell<Option<VecDeque<ChannelUsage>>>,
1873 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1874 PaymentSuccess { path: Vec<RouteHop> },
1880 event_expectations: None,
1881 scorer_expectations: RefCell::new(None),
1885 fn expect(mut self, expectation: TestResult) -> Self {
1886 self.event_expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1890 fn expect_usage(self, expectation: ChannelUsage) -> Self {
1891 self.scorer_expectations.borrow_mut().get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1897 impl lightning::util::ser::Writeable for TestScorer {
1898 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), lightning::io::Error> { unreachable!(); }
1901 impl Score for TestScorer {
1902 fn channel_penalty_msat(
1903 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, usage: ChannelUsage
1905 if let Some(scorer_expectations) = self.scorer_expectations.borrow_mut().as_mut() {
1906 match scorer_expectations.pop_front() {
1907 Some(expectation) => {
1908 assert_eq!(expectation.amount_msat, usage.amount_msat);
1909 assert_eq!(expectation.inflight_htlc_msat, usage.inflight_htlc_msat);
1917 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1918 if let Some(expectations) = &mut self.event_expectations {
1919 match expectations.pop_front() {
1920 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1921 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1922 assert_eq!(actual_short_channel_id, short_channel_id);
1924 Some(TestResult::PaymentSuccess { path }) => {
1925 panic!("Unexpected successful payment path: {:?}", path)
1927 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1932 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1933 if let Some(expectations) = &mut self.event_expectations {
1934 match expectations.pop_front() {
1935 Some(TestResult::PaymentFailure { path, .. }) => {
1936 panic!("Unexpected payment path failure: {:?}", path)
1938 Some(TestResult::PaymentSuccess { path }) => {
1939 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1941 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1946 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1947 if let Some(expectations) = &mut self.event_expectations {
1948 match expectations.pop_front() {
1949 Some(TestResult::PaymentFailure { path, .. }) => {
1950 panic!("Unexpected failed payment path: {:?}", path)
1952 Some(TestResult::PaymentSuccess { path }) => {
1953 panic!("Unexpected successful payment path: {:?}", path)
1955 None => panic!("Unexpected notify_payment_path_failed call: {:?}", actual_path),
1959 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1960 if let Some(expectations) = &mut self.event_expectations {
1961 match expectations.pop_front() {
1962 Some(TestResult::PaymentFailure { path, .. }) => {
1963 panic!("Unexpected payment path failure: {:?}", path)
1965 Some(TestResult::PaymentSuccess { path }) => {
1966 panic!("Unexpected successful payment path: {:?}", path)
1968 None => panic!("Unexpected notify_payment_path_successful call: {:?}", actual_path),
1974 impl Drop for TestScorer {
1975 fn drop(&mut self) {
1976 if std::thread::panicking() {
1980 if let Some(event_expectations) = &self.event_expectations {
1981 if !event_expectations.is_empty() {
1982 panic!("Unsatisfied event expectations: {:?}", event_expectations);
1986 if let Some(scorer_expectations) = self.scorer_expectations.borrow().as_ref() {
1987 if !scorer_expectations.is_empty() {
1988 panic!("Unsatisfied scorer expectations: {:?}", scorer_expectations)
1995 expectations: core::cell::RefCell<VecDeque<Amount>>,
1996 attempts: core::cell::RefCell<usize>,
1997 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2000 #[derive(Clone, Debug, PartialEq, Eq)]
2007 struct OnAttempt(usize);
2012 expectations: core::cell::RefCell::new(VecDeque::new()),
2013 attempts: core::cell::RefCell::new(0),
2014 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2018 fn expect_send(self, value_msat: Amount) -> Self {
2019 self.expectations.borrow_mut().push_back(value_msat);
2023 fn fails_on_attempt(self, attempt: usize) -> Self {
2024 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateInProgress);
2025 self.fails_with(failure, OnAttempt(attempt))
2028 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt, results: Option<Vec<Result<(), APIError>>>) -> Self {
2029 self.fails_with(PaymentSendFailure::PartialFailure {
2030 results: results.unwrap_or(vec![]),
2031 failed_paths_retry: Some(retry),
2032 payment_id: PaymentId([1; 32]),
2036 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
2037 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
2041 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
2042 let mut attempts = self.attempts.borrow_mut();
2045 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
2046 Some(failure) => Err(failure),
2047 None => Ok(PaymentId([1; 32])),
2051 fn check_value_msats(&self, actual_value_msats: Amount) {
2052 let expected_value_msats = self.expectations.borrow_mut().pop_front();
2053 if let Some(expected_value_msats) = expected_value_msats {
2054 assert_eq!(actual_value_msats, expected_value_msats);
2056 panic!("Unexpected amount: {:?}", actual_value_msats);
2061 impl Drop for TestPayer {
2062 fn drop(&mut self) {
2063 if std::thread::panicking() {
2067 if !self.expectations.borrow().is_empty() {
2068 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
2073 impl Payer for TestPayer {
2074 fn node_id(&self) -> PublicKey {
2075 let secp_ctx = Secp256k1::new();
2076 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
2079 fn first_hops(&self) -> Vec<ChannelDetails> {
2084 &self, route: &Route, _payment_hash: PaymentHash,
2085 _payment_secret: &Option<PaymentSecret>
2086 ) -> Result<PaymentId, PaymentSendFailure> {
2087 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2088 self.check_attempts()
2091 fn send_spontaneous_payment(
2092 &self, route: &Route, _payment_preimage: PaymentPreimage,
2093 ) -> Result<PaymentId, PaymentSendFailure> {
2094 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
2095 self.check_attempts()
2099 &self, route: &Route, _payment_id: PaymentId
2100 ) -> Result<(), PaymentSendFailure> {
2101 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2102 self.check_attempts().map(|_| ())
2105 fn abandon_payment(&self, _payment_id: PaymentId) { }
2108 // *** Full Featured Functional Tests with a Real ChannelManager ***
2109 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
2111 impl Router for ManualRouter {
2113 &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
2114 _inflight_htlcs: InFlightHtlcs
2115 ) -> Result<Route, LightningError> {
2116 self.0.borrow_mut().pop_front().unwrap()
2119 impl ScoringRouter for ManualRouter {
2120 fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2122 fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {}
2124 fn notify_payment_probe_successful(&self, _path: &[&RouteHop]) {}
2126 fn notify_payment_probe_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {}
2129 fn expect_find_route(&self, result: Result<Route, LightningError>) {
2130 self.0.borrow_mut().push_back(result);
2133 impl Drop for ManualRouter {
2134 fn drop(&mut self) {
2135 if std::thread::panicking() {
2138 assert!(self.0.borrow_mut().is_empty());
2143 fn retry_multi_path_single_failed_payment() {
2144 // Tests that we can/will retry after a single path of an MPP payment failed immediately
2145 let chanmon_cfgs = create_chanmon_cfgs(2);
2146 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2147 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2148 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2150 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2151 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2152 let chans = nodes[0].node.list_usable_channels();
2153 let mut route = Route {
2156 pubkey: nodes[1].node.get_our_node_id(),
2157 node_features: channelmanager::provided_node_features(),
2158 short_channel_id: chans[0].short_channel_id.unwrap(),
2159 channel_features: channelmanager::provided_channel_features(),
2161 cltv_expiry_delta: 100,
2164 pubkey: nodes[1].node.get_our_node_id(),
2165 node_features: channelmanager::provided_node_features(),
2166 short_channel_id: chans[1].short_channel_id.unwrap(),
2167 channel_features: channelmanager::provided_channel_features(),
2168 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2169 cltv_expiry_delta: 100,
2172 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2174 let router = ManualRouter(RefCell::new(VecDeque::new()));
2175 router.expect_find_route(Ok(route.clone()));
2176 // On retry, split the payment across both channels.
2177 route.paths[0][0].fee_msat = 50_000_001;
2178 route.paths[1][0].fee_msat = 50_000_000;
2179 router.expect_find_route(Ok(route.clone()));
2181 let event_handler = |_: &_| { panic!(); };
2182 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2184 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2185 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2186 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2188 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2189 assert_eq!(htlc_msgs.len(), 2);
2190 check_added_monitors!(nodes[0], 2);
2194 fn immediate_retry_on_failure() {
2195 // Tests that we can/will retry immediately after a failure
2196 let chanmon_cfgs = create_chanmon_cfgs(2);
2197 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2198 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
2199 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2201 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2202 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
2203 let chans = nodes[0].node.list_usable_channels();
2204 let mut route = Route {
2207 pubkey: nodes[1].node.get_our_node_id(),
2208 node_features: channelmanager::provided_node_features(),
2209 short_channel_id: chans[0].short_channel_id.unwrap(),
2210 channel_features: channelmanager::provided_channel_features(),
2211 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
2212 cltv_expiry_delta: 100,
2215 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
2217 let router = ManualRouter(RefCell::new(VecDeque::new()));
2218 router.expect_find_route(Ok(route.clone()));
2219 // On retry, split the payment across both channels.
2220 route.paths.push(route.paths[0].clone());
2221 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
2222 route.paths[0][0].fee_msat = 50_000_000;
2223 route.paths[1][0].fee_msat = 50_000_001;
2224 router.expect_find_route(Ok(route.clone()));
2226 let event_handler = |_: &_| { panic!(); };
2227 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2229 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2230 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2231 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2233 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
2234 assert_eq!(htlc_msgs.len(), 2);
2235 check_added_monitors!(nodes[0], 2);
2239 fn no_extra_retries_on_back_to_back_fail() {
2240 // In a previous release, we had a race where we may exceed the payment retry count if we
2241 // get two failures in a row with the second having `all_paths_failed` set.
2242 // Generally, when we give up trying to retry a payment, we don't know for sure what the
2243 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
2244 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
2245 // pending which we will see later. Thus, when we previously removed the retry tracking map
2246 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
2247 // retry entry even though more events for the same payment were still pending. This led to
2248 // us retrying a payment again even though we'd already given up on it.
2250 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
2251 // is used to remove the payment retry counter entries instead. This tests for the specific
2252 // excess-retry case while also testing `PaymentFailed` generation.
2254 let chanmon_cfgs = create_chanmon_cfgs(3);
2255 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2256 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2257 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2259 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;
2260 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;
2262 let mut route = Route {
2265 pubkey: nodes[1].node.get_our_node_id(),
2266 node_features: channelmanager::provided_node_features(),
2267 short_channel_id: chan_1_scid,
2268 channel_features: channelmanager::provided_channel_features(),
2270 cltv_expiry_delta: 100,
2272 pubkey: nodes[2].node.get_our_node_id(),
2273 node_features: channelmanager::provided_node_features(),
2274 short_channel_id: chan_2_scid,
2275 channel_features: channelmanager::provided_channel_features(),
2276 fee_msat: 100_000_000,
2277 cltv_expiry_delta: 100,
2280 pubkey: nodes[1].node.get_our_node_id(),
2281 node_features: channelmanager::provided_node_features(),
2282 short_channel_id: chan_1_scid,
2283 channel_features: channelmanager::provided_channel_features(),
2285 cltv_expiry_delta: 100,
2287 pubkey: nodes[2].node.get_our_node_id(),
2288 node_features: channelmanager::provided_node_features(),
2289 short_channel_id: chan_2_scid,
2290 channel_features: channelmanager::provided_channel_features(),
2291 fee_msat: 100_000_000,
2292 cltv_expiry_delta: 100,
2295 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
2297 let router = ManualRouter(RefCell::new(VecDeque::new()));
2298 router.expect_find_route(Ok(route.clone()));
2299 // On retry, we'll only be asked for one path
2300 route.paths.remove(1);
2301 router.expect_find_route(Ok(route.clone()));
2303 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
2304 let event_handler = |event: &Event| {
2305 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
2306 event_checker(event);
2308 let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1));
2310 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
2311 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::Bitcoin,
2312 Some(100_010_000), "Invoice".to_string(), duration_since_epoch(), 3600).unwrap())
2314 let htlc_updates = SendEvent::from_node(&nodes[0]);
2315 check_added_monitors!(nodes[0], 1);
2316 assert_eq!(htlc_updates.msgs.len(), 1);
2318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
2319 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
2320 check_added_monitors!(nodes[1], 1);
2321 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2323 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
2324 check_added_monitors!(nodes[0], 1);
2325 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
2327 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
2328 check_added_monitors!(nodes[0], 1);
2329 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2331 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
2332 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
2333 check_added_monitors!(nodes[1], 1);
2334 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2336 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
2337 check_added_monitors!(nodes[1], 1);
2338 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2340 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
2341 check_added_monitors!(nodes[0], 1);
2343 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2344 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
2345 check_added_monitors!(nodes[0], 1);
2346 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2348 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
2349 check_added_monitors!(nodes[1], 1);
2350 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2352 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
2353 check_added_monitors!(nodes[1], 1);
2354 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2356 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
2357 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
2358 check_added_monitors!(nodes[0], 1);
2360 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
2361 check_added_monitors!(nodes[0], 1);
2362 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2364 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
2365 check_added_monitors!(nodes[1], 1);
2366 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
2367 check_added_monitors!(nodes[1], 1);
2368 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2370 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
2371 check_added_monitors!(nodes[0], 1);
2373 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
2374 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
2375 // with it set. The first event will use up the only retry we are allowed, with the second
2376 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
2377 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
2378 // if the final HTLC failed.
2379 expected_events.borrow_mut().push_back(&|ev: &Event| {
2380 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2381 assert!(!payment_failed_permanently);
2382 assert!(all_paths_failed);
2383 } else { panic!("Unexpected event"); }
2385 nodes[0].node.process_pending_events(&invoice_payer);
2386 assert!(expected_events.borrow().is_empty());
2388 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
2389 check_added_monitors!(nodes[0], 1);
2391 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
2392 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
2393 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2394 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
2395 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
2397 expected_events.borrow_mut().push_back(&|ev: &Event| {
2398 if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev {
2399 assert!(!payment_failed_permanently);
2400 assert!(all_paths_failed);
2401 } else { panic!("Unexpected event"); }
2403 expected_events.borrow_mut().push_back(&|ev: &Event| {
2404 if let Event::PaymentFailed { .. } = ev {
2405 } else { panic!("Unexpected event"); }
2407 nodes[0].node.process_pending_events(&invoice_payer);
2408 assert!(expected_events.borrow().is_empty());