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::network_graph::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, 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, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, 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, R, S: Deref, L: Deref, E: EventHandler, T: Time>
179 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
180 S::Target: for <'a> LockableScore<'a>,
188 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
189 payment_cache: Mutex<HashMap<PaymentHash, PaymentAttempts<T>>>,
193 /// Storing minimal payment attempts information required for determining if a outbound payment can
195 #[derive(Clone, Copy)]
196 struct PaymentAttempts<T: Time> {
197 /// This count will be incremented only after the result of the attempt is known. When it's 0,
198 /// it means the result of the first attempt is now known yet.
200 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
201 first_attempted_at: T
204 impl<T: Time> PaymentAttempts<T> {
208 first_attempted_at: T::now()
213 impl<T: Time> Display for PaymentAttempts<T> {
214 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
215 #[cfg(feature = "no-std")]
216 return write!( f, "attempts: {}", self.count);
217 #[cfg(not(feature = "no-std"))]
220 "attempts: {}, duration: {}s",
222 T::now().duration_since(self.first_attempted_at).as_secs()
227 /// A trait defining behavior of an [`Invoice`] payer.
229 /// Returns the payer's node id.
230 fn node_id(&self) -> PublicKey;
232 /// Returns the payer's channels.
233 fn first_hops(&self) -> Vec<ChannelDetails>;
235 /// Sends a payment over the Lightning Network using the given [`Route`].
237 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
238 ) -> Result<PaymentId, PaymentSendFailure>;
240 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
241 fn send_spontaneous_payment(
242 &self, route: &Route, payment_preimage: PaymentPreimage
243 ) -> Result<PaymentId, PaymentSendFailure>;
245 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
246 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
248 /// Signals that no further retries for the given payment will occur.
249 fn abandon_payment(&self, payment_id: PaymentId);
252 /// A trait defining behavior for routing an [`Invoice`] payment.
253 pub trait Router<S: Score> {
254 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
256 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
257 first_hops: Option<&[&ChannelDetails]>, scorer: &S
258 ) -> Result<Route, LightningError>;
261 /// Strategies available to retry payment path failures for an [`Invoice`].
263 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
265 /// Max number of attempts to retry payment.
267 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
268 /// payments, if this is less than the total number of paths, we will never even retry all of the
271 #[cfg(feature = "std")]
272 /// Time elapsed before abandoning retries for a payment.
277 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
278 match (self, attempts) {
279 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
280 max_retry_count >= &count
282 #[cfg(feature = "std")]
283 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
284 *max_duration >= T::now().duration_since(*first_attempted_at),
289 /// An error that may occur when making a payment.
290 #[derive(Clone, Debug)]
291 pub enum PaymentError {
292 /// An error resulting from the provided [`Invoice`] or payment hash.
293 Invoice(&'static str),
294 /// An error occurring when finding a route.
295 Routing(LightningError),
296 /// An error occurring when sending a payment.
297 Sending(PaymentSendFailure),
300 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, S, L, E, T>
303 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
304 S::Target: for <'a> LockableScore<'a>,
307 /// Creates an invoice payer that retries failed payment paths.
309 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
310 /// `retry` has been exceeded for a given [`Invoice`].
312 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry: Retry
320 payment_cache: Mutex::new(HashMap::new()),
325 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
327 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
328 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
330 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
331 if invoice.amount_milli_satoshis().is_none() {
332 Err(PaymentError::Invoice("amount missing"))
334 self.pay_invoice_using_amount(invoice, None)
338 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
339 /// case a retry is needed.
341 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
342 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
344 pub fn pay_zero_value_invoice(
345 &self, invoice: &Invoice, amount_msats: u64
346 ) -> Result<PaymentId, PaymentError> {
347 if invoice.amount_milli_satoshis().is_some() {
348 Err(PaymentError::Invoice("amount unexpected"))
350 self.pay_invoice_using_amount(invoice, Some(amount_msats))
354 fn pay_invoice_using_amount(
355 &self, invoice: &Invoice, amount_msats: Option<u64>
356 ) -> Result<PaymentId, PaymentError> {
357 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
359 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
360 match self.payment_cache.lock().unwrap().entry(payment_hash) {
361 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
362 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
365 let payment_secret = Some(invoice.payment_secret().clone());
366 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
367 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
368 .with_route_hints(invoice.route_hints());
369 if let Some(features) = invoice.features() {
370 payment_params = payment_params.with_features(features.clone());
372 let route_params = RouteParameters {
374 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
375 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
378 let send_payment = |route: &Route| {
379 self.payer.send_payment(route, payment_hash, &payment_secret)
382 self.pay_internal(&route_params, payment_hash, send_payment)
383 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
386 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
387 /// case a retry is needed.
389 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
390 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
392 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
393 final_cltv_expiry_delta: u32
394 ) -> Result<PaymentId, PaymentError> {
395 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
396 match self.payment_cache.lock().unwrap().entry(payment_hash) {
397 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
398 hash_map::Entry::Vacant(entry) => entry.insert(PaymentAttempts::new()),
401 let route_params = RouteParameters {
402 payment_params: PaymentParameters::for_keysend(pubkey),
403 final_value_msat: amount_msats,
404 final_cltv_expiry_delta,
407 let send_payment = |route: &Route| {
408 self.payer.send_spontaneous_payment(route, payment_preimage)
410 self.pay_internal(&route_params, payment_hash, send_payment)
411 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
414 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
415 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
416 ) -> Result<PaymentId, PaymentError> {
417 #[cfg(feature = "std")] {
418 if has_expired(params) {
419 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
420 return Err(PaymentError::Invoice("Invoice expired prior to send"));
424 let payer = self.payer.node_id();
425 let first_hops = self.payer.first_hops();
426 let route = self.router.find_route(
427 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
429 ).map_err(|e| PaymentError::Routing(e))?;
431 match send_payment(&route) {
432 Ok(payment_id) => Ok(payment_id),
434 PaymentSendFailure::ParameterError(_) => Err(e),
435 PaymentSendFailure::PathParameterError(_) => Err(e),
436 PaymentSendFailure::AllFailedRetrySafe(_) => {
437 let mut payment_cache = self.payment_cache.lock().unwrap();
438 let payment_attempts = payment_cache.get_mut(&payment_hash).unwrap();
439 payment_attempts.count += 1;
440 if self.retry.is_retryable_now(payment_attempts) {
441 core::mem::drop(payment_cache);
442 Ok(self.pay_internal(params, payment_hash, send_payment)?)
447 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
448 if let Some(retry_data) = failed_paths_retry {
449 // Some paths were sent, even if we failed to send the full MPP value our
450 // recipient may misbehave and claim the funds, at which point we have to
451 // consider the payment sent, so return `Ok()` here, ignoring any retry
453 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
456 // This may happen if we send a payment and some paths fail, but
457 // only due to a temporary monitor failure or the like, implying
458 // they're really in-flight, but we haven't sent the initial
459 // HTLC-Add messages yet.
464 }.map_err(|e| PaymentError::Sending(e))
468 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
469 ) -> Result<(), ()> {
471 *self.payment_cache.lock().unwrap().entry(payment_hash)
472 .and_modify(|attempts| attempts.count += 1)
473 .or_insert(PaymentAttempts {
475 first_attempted_at: T::now()
478 if !self.retry.is_retryable_now(&attempts) {
479 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
483 #[cfg(feature = "std")] {
484 if has_expired(params) {
485 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
490 let payer = self.payer.node_id();
491 let first_hops = self.payer.first_hops();
492 let route = self.router.find_route(
493 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
497 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
501 match self.payer.retry_payment(&route.unwrap(), payment_id) {
503 Err(PaymentSendFailure::ParameterError(_)) |
504 Err(PaymentSendFailure::PathParameterError(_)) => {
505 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
508 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
509 self.retry_payment(payment_id, payment_hash, params)
511 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
512 if let Some(retry) = failed_paths_retry {
513 // Always return Ok for the same reason as noted in pay_internal.
514 let _ = self.retry_payment(payment_id, payment_hash, &retry);
521 /// Removes the payment cached by the given payment hash.
523 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
524 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
525 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
526 self.payment_cache.lock().unwrap().remove(payment_hash);
530 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
531 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
534 #[cfg(feature = "std")]
535 fn has_expired(route_params: &RouteParameters) -> bool {
536 if let Some(expiry_time) = route_params.payment_params.expiry_time {
537 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
541 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, S, L, E, T>
544 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
545 S::Target: for <'a> LockableScore<'a>,
548 fn handle_event(&self, event: &Event) {
550 Event::PaymentPathFailed {
551 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
553 if let Some(short_channel_id) = short_channel_id {
554 let path = path.iter().collect::<Vec<_>>();
555 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
558 if payment_id.is_none() {
559 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
560 } else if *rejected_by_dest {
561 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
562 self.payer.abandon_payment(payment_id.unwrap());
563 } else if retry.is_none() {
564 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
565 self.payer.abandon_payment(payment_id.unwrap());
566 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
567 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
570 self.payer.abandon_payment(payment_id.unwrap());
573 Event::PaymentFailed { payment_hash, .. } => {
574 self.remove_cached_payment(&payment_hash);
576 Event::PaymentPathSuccessful { path, .. } => {
577 let path = path.iter().collect::<Vec<_>>();
578 self.scorer.lock().payment_path_successful(&path);
580 Event::PaymentSent { payment_hash, .. } => {
581 let mut payment_cache = self.payment_cache.lock().unwrap();
582 let attempts = payment_cache
583 .remove(payment_hash)
584 .map_or(1, |attempts| attempts.count + 1);
585 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
590 // Delegate to the decorated event handler unless the payment is retried.
591 self.event_handler.handle_event(event)
598 use crate::{InvoiceBuilder, Currency};
599 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
600 use bitcoin_hashes::sha256::Hash as Sha256;
601 use lightning::ln::PaymentPreimage;
602 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
603 use lightning::ln::functional_test_utils::*;
604 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
605 use lightning::routing::network_graph::NodeId;
606 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
607 use lightning::routing::scoring::ChannelUsage;
608 use lightning::util::test_utils::TestLogger;
609 use lightning::util::errors::APIError;
610 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
611 use secp256k1::{SecretKey, PublicKey, Secp256k1};
612 use std::cell::RefCell;
613 use std::collections::VecDeque;
614 use std::time::{SystemTime, Duration};
615 use time_utils::tests::SinceEpoch;
616 use DEFAULT_EXPIRY_TIME;
618 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
619 let payment_hash = Sha256::hash(&payment_preimage.0);
620 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
622 InvoiceBuilder::new(Currency::Bitcoin)
623 .description("test".into())
624 .payment_hash(payment_hash)
625 .payment_secret(PaymentSecret([0; 32]))
626 .duration_since_epoch(duration_since_epoch())
627 .min_final_cltv_expiry(144)
628 .amount_milli_satoshis(128)
629 .build_signed(|hash| {
630 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
635 fn duration_since_epoch() -> Duration {
636 #[cfg(feature = "std")]
637 let duration_since_epoch =
638 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
639 #[cfg(not(feature = "std"))]
640 let duration_since_epoch = Duration::from_secs(1234567);
644 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
645 let payment_hash = Sha256::hash(&payment_preimage.0);
646 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
648 InvoiceBuilder::new(Currency::Bitcoin)
649 .description("test".into())
650 .payment_hash(payment_hash)
651 .payment_secret(PaymentSecret([0; 32]))
652 .duration_since_epoch(duration_since_epoch())
653 .min_final_cltv_expiry(144)
654 .build_signed(|hash| {
655 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
660 #[cfg(feature = "std")]
661 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
662 let payment_hash = Sha256::hash(&payment_preimage.0);
663 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
664 let duration = duration_since_epoch()
665 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
667 InvoiceBuilder::new(Currency::Bitcoin)
668 .description("test".into())
669 .payment_hash(payment_hash)
670 .payment_secret(PaymentSecret([0; 32]))
671 .duration_since_epoch(duration)
672 .min_final_cltv_expiry(144)
673 .amount_milli_satoshis(128)
674 .build_signed(|hash| {
675 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
680 fn pubkey() -> PublicKey {
681 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
685 fn pays_invoice_on_first_attempt() {
686 let event_handled = core::cell::RefCell::new(false);
687 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
689 let payment_preimage = PaymentPreimage([1; 32]);
690 let invoice = invoice(payment_preimage);
691 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
692 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
694 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
695 let router = TestRouter {};
696 let scorer = RefCell::new(TestScorer::new());
697 let logger = TestLogger::new();
699 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
701 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
702 assert_eq!(*payer.attempts.borrow(), 1);
704 invoice_payer.handle_event(&Event::PaymentSent {
705 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
707 assert_eq!(*event_handled.borrow(), true);
708 assert_eq!(*payer.attempts.borrow(), 1);
712 fn pays_invoice_on_retry() {
713 let event_handled = core::cell::RefCell::new(false);
714 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
716 let payment_preimage = PaymentPreimage([1; 32]);
717 let invoice = invoice(payment_preimage);
718 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
719 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
721 let payer = TestPayer::new()
722 .expect_send(Amount::ForInvoice(final_value_msat))
723 .expect_send(Amount::OnRetry(final_value_msat / 2));
724 let router = TestRouter {};
725 let scorer = RefCell::new(TestScorer::new());
726 let logger = TestLogger::new();
728 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
730 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
731 assert_eq!(*payer.attempts.borrow(), 1);
733 let event = Event::PaymentPathFailed {
736 network_update: None,
737 rejected_by_dest: false,
738 all_paths_failed: false,
739 path: TestRouter::path_for_value(final_value_msat),
740 short_channel_id: None,
741 retry: Some(TestRouter::retry_for_invoice(&invoice)),
743 invoice_payer.handle_event(&event);
744 assert_eq!(*event_handled.borrow(), false);
745 assert_eq!(*payer.attempts.borrow(), 2);
747 invoice_payer.handle_event(&Event::PaymentSent {
748 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
750 assert_eq!(*event_handled.borrow(), true);
751 assert_eq!(*payer.attempts.borrow(), 2);
755 fn pays_invoice_on_partial_failure() {
756 let event_handler = |_: &_| { panic!() };
758 let payment_preimage = PaymentPreimage([1; 32]);
759 let invoice = invoice(payment_preimage);
760 let retry = TestRouter::retry_for_invoice(&invoice);
761 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
763 let payer = TestPayer::new()
764 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
765 .fails_with_partial_failure(retry, OnAttempt(2))
766 .expect_send(Amount::ForInvoice(final_value_msat))
767 .expect_send(Amount::OnRetry(final_value_msat / 2))
768 .expect_send(Amount::OnRetry(final_value_msat / 2));
769 let router = TestRouter {};
770 let scorer = RefCell::new(TestScorer::new());
771 let logger = TestLogger::new();
773 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
775 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
779 fn retries_payment_path_for_unknown_payment() {
780 let event_handled = core::cell::RefCell::new(false);
781 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
783 let payment_preimage = PaymentPreimage([1; 32]);
784 let invoice = invoice(payment_preimage);
785 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
786 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
788 let payer = TestPayer::new()
789 .expect_send(Amount::OnRetry(final_value_msat / 2))
790 .expect_send(Amount::OnRetry(final_value_msat / 2));
791 let router = TestRouter {};
792 let scorer = RefCell::new(TestScorer::new());
793 let logger = TestLogger::new();
795 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
797 let payment_id = Some(PaymentId([1; 32]));
798 let event = Event::PaymentPathFailed {
801 network_update: None,
802 rejected_by_dest: false,
803 all_paths_failed: false,
804 path: TestRouter::path_for_value(final_value_msat),
805 short_channel_id: None,
806 retry: Some(TestRouter::retry_for_invoice(&invoice)),
808 invoice_payer.handle_event(&event);
809 assert_eq!(*event_handled.borrow(), false);
810 assert_eq!(*payer.attempts.borrow(), 1);
812 invoice_payer.handle_event(&event);
813 assert_eq!(*event_handled.borrow(), false);
814 assert_eq!(*payer.attempts.borrow(), 2);
816 invoice_payer.handle_event(&Event::PaymentSent {
817 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
819 assert_eq!(*event_handled.borrow(), true);
820 assert_eq!(*payer.attempts.borrow(), 2);
824 fn fails_paying_invoice_after_max_retry_counts() {
825 let event_handled = core::cell::RefCell::new(false);
826 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
828 let payment_preimage = PaymentPreimage([1; 32]);
829 let invoice = invoice(payment_preimage);
830 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
832 let payer = TestPayer::new()
833 .expect_send(Amount::ForInvoice(final_value_msat))
834 .expect_send(Amount::OnRetry(final_value_msat / 2))
835 .expect_send(Amount::OnRetry(final_value_msat / 2));
836 let router = TestRouter {};
837 let scorer = RefCell::new(TestScorer::new());
838 let logger = TestLogger::new();
840 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
842 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
843 assert_eq!(*payer.attempts.borrow(), 1);
845 let event = Event::PaymentPathFailed {
847 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
848 network_update: None,
849 rejected_by_dest: false,
850 all_paths_failed: true,
851 path: TestRouter::path_for_value(final_value_msat),
852 short_channel_id: None,
853 retry: Some(TestRouter::retry_for_invoice(&invoice)),
855 invoice_payer.handle_event(&event);
856 assert_eq!(*event_handled.borrow(), false);
857 assert_eq!(*payer.attempts.borrow(), 2);
859 let event = Event::PaymentPathFailed {
861 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
862 network_update: None,
863 rejected_by_dest: false,
864 all_paths_failed: false,
865 path: TestRouter::path_for_value(final_value_msat / 2),
866 short_channel_id: None,
867 retry: Some(RouteParameters {
868 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
871 invoice_payer.handle_event(&event);
872 assert_eq!(*event_handled.borrow(), false);
873 assert_eq!(*payer.attempts.borrow(), 3);
875 invoice_payer.handle_event(&event);
876 assert_eq!(*event_handled.borrow(), true);
877 assert_eq!(*payer.attempts.borrow(), 3);
880 #[cfg(feature = "std")]
882 fn fails_paying_invoice_after_max_retry_timeout() {
883 let event_handled = core::cell::RefCell::new(false);
884 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
886 let payment_preimage = PaymentPreimage([1; 32]);
887 let invoice = invoice(payment_preimage);
888 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
890 let payer = TestPayer::new()
891 .expect_send(Amount::ForInvoice(final_value_msat))
892 .expect_send(Amount::OnRetry(final_value_msat / 2));
894 let router = TestRouter {};
895 let scorer = RefCell::new(TestScorer::new());
896 let logger = TestLogger::new();
897 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
900 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
902 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
903 assert_eq!(*payer.attempts.borrow(), 1);
905 let event = Event::PaymentPathFailed {
907 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
908 network_update: None,
909 rejected_by_dest: false,
910 all_paths_failed: true,
911 path: TestRouter::path_for_value(final_value_msat),
912 short_channel_id: None,
913 retry: Some(TestRouter::retry_for_invoice(&invoice)),
915 invoice_payer.handle_event(&event);
916 assert_eq!(*event_handled.borrow(), false);
917 assert_eq!(*payer.attempts.borrow(), 2);
919 SinceEpoch::advance(Duration::from_secs(121));
921 invoice_payer.handle_event(&event);
922 assert_eq!(*event_handled.borrow(), true);
923 assert_eq!(*payer.attempts.borrow(), 2);
927 fn fails_paying_invoice_with_missing_retry_params() {
928 let event_handled = core::cell::RefCell::new(false);
929 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
931 let payment_preimage = PaymentPreimage([1; 32]);
932 let invoice = invoice(payment_preimage);
933 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
935 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
936 let router = TestRouter {};
937 let scorer = RefCell::new(TestScorer::new());
938 let logger = TestLogger::new();
940 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
942 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
943 assert_eq!(*payer.attempts.borrow(), 1);
945 let event = Event::PaymentPathFailed {
947 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
948 network_update: None,
949 rejected_by_dest: false,
950 all_paths_failed: false,
952 short_channel_id: None,
955 invoice_payer.handle_event(&event);
956 assert_eq!(*event_handled.borrow(), true);
957 assert_eq!(*payer.attempts.borrow(), 1);
960 // Expiration is checked only in an std environment
961 #[cfg(feature = "std")]
963 fn fails_paying_invoice_after_expiration() {
964 let event_handled = core::cell::RefCell::new(false);
965 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
967 let payer = TestPayer::new();
968 let router = TestRouter {};
969 let scorer = RefCell::new(TestScorer::new());
970 let logger = TestLogger::new();
972 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
974 let payment_preimage = PaymentPreimage([1; 32]);
975 let invoice = expired_invoice(payment_preimage);
976 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
977 assert_eq!(msg, "Invoice expired prior to send");
978 } else { panic!("Expected Invoice Error"); }
981 // Expiration is checked only in an std environment
982 #[cfg(feature = "std")]
984 fn fails_retrying_invoice_after_expiration() {
985 let event_handled = core::cell::RefCell::new(false);
986 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
988 let payment_preimage = PaymentPreimage([1; 32]);
989 let invoice = invoice(payment_preimage);
990 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
992 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
993 let router = TestRouter {};
994 let scorer = RefCell::new(TestScorer::new());
995 let logger = TestLogger::new();
997 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
999 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1000 assert_eq!(*payer.attempts.borrow(), 1);
1002 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1003 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1004 .checked_sub(Duration::from_secs(2)).unwrap()
1005 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1006 let event = Event::PaymentPathFailed {
1008 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1009 network_update: None,
1010 rejected_by_dest: false,
1011 all_paths_failed: false,
1013 short_channel_id: None,
1014 retry: Some(retry_data),
1016 invoice_payer.handle_event(&event);
1017 assert_eq!(*event_handled.borrow(), true);
1018 assert_eq!(*payer.attempts.borrow(), 1);
1022 fn fails_paying_invoice_after_retry_error() {
1023 let event_handled = core::cell::RefCell::new(false);
1024 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1026 let payment_preimage = PaymentPreimage([1; 32]);
1027 let invoice = invoice(payment_preimage);
1028 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1030 let payer = TestPayer::new()
1031 .fails_on_attempt(2)
1032 .expect_send(Amount::ForInvoice(final_value_msat))
1033 .expect_send(Amount::OnRetry(final_value_msat / 2));
1034 let router = TestRouter {};
1035 let scorer = RefCell::new(TestScorer::new());
1036 let logger = TestLogger::new();
1038 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1040 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1041 assert_eq!(*payer.attempts.borrow(), 1);
1043 let event = Event::PaymentPathFailed {
1045 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1046 network_update: None,
1047 rejected_by_dest: false,
1048 all_paths_failed: false,
1049 path: TestRouter::path_for_value(final_value_msat / 2),
1050 short_channel_id: None,
1051 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1053 invoice_payer.handle_event(&event);
1054 assert_eq!(*event_handled.borrow(), true);
1055 assert_eq!(*payer.attempts.borrow(), 2);
1059 fn fails_paying_invoice_after_rejected_by_payee() {
1060 let event_handled = core::cell::RefCell::new(false);
1061 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1063 let payment_preimage = PaymentPreimage([1; 32]);
1064 let invoice = invoice(payment_preimage);
1065 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1067 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1068 let router = TestRouter {};
1069 let scorer = RefCell::new(TestScorer::new());
1070 let logger = TestLogger::new();
1072 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1074 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1075 assert_eq!(*payer.attempts.borrow(), 1);
1077 let event = Event::PaymentPathFailed {
1079 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1080 network_update: None,
1081 rejected_by_dest: true,
1082 all_paths_failed: false,
1084 short_channel_id: None,
1085 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1087 invoice_payer.handle_event(&event);
1088 assert_eq!(*event_handled.borrow(), true);
1089 assert_eq!(*payer.attempts.borrow(), 1);
1093 fn fails_repaying_invoice_with_pending_payment() {
1094 let event_handled = core::cell::RefCell::new(false);
1095 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1097 let payment_preimage = PaymentPreimage([1; 32]);
1098 let invoice = invoice(payment_preimage);
1099 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1101 let payer = TestPayer::new()
1102 .expect_send(Amount::ForInvoice(final_value_msat))
1103 .expect_send(Amount::ForInvoice(final_value_msat));
1104 let router = TestRouter {};
1105 let scorer = RefCell::new(TestScorer::new());
1106 let logger = TestLogger::new();
1108 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1110 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1112 // Cannot repay an invoice pending payment.
1113 match invoice_payer.pay_invoice(&invoice) {
1114 Err(PaymentError::Invoice("payment pending")) => {},
1115 Err(_) => panic!("unexpected error"),
1116 Ok(_) => panic!("expected invoice error"),
1119 // Can repay an invoice once cleared from cache.
1120 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1121 invoice_payer.remove_cached_payment(&payment_hash);
1122 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1124 // Cannot retry paying an invoice if cleared from cache.
1125 invoice_payer.remove_cached_payment(&payment_hash);
1126 let event = Event::PaymentPathFailed {
1129 network_update: None,
1130 rejected_by_dest: false,
1131 all_paths_failed: false,
1133 short_channel_id: None,
1134 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1136 invoice_payer.handle_event(&event);
1137 assert_eq!(*event_handled.borrow(), true);
1141 fn fails_paying_invoice_with_routing_errors() {
1142 let payer = TestPayer::new();
1143 let router = FailingRouter {};
1144 let scorer = RefCell::new(TestScorer::new());
1145 let logger = TestLogger::new();
1147 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1149 let payment_preimage = PaymentPreimage([1; 32]);
1150 let invoice = invoice(payment_preimage);
1151 match invoice_payer.pay_invoice(&invoice) {
1152 Err(PaymentError::Routing(_)) => {},
1153 Err(_) => panic!("unexpected error"),
1154 Ok(_) => panic!("expected routing error"),
1159 fn fails_paying_invoice_with_sending_errors() {
1160 let payment_preimage = PaymentPreimage([1; 32]);
1161 let invoice = invoice(payment_preimage);
1162 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1164 let payer = TestPayer::new()
1165 .fails_on_attempt(1)
1166 .expect_send(Amount::ForInvoice(final_value_msat));
1167 let router = TestRouter {};
1168 let scorer = RefCell::new(TestScorer::new());
1169 let logger = TestLogger::new();
1171 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1173 match invoice_payer.pay_invoice(&invoice) {
1174 Err(PaymentError::Sending(_)) => {},
1175 Err(_) => panic!("unexpected error"),
1176 Ok(_) => panic!("expected sending error"),
1181 fn pays_zero_value_invoice_using_amount() {
1182 let event_handled = core::cell::RefCell::new(false);
1183 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1185 let payment_preimage = PaymentPreimage([1; 32]);
1186 let invoice = zero_value_invoice(payment_preimage);
1187 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1188 let final_value_msat = 100;
1190 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1191 let router = TestRouter {};
1192 let scorer = RefCell::new(TestScorer::new());
1193 let logger = TestLogger::new();
1195 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1198 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1199 assert_eq!(*payer.attempts.borrow(), 1);
1201 invoice_payer.handle_event(&Event::PaymentSent {
1202 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1204 assert_eq!(*event_handled.borrow(), true);
1205 assert_eq!(*payer.attempts.borrow(), 1);
1209 fn fails_paying_zero_value_invoice_with_amount() {
1210 let event_handled = core::cell::RefCell::new(false);
1211 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1213 let payer = TestPayer::new();
1214 let router = TestRouter {};
1215 let scorer = RefCell::new(TestScorer::new());
1216 let logger = TestLogger::new();
1218 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1220 let payment_preimage = PaymentPreimage([1; 32]);
1221 let invoice = invoice(payment_preimage);
1223 // Cannot repay an invoice pending payment.
1224 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1225 Err(PaymentError::Invoice("amount unexpected")) => {},
1226 Err(_) => panic!("unexpected error"),
1227 Ok(_) => panic!("expected invoice error"),
1232 fn pays_pubkey_with_amount() {
1233 let event_handled = core::cell::RefCell::new(false);
1234 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1236 let pubkey = pubkey();
1237 let payment_preimage = PaymentPreimage([1; 32]);
1238 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1239 let final_value_msat = 100;
1240 let final_cltv_expiry_delta = 42;
1242 let payer = TestPayer::new()
1243 .expect_send(Amount::Spontaneous(final_value_msat))
1244 .expect_send(Amount::OnRetry(final_value_msat));
1245 let router = TestRouter {};
1246 let scorer = RefCell::new(TestScorer::new());
1247 let logger = TestLogger::new();
1249 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1251 let payment_id = Some(invoice_payer.pay_pubkey(
1252 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1254 assert_eq!(*payer.attempts.borrow(), 1);
1256 let retry = RouteParameters {
1257 payment_params: PaymentParameters::for_keysend(pubkey),
1259 final_cltv_expiry_delta,
1261 let event = Event::PaymentPathFailed {
1264 network_update: None,
1265 rejected_by_dest: false,
1266 all_paths_failed: false,
1268 short_channel_id: None,
1271 invoice_payer.handle_event(&event);
1272 assert_eq!(*event_handled.borrow(), false);
1273 assert_eq!(*payer.attempts.borrow(), 2);
1275 invoice_payer.handle_event(&Event::PaymentSent {
1276 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1278 assert_eq!(*event_handled.borrow(), true);
1279 assert_eq!(*payer.attempts.borrow(), 2);
1283 fn scores_failed_channel() {
1284 let event_handled = core::cell::RefCell::new(false);
1285 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1287 let payment_preimage = PaymentPreimage([1; 32]);
1288 let invoice = invoice(payment_preimage);
1289 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1290 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1291 let path = TestRouter::path_for_value(final_value_msat);
1292 let short_channel_id = Some(path[0].short_channel_id);
1294 // Expect that scorer is given short_channel_id upon handling the event.
1295 let payer = TestPayer::new()
1296 .expect_send(Amount::ForInvoice(final_value_msat))
1297 .expect_send(Amount::OnRetry(final_value_msat / 2));
1298 let router = TestRouter {};
1299 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1300 path: path.clone(), short_channel_id: path[0].short_channel_id,
1302 let logger = TestLogger::new();
1304 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1306 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1307 let event = Event::PaymentPathFailed {
1310 network_update: None,
1311 rejected_by_dest: false,
1312 all_paths_failed: false,
1315 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1317 invoice_payer.handle_event(&event);
1321 fn scores_successful_channels() {
1322 let event_handled = core::cell::RefCell::new(false);
1323 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1325 let payment_preimage = PaymentPreimage([1; 32]);
1326 let invoice = invoice(payment_preimage);
1327 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1328 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1329 let route = TestRouter::route_for_value(final_value_msat);
1331 // Expect that scorer is given short_channel_id upon handling the event.
1332 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1333 let router = TestRouter {};
1334 let scorer = RefCell::new(TestScorer::new()
1335 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1336 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1338 let logger = TestLogger::new();
1340 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1342 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1343 let event = Event::PaymentPathSuccessful {
1344 payment_id, payment_hash, path: route.paths[0].clone()
1346 invoice_payer.handle_event(&event);
1347 let event = Event::PaymentPathSuccessful {
1348 payment_id, payment_hash, path: route.paths[1].clone()
1350 invoice_payer.handle_event(&event);
1356 fn route_for_value(final_value_msat: u64) -> Route {
1360 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1361 channel_features: ChannelFeatures::empty(),
1362 node_features: NodeFeatures::empty(),
1363 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1366 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1367 channel_features: ChannelFeatures::empty(),
1368 node_features: NodeFeatures::empty(),
1369 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1372 payment_params: None,
1376 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1377 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1380 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1381 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1382 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1383 .with_route_hints(invoice.route_hints());
1384 if let Some(features) = invoice.features() {
1385 payment_params = payment_params.with_features(features.clone());
1387 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1391 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1396 impl<S: Score> Router<S> for TestRouter {
1398 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1399 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1400 ) -> Result<Route, LightningError> {
1402 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1407 struct FailingRouter;
1409 impl<S: Score> Router<S> for FailingRouter {
1411 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1412 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1413 ) -> Result<Route, LightningError> {
1414 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1419 expectations: Option<VecDeque<PaymentPath>>,
1424 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1425 Success { path: Vec<RouteHop> },
1435 fn expect(mut self, expectation: PaymentPath) -> Self {
1436 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1442 impl lightning::util::ser::Writeable for TestScorer {
1443 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1446 impl Score for TestScorer {
1447 fn channel_penalty_msat(
1448 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
1451 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1452 if let Some(expectations) = &mut self.expectations {
1453 match expectations.pop_front() {
1454 Some(PaymentPath::Failure { path, short_channel_id }) => {
1455 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1456 assert_eq!(actual_short_channel_id, short_channel_id);
1458 Some(PaymentPath::Success { path }) => {
1459 panic!("Unexpected successful payment path: {:?}", path)
1461 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1466 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1467 if let Some(expectations) = &mut self.expectations {
1468 match expectations.pop_front() {
1469 Some(PaymentPath::Failure { path, .. }) => {
1470 panic!("Unexpected payment path failure: {:?}", path)
1472 Some(PaymentPath::Success { path }) => {
1473 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1475 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1481 impl Drop for TestScorer {
1482 fn drop(&mut self) {
1483 if std::thread::panicking() {
1487 if let Some(expectations) = &self.expectations {
1488 if !expectations.is_empty() {
1489 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1496 expectations: core::cell::RefCell<VecDeque<Amount>>,
1497 attempts: core::cell::RefCell<usize>,
1498 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1501 #[derive(Clone, Debug, PartialEq, Eq)]
1508 struct OnAttempt(usize);
1513 expectations: core::cell::RefCell::new(VecDeque::new()),
1514 attempts: core::cell::RefCell::new(0),
1515 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1519 fn expect_send(self, value_msat: Amount) -> Self {
1520 self.expectations.borrow_mut().push_back(value_msat);
1524 fn fails_on_attempt(self, attempt: usize) -> Self {
1525 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1526 self.fails_with(failure, OnAttempt(attempt))
1529 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1530 self.fails_with(PaymentSendFailure::PartialFailure {
1532 failed_paths_retry: Some(retry),
1533 payment_id: PaymentId([1; 32]),
1537 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1538 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1542 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1543 let mut attempts = self.attempts.borrow_mut();
1546 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1547 Some(failure) => Err(failure),
1548 None => Ok(PaymentId([1; 32])),
1552 fn check_value_msats(&self, actual_value_msats: Amount) {
1553 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1554 if let Some(expected_value_msats) = expected_value_msats {
1555 assert_eq!(actual_value_msats, expected_value_msats);
1557 panic!("Unexpected amount: {:?}", actual_value_msats);
1562 impl Drop for TestPayer {
1563 fn drop(&mut self) {
1564 if std::thread::panicking() {
1568 if !self.expectations.borrow().is_empty() {
1569 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1574 impl Payer for TestPayer {
1575 fn node_id(&self) -> PublicKey {
1576 let secp_ctx = Secp256k1::new();
1577 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1580 fn first_hops(&self) -> Vec<ChannelDetails> {
1585 &self, route: &Route, _payment_hash: PaymentHash,
1586 _payment_secret: &Option<PaymentSecret>
1587 ) -> Result<PaymentId, PaymentSendFailure> {
1588 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1589 self.check_attempts()
1592 fn send_spontaneous_payment(
1593 &self, route: &Route, _payment_preimage: PaymentPreimage,
1594 ) -> Result<PaymentId, PaymentSendFailure> {
1595 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1596 self.check_attempts()
1600 &self, route: &Route, _payment_id: PaymentId
1601 ) -> Result<(), PaymentSendFailure> {
1602 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1603 self.check_attempts().map(|_| ())
1606 fn abandon_payment(&self, _payment_id: PaymentId) { }
1609 // *** Full Featured Functional Tests with a Real ChannelManager ***
1610 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1612 impl<S: Score> Router<S> for ManualRouter {
1614 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1615 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1616 ) -> Result<Route, LightningError> {
1617 self.0.borrow_mut().pop_front().unwrap()
1621 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1622 self.0.borrow_mut().push_back(result);
1625 impl Drop for ManualRouter {
1626 fn drop(&mut self) {
1627 if std::thread::panicking() {
1630 assert!(self.0.borrow_mut().is_empty());
1635 fn retry_multi_path_single_failed_payment() {
1636 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1637 let chanmon_cfgs = create_chanmon_cfgs(2);
1638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1640 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1642 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1643 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1644 let chans = nodes[0].node.list_usable_channels();
1645 let mut route = Route {
1648 pubkey: nodes[1].node.get_our_node_id(),
1649 node_features: NodeFeatures::known(),
1650 short_channel_id: chans[0].short_channel_id.unwrap(),
1651 channel_features: ChannelFeatures::known(),
1653 cltv_expiry_delta: 100,
1656 pubkey: nodes[1].node.get_our_node_id(),
1657 node_features: NodeFeatures::known(),
1658 short_channel_id: chans[1].short_channel_id.unwrap(),
1659 channel_features: ChannelFeatures::known(),
1660 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1661 cltv_expiry_delta: 100,
1664 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1666 let router = ManualRouter(RefCell::new(VecDeque::new()));
1667 router.expect_find_route(Ok(route.clone()));
1668 // On retry, split the payment across both channels.
1669 route.paths[0][0].fee_msat = 50_000_001;
1670 route.paths[1][0].fee_msat = 50_000_000;
1671 router.expect_find_route(Ok(route.clone()));
1673 let event_handler = |_: &_| { panic!(); };
1674 let scorer = RefCell::new(TestScorer::new());
1675 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1677 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1678 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1679 duration_since_epoch(), 3600).unwrap())
1681 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1682 assert_eq!(htlc_msgs.len(), 2);
1683 check_added_monitors!(nodes[0], 2);
1687 fn immediate_retry_on_failure() {
1688 // Tests that we can/will retry immediately after a failure
1689 let chanmon_cfgs = create_chanmon_cfgs(2);
1690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1692 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1694 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1695 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1696 let chans = nodes[0].node.list_usable_channels();
1697 let mut route = Route {
1700 pubkey: nodes[1].node.get_our_node_id(),
1701 node_features: NodeFeatures::known(),
1702 short_channel_id: chans[0].short_channel_id.unwrap(),
1703 channel_features: ChannelFeatures::known(),
1704 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1705 cltv_expiry_delta: 100,
1708 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1710 let router = ManualRouter(RefCell::new(VecDeque::new()));
1711 router.expect_find_route(Ok(route.clone()));
1712 // On retry, split the payment across both channels.
1713 route.paths.push(route.paths[0].clone());
1714 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1715 route.paths[0][0].fee_msat = 50_000_000;
1716 route.paths[1][0].fee_msat = 50_000_001;
1717 router.expect_find_route(Ok(route.clone()));
1719 let event_handler = |_: &_| { panic!(); };
1720 let scorer = RefCell::new(TestScorer::new());
1721 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1723 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1724 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1725 duration_since_epoch(), 3600).unwrap())
1727 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1728 assert_eq!(htlc_msgs.len(), 2);
1729 check_added_monitors!(nodes[0], 2);
1733 fn no_extra_retries_on_back_to_back_fail() {
1734 // In a previous release, we had a race where we may exceed the payment retry count if we
1735 // get two failures in a row with the second having `all_paths_failed` set.
1736 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1737 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1738 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1739 // pending which we will see later. Thus, when we previously removed the retry tracking map
1740 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1741 // retry entry even though more events for the same payment were still pending. This led to
1742 // us retrying a payment again even though we'd already given up on it.
1744 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1745 // is used to remove the payment retry counter entries instead. This tests for the specific
1746 // excess-retry case while also testing `PaymentFailed` generation.
1748 let chanmon_cfgs = create_chanmon_cfgs(3);
1749 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1750 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1751 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1753 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;
1754 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;
1756 let mut route = Route {
1759 pubkey: nodes[1].node.get_our_node_id(),
1760 node_features: NodeFeatures::known(),
1761 short_channel_id: chan_1_scid,
1762 channel_features: ChannelFeatures::known(),
1764 cltv_expiry_delta: 100,
1766 pubkey: nodes[2].node.get_our_node_id(),
1767 node_features: NodeFeatures::known(),
1768 short_channel_id: chan_2_scid,
1769 channel_features: ChannelFeatures::known(),
1770 fee_msat: 100_000_000,
1771 cltv_expiry_delta: 100,
1774 pubkey: nodes[1].node.get_our_node_id(),
1775 node_features: NodeFeatures::known(),
1776 short_channel_id: chan_1_scid,
1777 channel_features: ChannelFeatures::known(),
1779 cltv_expiry_delta: 100,
1781 pubkey: nodes[2].node.get_our_node_id(),
1782 node_features: NodeFeatures::known(),
1783 short_channel_id: chan_2_scid,
1784 channel_features: ChannelFeatures::known(),
1785 fee_msat: 100_000_000,
1786 cltv_expiry_delta: 100,
1789 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1791 let router = ManualRouter(RefCell::new(VecDeque::new()));
1792 router.expect_find_route(Ok(route.clone()));
1793 // On retry, we'll only be asked for one path
1794 route.paths.remove(1);
1795 router.expect_find_route(Ok(route.clone()));
1797 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1798 let event_handler = |event: &Event| {
1799 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1800 event_checker(event);
1802 let scorer = RefCell::new(TestScorer::new());
1803 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1805 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1806 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1807 duration_since_epoch(), 3600).unwrap())
1809 let htlc_updates = SendEvent::from_node(&nodes[0]);
1810 check_added_monitors!(nodes[0], 1);
1811 assert_eq!(htlc_updates.msgs.len(), 1);
1813 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1814 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1815 check_added_monitors!(nodes[1], 1);
1816 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1818 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1819 check_added_monitors!(nodes[0], 1);
1820 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1822 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1823 check_added_monitors!(nodes[0], 1);
1824 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1826 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1827 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1828 check_added_monitors!(nodes[1], 1);
1829 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1831 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1832 check_added_monitors!(nodes[1], 1);
1833 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1835 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1836 check_added_monitors!(nodes[0], 1);
1838 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1839 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1840 check_added_monitors!(nodes[0], 1);
1841 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1843 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1844 check_added_monitors!(nodes[1], 1);
1845 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1847 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1848 check_added_monitors!(nodes[1], 1);
1849 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1851 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1852 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1853 check_added_monitors!(nodes[0], 1);
1855 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1856 check_added_monitors!(nodes[0], 1);
1857 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1859 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1860 check_added_monitors!(nodes[1], 1);
1861 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1862 check_added_monitors!(nodes[1], 1);
1863 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1865 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1866 check_added_monitors!(nodes[0], 1);
1868 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1869 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1870 // with it set. The first event will use up the only retry we are allowed, with the second
1871 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1872 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1873 // if the final HTLC failed.
1874 expected_events.borrow_mut().push_back(&|ev: &Event| {
1875 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1876 assert!(!rejected_by_dest);
1877 assert!(all_paths_failed);
1878 } else { panic!("Unexpected event"); }
1880 nodes[0].node.process_pending_events(&invoice_payer);
1881 assert!(expected_events.borrow().is_empty());
1883 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1884 check_added_monitors!(nodes[0], 1);
1886 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1887 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1888 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1889 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1890 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1892 expected_events.borrow_mut().push_back(&|ev: &Event| {
1893 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1894 assert!(!rejected_by_dest);
1895 assert!(all_paths_failed);
1896 } else { panic!("Unexpected event"); }
1898 expected_events.borrow_mut().push_back(&|ev: &Event| {
1899 if let Event::PaymentFailed { .. } = ev {
1900 } else { panic!("Unexpected event"); }
1902 nodes[0].node.process_pending_events(&invoice_payer);
1903 assert!(expected_events.borrow().is_empty());