1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
19 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
20 //! [`Event::PaymentPathSuccessful`] events, respectively.
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
35 //! # #[cfg(feature = "no-std")]
36 //! # extern crate core2;
38 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
39 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
40 //! # use lightning::ln::msgs::LightningError;
41 //! # use lightning::routing::gossip::NodeId;
42 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
43 //! # use lightning::routing::scoring::{ChannelUsage, Score};
44 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # use lightning::util::ser::{Writeable, Writer};
47 //! # use lightning_invoice::Invoice;
48 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, Router};
49 //! # use secp256k1::PublicKey;
50 //! # use std::cell::RefCell;
51 //! # use std::ops::Deref;
53 //! # #[cfg(not(feature = "std"))]
55 //! # #[cfg(feature = "std")]
58 //! # struct FakeEventProvider {}
59 //! # impl EventsProvider for FakeEventProvider {
60 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
63 //! # struct FakePayer {}
64 //! # impl Payer for FakePayer {
65 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
66 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
67 //! # fn send_payment(
68 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
69 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
70 //! # fn send_spontaneous_payment(
71 //! # &self, route: &Route, payment_preimage: PaymentPreimage
72 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
73 //! # fn retry_payment(
74 //! # &self, route: &Route, payment_id: PaymentId
75 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
76 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
79 //! # struct FakeRouter {}
80 //! # impl<S: Score> Router<S> for FakeRouter {
82 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
83 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
84 //! # ) -> Result<Route, LightningError> { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
99 //! # struct FakeLogger {}
100 //! # impl Logger for FakeLogger {
101 //! # fn log(&self, record: &Record) { unimplemented!() }
105 //! let event_handler = |event: &Event| {
107 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
108 //! Event::PaymentSent { .. } => println!("payment successful"),
112 //! # let payer = FakePayer {};
113 //! # let router = FakeRouter {};
114 //! # let scorer = RefCell::new(FakeScorer {});
115 //! # let logger = FakeLogger {};
116 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
118 //! let invoice = "...";
119 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
120 //! invoice_payer.pay_invoice(&invoice).unwrap();
122 //! # let event_provider = FakeEventProvider {};
124 //! event_provider.process_pending_events(&invoice_payer);
132 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
133 //! as updates to the network graph or changes to channel scores should be applied prior to
134 //! retries, typically by way of composing [`EventHandler`]s accordingly.
138 use bitcoin_hashes::Hash;
139 use bitcoin_hashes::sha256::Hash as Sha256;
141 use crate::prelude::*;
142 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
143 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
144 use lightning::ln::msgs::LightningError;
145 use lightning::routing::scoring::{LockableScore, MultiThreadedLockableScore, Score};
146 use lightning::routing::router::{PaymentParameters, Route, RouteParameters};
147 use lightning::util::events::{Event, EventHandler};
148 use lightning::util::logger::Logger;
149 use time_utils::Time;
150 use crate::sync::Mutex;
152 use secp256k1::PublicKey;
155 use core::fmt::{Debug, Display, Formatter};
156 use core::ops::Deref;
157 use core::time::Duration;
158 #[cfg(feature = "std")]
159 use std::time::SystemTime;
161 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
163 /// See [module-level documentation] for details.
165 /// [module-level documentation]: crate::payment
166 pub type InvoicePayer<P, S, R, SR, L, E> = InvoicePayerUsingTime::<P, S, R, SR, L, E, ConfiguredTime>;
168 #[cfg(not(feature = "no-std"))]
169 type ConfiguredTime = std::time::Instant;
170 #[cfg(feature = "no-std")]
172 #[cfg(feature = "no-std")]
173 type ConfiguredTime = time_utils::Eternity;
175 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
176 pub struct InvoicePayerUsingTime<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler, T: Time>
179 R::Target: Router<S>,
187 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
188 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
192 /// Storing minimal payment attempts information required for determining if a outbound payment can
194 #[derive(Clone, Copy)]
195 struct PaymentAttempts<T: Time> {
196 /// This count will be incremented only after the result of the attempt is known. When it's 0,
197 /// it means the result of the first attempt is now known yet.
199 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
200 first_attempted_at: T
203 impl<T: Time> PaymentAttempts<T> {
207 first_attempted_at: T::now()
212 impl<T: Time> Display for PaymentAttempts<T> {
213 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
214 #[cfg(feature = "no-std")]
215 return write!( f, "attempts: {}", self.count);
216 #[cfg(not(feature = "no-std"))]
219 "attempts: {}, duration: {}s",
221 T::now().duration_since(self.first_attempted_at).as_secs()
226 /// A trait defining behavior of an [`Invoice`] payer.
228 /// Returns the payer's node id.
229 fn node_id(&self) -> PublicKey;
231 /// Returns the payer's channels.
232 fn first_hops(&self) -> Vec<ChannelDetails>;
234 /// Sends a payment over the Lightning Network using the given [`Route`].
236 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
237 ) -> Result<PaymentId, PaymentSendFailure>;
239 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
240 fn send_spontaneous_payment(
241 &self, route: &Route, payment_preimage: PaymentPreimage
242 ) -> Result<PaymentId, PaymentSendFailure>;
244 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
245 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
247 /// Signals that no further retries for the given payment will occur.
248 fn abandon_payment(&self, payment_id: PaymentId);
251 /// A trait defining behavior for routing an [`Invoice`] payment.
252 pub trait Router<S: Score> {
253 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
255 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
256 first_hops: Option<&[&ChannelDetails]>, scorer: &S
257 ) -> Result<Route, LightningError>;
260 /// Strategies available to retry payment path failures for an [`Invoice`].
262 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
264 /// Max number of attempts to retry payment.
266 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
267 /// payments, if this is less than the total number of paths, we will never even retry all of the
270 #[cfg(feature = "std")]
271 /// Time elapsed before abandoning retries for a payment.
276 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
277 match (self, attempts) {
278 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
279 max_retry_count >= &count
281 #[cfg(feature = "std")]
282 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
283 *max_duration >= T::now().duration_since(*first_attempted_at),
288 /// An error that may occur when making a payment.
289 #[derive(Clone, Debug)]
290 pub enum PaymentError {
291 /// An error resulting from the provided [`Invoice`] or payment hash.
292 Invoice(&'static str),
293 /// An error occurring when finding a route.
294 Routing(LightningError),
295 /// An error occurring when sending a payment.
296 Sending(PaymentSendFailure),
299 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, S, R, SR, L, E, T>
302 R::Target: Router<S>,
305 /// Creates an invoice payer that retries failed payment paths.
307 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
308 /// `retry` has been exceeded for a given [`Invoice`].
310 payer: P, router: R, scorer: SR, logger: L, event_handler: E, retry: Retry
318 payment_cache: Mutex::new(HashMap::new()),
323 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
325 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
326 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
328 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
329 if invoice.amount_milli_satoshis().is_none() {
330 Err(PaymentError::Invoice("amount missing"))
332 self.pay_invoice_using_amount(invoice, None)
336 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
337 /// case a retry is needed.
339 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
340 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
342 pub fn pay_zero_value_invoice(
343 &self, invoice: &Invoice, amount_msats: u64
344 ) -> Result<PaymentId, PaymentError> {
345 if invoice.amount_milli_satoshis().is_some() {
346 Err(PaymentError::Invoice("amount unexpected"))
348 self.pay_invoice_using_amount(invoice, Some(amount_msats))
352 fn pay_invoice_using_amount(
353 &self, invoice: &Invoice, amount_msats: Option<u64>
354 ) -> Result<PaymentId, PaymentError> {
355 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
357 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
358 match self.payment_cache.lock().unwrap().entry(payment_hash) {
359 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
360 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
363 let payment_secret = Some(invoice.payment_secret().clone());
364 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
365 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
366 .with_route_hints(invoice.route_hints());
367 if let Some(features) = invoice.features() {
368 payment_params = payment_params.with_features(features.clone());
370 let route_params = RouteParameters {
372 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
373 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
376 let send_payment = |route: &Route| {
377 self.payer.send_payment(route, payment_hash, &payment_secret)
380 self.pay_internal(&route_params, payment_hash, send_payment)
381 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
384 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
385 /// case a retry is needed.
387 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
388 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
390 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
391 final_cltv_expiry_delta: u32
392 ) -> Result<PaymentId, PaymentError> {
393 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
394 match self.payment_cache.lock().unwrap().entry(payment_hash) {
395 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
396 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
399 let route_params = RouteParameters {
400 payment_params: PaymentParameters::for_keysend(pubkey),
401 final_value_msat: amount_msats,
402 final_cltv_expiry_delta,
405 let send_payment = |route: &Route| {
406 self.payer.send_spontaneous_payment(route, payment_preimage)
408 self.pay_internal(&route_params, payment_hash, send_payment)
409 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
412 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
413 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
414 ) -> Result<PaymentId, PaymentError> {
415 #[cfg(feature = "std")] {
416 if has_expired(params) {
417 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
418 return Err(PaymentError::Invoice("Invoice expired prior to send"));
422 let payer = self.payer.node_id();
423 let first_hops = self.payer.first_hops();
424 let route = self.router.find_route(
425 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
427 ).map_err(|e| PaymentError::Routing(e))?;
429 match send_payment(&route) {
430 Ok(payment_id) => Ok(payment_id),
432 PaymentSendFailure::ParameterError(_) => Err(e),
433 PaymentSendFailure::PathParameterError(_) => Err(e),
434 PaymentSendFailure::AllFailedRetrySafe(_) => {
435 let mut payment_cache = self.payment_cache.lock().unwrap();
436 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
437 payment_attempts.count += 1;
438 if self.retry.is_retryable_now(payment_attempts) {
439 core::mem::drop(payment_cache);
440 Ok(self.pay_internal(params, payment_hash, send_payment)?)
445 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
446 if let Some(retry_data) = failed_paths_retry {
447 // Some paths were sent, even if we failed to send the full MPP value our
448 // recipient may misbehave and claim the funds, at which point we have to
449 // consider the payment sent, so return `Ok()` here, ignoring any retry
451 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
454 // This may happen if we send a payment and some paths fail, but
455 // only due to a temporary monitor failure or the like, implying
456 // they're really in-flight, but we haven't sent the initial
457 // HTLC-Add messages yet.
462 }.map_err(|e| PaymentError::Sending(e))
466 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
467 ) -> Result<(), ()> {
469 *self.payment_cache.lock().unwrap().entry(payment_hash)
470 .and_modify(|attempts| attempts.count += 1)
471 .or_insert(PaymentAttempts {
473 first_attempted_at: T::now()
476 if !self.retry.is_retryable_now(&attempts) {
477 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
481 #[cfg(feature = "std")] {
482 if has_expired(params) {
483 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
488 let payer = self.payer.node_id();
489 let first_hops = self.payer.first_hops();
490 let route = self.router.find_route(
491 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
495 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
499 match self.payer.retry_payment(&route.unwrap(), payment_id) {
501 Err(PaymentSendFailure::ParameterError(_)) |
502 Err(PaymentSendFailure::PathParameterError(_)) => {
503 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
506 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
507 self.retry_payment(payment_id, payment_hash, params)
509 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
510 if let Some(retry) = failed_paths_retry {
511 // Always return Ok for the same reason as noted in pay_internal.
512 let _ = self.retry_payment(payment_id, payment_hash, &retry);
519 /// Removes the payment cached by the given payment hash.
521 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
522 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
523 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
524 self.payment_cache.lock().unwrap().remove(payment_hash);
528 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
529 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
532 #[cfg(feature = "std")]
533 fn has_expired(route_params: &RouteParameters) -> bool {
534 if let Some(expiry_time) = route_params.payment_params.expiry_time {
535 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
539 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, S, R, SR, L, E, T>
542 R::Target: Router<S>,
545 fn handle_event(&self, event: &Event) {
547 Event::PaymentPathFailed {
548 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
550 if let Some(short_channel_id) = short_channel_id {
551 let path = path.iter().collect::<Vec<_>>();
552 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
555 if payment_id.is_none() {
556 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
557 } else if *rejected_by_dest {
558 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
559 self.payer.abandon_payment(payment_id.unwrap());
560 } else if retry.is_none() {
561 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
562 self.payer.abandon_payment(payment_id.unwrap());
563 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
564 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
567 self.payer.abandon_payment(payment_id.unwrap());
570 Event::PaymentFailed { payment_hash, .. } => {
571 self.remove_cached_payment(&payment_hash);
573 Event::PaymentPathSuccessful { path, .. } => {
574 let path = path.iter().collect::<Vec<_>>();
575 self.scorer.lock().payment_path_successful(&path);
577 Event::PaymentSent { payment_hash, .. } => {
578 let mut payment_cache = self.payment_cache.lock().unwrap();
579 let attempts = payment_cache
580 .remove(payment_hash)
581 .map_or(1, |attempts| attempts.count + 1);
582 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
587 // Delegate to the decorated event handler unless the payment is retried.
588 self.event_handler.handle_event(event)
595 use crate::{InvoiceBuilder, Currency};
596 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
597 use bitcoin_hashes::sha256::Hash as Sha256;
598 use lightning::ln::PaymentPreimage;
599 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
600 use lightning::ln::functional_test_utils::*;
601 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
602 use lightning::routing::gossip::NodeId;
603 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
604 use lightning::routing::scoring::ChannelUsage;
605 use lightning::util::test_utils::TestLogger;
606 use lightning::util::errors::APIError;
607 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
608 use secp256k1::{SecretKey, PublicKey, Secp256k1};
609 use std::cell::RefCell;
610 use std::collections::VecDeque;
611 use std::time::{SystemTime, Duration};
612 use time_utils::tests::SinceEpoch;
613 use DEFAULT_EXPIRY_TIME;
615 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
616 let payment_hash = Sha256::hash(&payment_preimage.0);
617 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
619 InvoiceBuilder::new(Currency::Bitcoin)
620 .description("test".into())
621 .payment_hash(payment_hash)
622 .payment_secret(PaymentSecret([0; 32]))
623 .duration_since_epoch(duration_since_epoch())
624 .min_final_cltv_expiry(144)
625 .amount_milli_satoshis(128)
626 .build_signed(|hash| {
627 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
632 fn duration_since_epoch() -> Duration {
633 #[cfg(feature = "std")]
634 let duration_since_epoch =
635 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
636 #[cfg(not(feature = "std"))]
637 let duration_since_epoch = Duration::from_secs(1234567);
641 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
642 let payment_hash = Sha256::hash(&payment_preimage.0);
643 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
645 InvoiceBuilder::new(Currency::Bitcoin)
646 .description("test".into())
647 .payment_hash(payment_hash)
648 .payment_secret(PaymentSecret([0; 32]))
649 .duration_since_epoch(duration_since_epoch())
650 .min_final_cltv_expiry(144)
651 .build_signed(|hash| {
652 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
657 #[cfg(feature = "std")]
658 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
659 let payment_hash = Sha256::hash(&payment_preimage.0);
660 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
661 let duration = duration_since_epoch()
662 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
664 InvoiceBuilder::new(Currency::Bitcoin)
665 .description("test".into())
666 .payment_hash(payment_hash)
667 .payment_secret(PaymentSecret([0; 32]))
668 .duration_since_epoch(duration)
669 .min_final_cltv_expiry(144)
670 .amount_milli_satoshis(128)
671 .build_signed(|hash| {
672 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
677 fn pubkey() -> PublicKey {
678 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
682 fn pays_invoice_on_first_attempt() {
683 let event_handled = core::cell::RefCell::new(false);
684 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
686 let payment_preimage = PaymentPreimage([1; 32]);
687 let invoice = invoice(payment_preimage);
688 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
689 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
691 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
692 let router = TestRouter {};
693 let scorer = RefCell::new(TestScorer::new());
694 let logger = TestLogger::new();
696 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
698 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
699 assert_eq!(*payer.attempts.borrow(), 1);
701 invoice_payer.handle_event(&Event::PaymentSent {
702 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
704 assert_eq!(*event_handled.borrow(), true);
705 assert_eq!(*payer.attempts.borrow(), 1);
709 fn pays_invoice_on_retry() {
710 let event_handled = core::cell::RefCell::new(false);
711 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
713 let payment_preimage = PaymentPreimage([1; 32]);
714 let invoice = invoice(payment_preimage);
715 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
716 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
718 let payer = TestPayer::new()
719 .expect_send(Amount::ForInvoice(final_value_msat))
720 .expect_send(Amount::OnRetry(final_value_msat / 2));
721 let router = TestRouter {};
722 let scorer = RefCell::new(TestScorer::new());
723 let logger = TestLogger::new();
725 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
727 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
728 assert_eq!(*payer.attempts.borrow(), 1);
730 let event = Event::PaymentPathFailed {
733 network_update: None,
734 rejected_by_dest: false,
735 all_paths_failed: false,
736 path: TestRouter::path_for_value(final_value_msat),
737 short_channel_id: None,
738 retry: Some(TestRouter::retry_for_invoice(&invoice)),
740 invoice_payer.handle_event(&event);
741 assert_eq!(*event_handled.borrow(), false);
742 assert_eq!(*payer.attempts.borrow(), 2);
744 invoice_payer.handle_event(&Event::PaymentSent {
745 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
747 assert_eq!(*event_handled.borrow(), true);
748 assert_eq!(*payer.attempts.borrow(), 2);
752 fn pays_invoice_on_partial_failure() {
753 let event_handler = |_: &_| { panic!() };
755 let payment_preimage = PaymentPreimage([1; 32]);
756 let invoice = invoice(payment_preimage);
757 let retry = TestRouter::retry_for_invoice(&invoice);
758 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
760 let payer = TestPayer::new()
761 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
762 .fails_with_partial_failure(retry, OnAttempt(2))
763 .expect_send(Amount::ForInvoice(final_value_msat))
764 .expect_send(Amount::OnRetry(final_value_msat / 2))
765 .expect_send(Amount::OnRetry(final_value_msat / 2));
766 let router = TestRouter {};
767 let scorer = RefCell::new(TestScorer::new());
768 let logger = TestLogger::new();
770 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
772 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
776 fn retries_payment_path_for_unknown_payment() {
777 let event_handled = core::cell::RefCell::new(false);
778 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
780 let payment_preimage = PaymentPreimage([1; 32]);
781 let invoice = invoice(payment_preimage);
782 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
783 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
785 let payer = TestPayer::new()
786 .expect_send(Amount::OnRetry(final_value_msat / 2))
787 .expect_send(Amount::OnRetry(final_value_msat / 2));
788 let router = TestRouter {};
789 let scorer = RefCell::new(TestScorer::new());
790 let logger = TestLogger::new();
792 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
794 let payment_id = Some(PaymentId([1; 32]));
795 let event = Event::PaymentPathFailed {
798 network_update: None,
799 rejected_by_dest: false,
800 all_paths_failed: false,
801 path: TestRouter::path_for_value(final_value_msat),
802 short_channel_id: None,
803 retry: Some(TestRouter::retry_for_invoice(&invoice)),
805 invoice_payer.handle_event(&event);
806 assert_eq!(*event_handled.borrow(), false);
807 assert_eq!(*payer.attempts.borrow(), 1);
809 invoice_payer.handle_event(&event);
810 assert_eq!(*event_handled.borrow(), false);
811 assert_eq!(*payer.attempts.borrow(), 2);
813 invoice_payer.handle_event(&Event::PaymentSent {
814 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
816 assert_eq!(*event_handled.borrow(), true);
817 assert_eq!(*payer.attempts.borrow(), 2);
821 fn fails_paying_invoice_after_max_retry_counts() {
822 let event_handled = core::cell::RefCell::new(false);
823 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
825 let payment_preimage = PaymentPreimage([1; 32]);
826 let invoice = invoice(payment_preimage);
827 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
829 let payer = TestPayer::new()
830 .expect_send(Amount::ForInvoice(final_value_msat))
831 .expect_send(Amount::OnRetry(final_value_msat / 2))
832 .expect_send(Amount::OnRetry(final_value_msat / 2));
833 let router = TestRouter {};
834 let scorer = RefCell::new(TestScorer::new());
835 let logger = TestLogger::new();
837 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
839 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
840 assert_eq!(*payer.attempts.borrow(), 1);
842 let event = Event::PaymentPathFailed {
844 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
845 network_update: None,
846 rejected_by_dest: false,
847 all_paths_failed: true,
848 path: TestRouter::path_for_value(final_value_msat),
849 short_channel_id: None,
850 retry: Some(TestRouter::retry_for_invoice(&invoice)),
852 invoice_payer.handle_event(&event);
853 assert_eq!(*event_handled.borrow(), false);
854 assert_eq!(*payer.attempts.borrow(), 2);
856 let event = Event::PaymentPathFailed {
858 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
859 network_update: None,
860 rejected_by_dest: false,
861 all_paths_failed: false,
862 path: TestRouter::path_for_value(final_value_msat / 2),
863 short_channel_id: None,
864 retry: Some(RouteParameters {
865 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
868 invoice_payer.handle_event(&event);
869 assert_eq!(*event_handled.borrow(), false);
870 assert_eq!(*payer.attempts.borrow(), 3);
872 invoice_payer.handle_event(&event);
873 assert_eq!(*event_handled.borrow(), true);
874 assert_eq!(*payer.attempts.borrow(), 3);
877 #[cfg(feature = "std")]
879 fn fails_paying_invoice_after_max_retry_timeout() {
880 let event_handled = core::cell::RefCell::new(false);
881 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
883 let payment_preimage = PaymentPreimage([1; 32]);
884 let invoice = invoice(payment_preimage);
885 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
887 let payer = TestPayer::new()
888 .expect_send(Amount::ForInvoice(final_value_msat))
889 .expect_send(Amount::OnRetry(final_value_msat / 2));
891 let router = TestRouter {};
892 let scorer = RefCell::new(TestScorer::new());
893 let logger = TestLogger::new();
894 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
897 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
899 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
900 assert_eq!(*payer.attempts.borrow(), 1);
902 let event = Event::PaymentPathFailed {
904 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
905 network_update: None,
906 rejected_by_dest: false,
907 all_paths_failed: true,
908 path: TestRouter::path_for_value(final_value_msat),
909 short_channel_id: None,
910 retry: Some(TestRouter::retry_for_invoice(&invoice)),
912 invoice_payer.handle_event(&event);
913 assert_eq!(*event_handled.borrow(), false);
914 assert_eq!(*payer.attempts.borrow(), 2);
916 SinceEpoch::advance(Duration::from_secs(121));
918 invoice_payer.handle_event(&event);
919 assert_eq!(*event_handled.borrow(), true);
920 assert_eq!(*payer.attempts.borrow(), 2);
924 fn fails_paying_invoice_with_missing_retry_params() {
925 let event_handled = core::cell::RefCell::new(false);
926 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
928 let payment_preimage = PaymentPreimage([1; 32]);
929 let invoice = invoice(payment_preimage);
930 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
932 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
933 let router = TestRouter {};
934 let scorer = RefCell::new(TestScorer::new());
935 let logger = TestLogger::new();
937 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
939 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
940 assert_eq!(*payer.attempts.borrow(), 1);
942 let event = Event::PaymentPathFailed {
944 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
945 network_update: None,
946 rejected_by_dest: false,
947 all_paths_failed: false,
949 short_channel_id: None,
952 invoice_payer.handle_event(&event);
953 assert_eq!(*event_handled.borrow(), true);
954 assert_eq!(*payer.attempts.borrow(), 1);
957 // Expiration is checked only in an std environment
958 #[cfg(feature = "std")]
960 fn fails_paying_invoice_after_expiration() {
961 let event_handled = core::cell::RefCell::new(false);
962 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
964 let payer = TestPayer::new();
965 let router = TestRouter {};
966 let scorer = RefCell::new(TestScorer::new());
967 let logger = TestLogger::new();
969 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
971 let payment_preimage = PaymentPreimage([1; 32]);
972 let invoice = expired_invoice(payment_preimage);
973 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
974 assert_eq!(msg, "Invoice expired prior to send");
975 } else { panic!("Expected Invoice Error"); }
978 // Expiration is checked only in an std environment
979 #[cfg(feature = "std")]
981 fn fails_retrying_invoice_after_expiration() {
982 let event_handled = core::cell::RefCell::new(false);
983 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
985 let payment_preimage = PaymentPreimage([1; 32]);
986 let invoice = invoice(payment_preimage);
987 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
989 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
990 let router = TestRouter {};
991 let scorer = RefCell::new(TestScorer::new());
992 let logger = TestLogger::new();
994 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
996 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
997 assert_eq!(*payer.attempts.borrow(), 1);
999 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1000 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1001 .checked_sub(Duration::from_secs(2)).unwrap()
1002 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1003 let event = Event::PaymentPathFailed {
1005 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1006 network_update: None,
1007 rejected_by_dest: false,
1008 all_paths_failed: false,
1010 short_channel_id: None,
1011 retry: Some(retry_data),
1013 invoice_payer.handle_event(&event);
1014 assert_eq!(*event_handled.borrow(), true);
1015 assert_eq!(*payer.attempts.borrow(), 1);
1019 fn fails_paying_invoice_after_retry_error() {
1020 let event_handled = core::cell::RefCell::new(false);
1021 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1023 let payment_preimage = PaymentPreimage([1; 32]);
1024 let invoice = invoice(payment_preimage);
1025 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1027 let payer = TestPayer::new()
1028 .fails_on_attempt(2)
1029 .expect_send(Amount::ForInvoice(final_value_msat))
1030 .expect_send(Amount::OnRetry(final_value_msat / 2));
1031 let router = TestRouter {};
1032 let scorer = RefCell::new(TestScorer::new());
1033 let logger = TestLogger::new();
1035 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1037 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1038 assert_eq!(*payer.attempts.borrow(), 1);
1040 let event = Event::PaymentPathFailed {
1042 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1043 network_update: None,
1044 rejected_by_dest: false,
1045 all_paths_failed: false,
1046 path: TestRouter::path_for_value(final_value_msat / 2),
1047 short_channel_id: None,
1048 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1050 invoice_payer.handle_event(&event);
1051 assert_eq!(*event_handled.borrow(), true);
1052 assert_eq!(*payer.attempts.borrow(), 2);
1056 fn fails_paying_invoice_after_rejected_by_payee() {
1057 let event_handled = core::cell::RefCell::new(false);
1058 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1060 let payment_preimage = PaymentPreimage([1; 32]);
1061 let invoice = invoice(payment_preimage);
1062 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1064 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1065 let router = TestRouter {};
1066 let scorer = RefCell::new(TestScorer::new());
1067 let logger = TestLogger::new();
1069 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1071 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1072 assert_eq!(*payer.attempts.borrow(), 1);
1074 let event = Event::PaymentPathFailed {
1076 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1077 network_update: None,
1078 rejected_by_dest: true,
1079 all_paths_failed: false,
1081 short_channel_id: None,
1082 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1084 invoice_payer.handle_event(&event);
1085 assert_eq!(*event_handled.borrow(), true);
1086 assert_eq!(*payer.attempts.borrow(), 1);
1090 fn fails_repaying_invoice_with_pending_payment() {
1091 let event_handled = core::cell::RefCell::new(false);
1092 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1094 let payment_preimage = PaymentPreimage([1; 32]);
1095 let invoice = invoice(payment_preimage);
1096 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1098 let payer = TestPayer::new()
1099 .expect_send(Amount::ForInvoice(final_value_msat))
1100 .expect_send(Amount::ForInvoice(final_value_msat));
1101 let router = TestRouter {};
1102 let scorer = RefCell::new(TestScorer::new());
1103 let logger = TestLogger::new();
1105 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1107 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1109 // Cannot repay an invoice pending payment.
1110 match invoice_payer.pay_invoice(&invoice) {
1111 Err(PaymentError::Invoice("payment pending")) => {},
1112 Err(_) => panic!("unexpected error"),
1113 Ok(_) => panic!("expected invoice error"),
1116 // Can repay an invoice once cleared from cache.
1117 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1118 invoice_payer.remove_cached_payment(&payment_hash);
1119 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1121 // Cannot retry paying an invoice if cleared from cache.
1122 invoice_payer.remove_cached_payment(&payment_hash);
1123 let event = Event::PaymentPathFailed {
1126 network_update: None,
1127 rejected_by_dest: false,
1128 all_paths_failed: false,
1130 short_channel_id: None,
1131 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1133 invoice_payer.handle_event(&event);
1134 assert_eq!(*event_handled.borrow(), true);
1138 fn fails_paying_invoice_with_routing_errors() {
1139 let payer = TestPayer::new();
1140 let router = FailingRouter {};
1141 let scorer = RefCell::new(TestScorer::new());
1142 let logger = TestLogger::new();
1144 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1146 let payment_preimage = PaymentPreimage([1; 32]);
1147 let invoice = invoice(payment_preimage);
1148 match invoice_payer.pay_invoice(&invoice) {
1149 Err(PaymentError::Routing(_)) => {},
1150 Err(_) => panic!("unexpected error"),
1151 Ok(_) => panic!("expected routing error"),
1156 fn fails_paying_invoice_with_sending_errors() {
1157 let payment_preimage = PaymentPreimage([1; 32]);
1158 let invoice = invoice(payment_preimage);
1159 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1161 let payer = TestPayer::new()
1162 .fails_on_attempt(1)
1163 .expect_send(Amount::ForInvoice(final_value_msat));
1164 let router = TestRouter {};
1165 let scorer = RefCell::new(TestScorer::new());
1166 let logger = TestLogger::new();
1168 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1170 match invoice_payer.pay_invoice(&invoice) {
1171 Err(PaymentError::Sending(_)) => {},
1172 Err(_) => panic!("unexpected error"),
1173 Ok(_) => panic!("expected sending error"),
1178 fn pays_zero_value_invoice_using_amount() {
1179 let event_handled = core::cell::RefCell::new(false);
1180 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1182 let payment_preimage = PaymentPreimage([1; 32]);
1183 let invoice = zero_value_invoice(payment_preimage);
1184 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1185 let final_value_msat = 100;
1187 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1188 let router = TestRouter {};
1189 let scorer = RefCell::new(TestScorer::new());
1190 let logger = TestLogger::new();
1192 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1195 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1196 assert_eq!(*payer.attempts.borrow(), 1);
1198 invoice_payer.handle_event(&Event::PaymentSent {
1199 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1201 assert_eq!(*event_handled.borrow(), true);
1202 assert_eq!(*payer.attempts.borrow(), 1);
1206 fn fails_paying_zero_value_invoice_with_amount() {
1207 let event_handled = core::cell::RefCell::new(false);
1208 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1210 let payer = TestPayer::new();
1211 let router = TestRouter {};
1212 let scorer = RefCell::new(TestScorer::new());
1213 let logger = TestLogger::new();
1215 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1217 let payment_preimage = PaymentPreimage([1; 32]);
1218 let invoice = invoice(payment_preimage);
1220 // Cannot repay an invoice pending payment.
1221 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1222 Err(PaymentError::Invoice("amount unexpected")) => {},
1223 Err(_) => panic!("unexpected error"),
1224 Ok(_) => panic!("expected invoice error"),
1229 fn pays_pubkey_with_amount() {
1230 let event_handled = core::cell::RefCell::new(false);
1231 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1233 let pubkey = pubkey();
1234 let payment_preimage = PaymentPreimage([1; 32]);
1235 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1236 let final_value_msat = 100;
1237 let final_cltv_expiry_delta = 42;
1239 let payer = TestPayer::new()
1240 .expect_send(Amount::Spontaneous(final_value_msat))
1241 .expect_send(Amount::OnRetry(final_value_msat));
1242 let router = TestRouter {};
1243 let scorer = RefCell::new(TestScorer::new());
1244 let logger = TestLogger::new();
1246 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1248 let payment_id = Some(invoice_payer.pay_pubkey(
1249 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1251 assert_eq!(*payer.attempts.borrow(), 1);
1253 let retry = RouteParameters {
1254 payment_params: PaymentParameters::for_keysend(pubkey),
1256 final_cltv_expiry_delta,
1258 let event = Event::PaymentPathFailed {
1261 network_update: None,
1262 rejected_by_dest: false,
1263 all_paths_failed: false,
1265 short_channel_id: None,
1268 invoice_payer.handle_event(&event);
1269 assert_eq!(*event_handled.borrow(), false);
1270 assert_eq!(*payer.attempts.borrow(), 2);
1272 invoice_payer.handle_event(&Event::PaymentSent {
1273 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1275 assert_eq!(*event_handled.borrow(), true);
1276 assert_eq!(*payer.attempts.borrow(), 2);
1280 fn scores_failed_channel() {
1281 let event_handled = core::cell::RefCell::new(false);
1282 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1284 let payment_preimage = PaymentPreimage([1; 32]);
1285 let invoice = invoice(payment_preimage);
1286 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1287 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1288 let path = TestRouter::path_for_value(final_value_msat);
1289 let short_channel_id = Some(path[0].short_channel_id);
1291 // Expect that scorer is given short_channel_id upon handling the event.
1292 let payer = TestPayer::new()
1293 .expect_send(Amount::ForInvoice(final_value_msat))
1294 .expect_send(Amount::OnRetry(final_value_msat / 2));
1295 let router = TestRouter {};
1296 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1297 path: path.clone(), short_channel_id: path[0].short_channel_id,
1299 let logger = TestLogger::new();
1301 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1303 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1304 let event = Event::PaymentPathFailed {
1307 network_update: None,
1308 rejected_by_dest: false,
1309 all_paths_failed: false,
1312 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1314 invoice_payer.handle_event(&event);
1318 fn scores_successful_channels() {
1319 let event_handled = core::cell::RefCell::new(false);
1320 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1322 let payment_preimage = PaymentPreimage([1; 32]);
1323 let invoice = invoice(payment_preimage);
1324 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1325 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1326 let route = TestRouter::route_for_value(final_value_msat);
1328 // Expect that scorer is given short_channel_id upon handling the event.
1329 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1330 let router = TestRouter {};
1331 let scorer = RefCell::new(TestScorer::new()
1332 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1333 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1335 let logger = TestLogger::new();
1337 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1339 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1340 let event = Event::PaymentPathSuccessful {
1341 payment_id, payment_hash, path: route.paths[0].clone()
1343 invoice_payer.handle_event(&event);
1344 let event = Event::PaymentPathSuccessful {
1345 payment_id, payment_hash, path: route.paths[1].clone()
1347 invoice_payer.handle_event(&event);
1353 fn route_for_value(final_value_msat: u64) -> Route {
1357 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1358 channel_features: ChannelFeatures::empty(),
1359 node_features: NodeFeatures::empty(),
1360 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1363 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1364 channel_features: ChannelFeatures::empty(),
1365 node_features: NodeFeatures::empty(),
1366 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1369 payment_params: None,
1373 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1374 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1377 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1378 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1379 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1380 .with_route_hints(invoice.route_hints());
1381 if let Some(features) = invoice.features() {
1382 payment_params = payment_params.with_features(features.clone());
1384 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1388 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1393 impl<S: Score> Router<S> for TestRouter {
1395 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1396 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1397 ) -> Result<Route, LightningError> {
1399 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1404 struct FailingRouter;
1406 impl<S: Score> Router<S> for FailingRouter {
1408 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1409 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1410 ) -> Result<Route, LightningError> {
1411 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1416 expectations: Option<VecDeque<PaymentPath>>,
1421 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1422 Success { path: Vec<RouteHop> },
1432 fn expect(mut self, expectation: PaymentPath) -> Self {
1433 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1439 impl lightning::util::ser::Writeable for TestScorer {
1440 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1443 impl Score for TestScorer {
1444 fn channel_penalty_msat(
1445 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
1448 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1449 if let Some(expectations) = &mut self.expectations {
1450 match expectations.pop_front() {
1451 Some(PaymentPath::Failure { path, short_channel_id }) => {
1452 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1453 assert_eq!(actual_short_channel_id, short_channel_id);
1455 Some(PaymentPath::Success { path }) => {
1456 panic!("Unexpected successful payment path: {:?}", path)
1458 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1463 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1464 if let Some(expectations) = &mut self.expectations {
1465 match expectations.pop_front() {
1466 Some(PaymentPath::Failure { path, .. }) => {
1467 panic!("Unexpected payment path failure: {:?}", path)
1469 Some(PaymentPath::Success { path }) => {
1470 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1472 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1478 impl Drop for TestScorer {
1479 fn drop(&mut self) {
1480 if std::thread::panicking() {
1484 if let Some(expectations) = &self.expectations {
1485 if !expectations.is_empty() {
1486 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1493 expectations: core::cell::RefCell<VecDeque<Amount>>,
1494 attempts: core::cell::RefCell<usize>,
1495 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1498 #[derive(Clone, Debug, PartialEq, Eq)]
1505 struct OnAttempt(usize);
1510 expectations: core::cell::RefCell::new(VecDeque::new()),
1511 attempts: core::cell::RefCell::new(0),
1512 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1516 fn expect_send(self, value_msat: Amount) -> Self {
1517 self.expectations.borrow_mut().push_back(value_msat);
1521 fn fails_on_attempt(self, attempt: usize) -> Self {
1522 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1523 self.fails_with(failure, OnAttempt(attempt))
1526 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1527 self.fails_with(PaymentSendFailure::PartialFailure {
1529 failed_paths_retry: Some(retry),
1530 payment_id: PaymentId([1; 32]),
1534 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1535 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1539 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1540 let mut attempts = self.attempts.borrow_mut();
1543 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1544 Some(failure) => Err(failure),
1545 None => Ok(PaymentId([1; 32])),
1549 fn check_value_msats(&self, actual_value_msats: Amount) {
1550 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1551 if let Some(expected_value_msats) = expected_value_msats {
1552 assert_eq!(actual_value_msats, expected_value_msats);
1554 panic!("Unexpected amount: {:?}", actual_value_msats);
1559 impl Drop for TestPayer {
1560 fn drop(&mut self) {
1561 if std::thread::panicking() {
1565 if !self.expectations.borrow().is_empty() {
1566 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1571 impl Payer for TestPayer {
1572 fn node_id(&self) -> PublicKey {
1573 let secp_ctx = Secp256k1::new();
1574 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1577 fn first_hops(&self) -> Vec<ChannelDetails> {
1582 &self, route: &Route, _payment_hash: PaymentHash,
1583 _payment_secret: &Option<PaymentSecret>
1584 ) -> Result<PaymentId, PaymentSendFailure> {
1585 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1586 self.check_attempts()
1589 fn send_spontaneous_payment(
1590 &self, route: &Route, _payment_preimage: PaymentPreimage,
1591 ) -> Result<PaymentId, PaymentSendFailure> {
1592 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1593 self.check_attempts()
1597 &self, route: &Route, _payment_id: PaymentId
1598 ) -> Result<(), PaymentSendFailure> {
1599 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1600 self.check_attempts().map(|_| ())
1603 fn abandon_payment(&self, _payment_id: PaymentId) { }
1606 // *** Full Featured Functional Tests with a Real ChannelManager ***
1607 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1609 impl<S: Score> Router<S> for ManualRouter {
1611 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1612 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1613 ) -> Result<Route, LightningError> {
1614 self.0.borrow_mut().pop_front().unwrap()
1618 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1619 self.0.borrow_mut().push_back(result);
1622 impl Drop for ManualRouter {
1623 fn drop(&mut self) {
1624 if std::thread::panicking() {
1627 assert!(self.0.borrow_mut().is_empty());
1632 fn retry_multi_path_single_failed_payment() {
1633 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1634 let chanmon_cfgs = create_chanmon_cfgs(2);
1635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1637 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1640 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1641 let chans = nodes[0].node.list_usable_channels();
1642 let mut route = Route {
1645 pubkey: nodes[1].node.get_our_node_id(),
1646 node_features: NodeFeatures::known(),
1647 short_channel_id: chans[0].short_channel_id.unwrap(),
1648 channel_features: ChannelFeatures::known(),
1650 cltv_expiry_delta: 100,
1653 pubkey: nodes[1].node.get_our_node_id(),
1654 node_features: NodeFeatures::known(),
1655 short_channel_id: chans[1].short_channel_id.unwrap(),
1656 channel_features: ChannelFeatures::known(),
1657 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1658 cltv_expiry_delta: 100,
1661 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1663 let router = ManualRouter(RefCell::new(VecDeque::new()));
1664 router.expect_find_route(Ok(route.clone()));
1665 // On retry, split the payment across both channels.
1666 route.paths[0][0].fee_msat = 50_000_001;
1667 route.paths[1][0].fee_msat = 50_000_000;
1668 router.expect_find_route(Ok(route.clone()));
1670 let event_handler = |_: &_| { panic!(); };
1671 let scorer = RefCell::new(TestScorer::new());
1672 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1674 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1675 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1676 duration_since_epoch(), 3600).unwrap())
1678 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1679 assert_eq!(htlc_msgs.len(), 2);
1680 check_added_monitors!(nodes[0], 2);
1684 fn immediate_retry_on_failure() {
1685 // Tests that we can/will retry immediately after a failure
1686 let chanmon_cfgs = create_chanmon_cfgs(2);
1687 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1688 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1689 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1691 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1692 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1693 let chans = nodes[0].node.list_usable_channels();
1694 let mut route = Route {
1697 pubkey: nodes[1].node.get_our_node_id(),
1698 node_features: NodeFeatures::known(),
1699 short_channel_id: chans[0].short_channel_id.unwrap(),
1700 channel_features: ChannelFeatures::known(),
1701 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1702 cltv_expiry_delta: 100,
1705 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1707 let router = ManualRouter(RefCell::new(VecDeque::new()));
1708 router.expect_find_route(Ok(route.clone()));
1709 // On retry, split the payment across both channels.
1710 route.paths.push(route.paths[0].clone());
1711 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1712 route.paths[0][0].fee_msat = 50_000_000;
1713 route.paths[1][0].fee_msat = 50_000_001;
1714 router.expect_find_route(Ok(route.clone()));
1716 let event_handler = |_: &_| { panic!(); };
1717 let scorer = RefCell::new(TestScorer::new());
1718 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1720 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1721 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1722 duration_since_epoch(), 3600).unwrap())
1724 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1725 assert_eq!(htlc_msgs.len(), 2);
1726 check_added_monitors!(nodes[0], 2);
1730 fn no_extra_retries_on_back_to_back_fail() {
1731 // In a previous release, we had a race where we may exceed the payment retry count if we
1732 // get two failures in a row with the second having `all_paths_failed` set.
1733 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1734 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1735 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1736 // pending which we will see later. Thus, when we previously removed the retry tracking map
1737 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1738 // retry entry even though more events for the same payment were still pending. This led to
1739 // us retrying a payment again even though we'd already given up on it.
1741 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1742 // is used to remove the payment retry counter entries instead. This tests for the specific
1743 // excess-retry case while also testing `PaymentFailed` generation.
1745 let chanmon_cfgs = create_chanmon_cfgs(3);
1746 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1747 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1748 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1750 let chan_1_scid = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1751 let chan_2_scid = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 10_000_000, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
1753 let mut route = Route {
1756 pubkey: nodes[1].node.get_our_node_id(),
1757 node_features: NodeFeatures::known(),
1758 short_channel_id: chan_1_scid,
1759 channel_features: ChannelFeatures::known(),
1761 cltv_expiry_delta: 100,
1763 pubkey: nodes[2].node.get_our_node_id(),
1764 node_features: NodeFeatures::known(),
1765 short_channel_id: chan_2_scid,
1766 channel_features: ChannelFeatures::known(),
1767 fee_msat: 100_000_000,
1768 cltv_expiry_delta: 100,
1771 pubkey: nodes[1].node.get_our_node_id(),
1772 node_features: NodeFeatures::known(),
1773 short_channel_id: chan_1_scid,
1774 channel_features: ChannelFeatures::known(),
1776 cltv_expiry_delta: 100,
1778 pubkey: nodes[2].node.get_our_node_id(),
1779 node_features: NodeFeatures::known(),
1780 short_channel_id: chan_2_scid,
1781 channel_features: ChannelFeatures::known(),
1782 fee_msat: 100_000_000,
1783 cltv_expiry_delta: 100,
1786 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1788 let router = ManualRouter(RefCell::new(VecDeque::new()));
1789 router.expect_find_route(Ok(route.clone()));
1790 // On retry, we'll only be asked for one path
1791 route.paths.remove(1);
1792 router.expect_find_route(Ok(route.clone()));
1794 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1795 let event_handler = |event: &Event| {
1796 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1797 event_checker(event);
1799 let scorer = RefCell::new(TestScorer::new());
1800 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1802 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1803 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1804 duration_since_epoch(), 3600).unwrap())
1806 let htlc_updates = SendEvent::from_node(&nodes[0]);
1807 check_added_monitors!(nodes[0], 1);
1808 assert_eq!(htlc_updates.msgs.len(), 1);
1810 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1811 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1812 check_added_monitors!(nodes[1], 1);
1813 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1815 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1816 check_added_monitors!(nodes[0], 1);
1817 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1819 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1820 check_added_monitors!(nodes[0], 1);
1821 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1823 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1824 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1825 check_added_monitors!(nodes[1], 1);
1826 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1828 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1829 check_added_monitors!(nodes[1], 1);
1830 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1832 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1833 check_added_monitors!(nodes[0], 1);
1835 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1836 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1837 check_added_monitors!(nodes[0], 1);
1838 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1840 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1841 check_added_monitors!(nodes[1], 1);
1842 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1844 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1845 check_added_monitors!(nodes[1], 1);
1846 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1848 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1849 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1850 check_added_monitors!(nodes[0], 1);
1852 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1853 check_added_monitors!(nodes[0], 1);
1854 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1856 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1857 check_added_monitors!(nodes[1], 1);
1858 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1859 check_added_monitors!(nodes[1], 1);
1860 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1862 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1863 check_added_monitors!(nodes[0], 1);
1865 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1866 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1867 // with it set. The first event will use up the only retry we are allowed, with the second
1868 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1869 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1870 // if the final HTLC failed.
1871 expected_events.borrow_mut().push_back(&|ev: &Event| {
1872 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1873 assert!(!rejected_by_dest);
1874 assert!(all_paths_failed);
1875 } else { panic!("Unexpected event"); }
1877 nodes[0].node.process_pending_events(&invoice_payer);
1878 assert!(expected_events.borrow().is_empty());
1880 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1881 check_added_monitors!(nodes[0], 1);
1883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1884 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1885 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1886 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1887 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1889 expected_events.borrow_mut().push_back(&|ev: &Event| {
1890 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1891 assert!(!rejected_by_dest);
1892 assert!(all_paths_failed);
1893 } else { panic!("Unexpected event"); }
1895 expected_events.borrow_mut().push_back(&|ev: &Event| {
1896 if let Event::PaymentFailed { .. } = ev {
1897 } else { panic!("Unexpected event"); }
1899 nodes[0].node.process_pending_events(&invoice_payer);
1900 assert!(expected_events.borrow().is_empty());