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::scoring::Score;
42 //! # use lightning::routing::network_graph::NodeId;
43 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
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, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
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::util::test_utils::TestLogger;
608 use lightning::util::errors::APIError;
609 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
610 use secp256k1::{SecretKey, PublicKey, Secp256k1};
611 use std::cell::RefCell;
612 use std::collections::VecDeque;
613 use std::time::{SystemTime, Duration};
614 use time_utils::tests::SinceEpoch;
615 use DEFAULT_EXPIRY_TIME;
617 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
618 let payment_hash = Sha256::hash(&payment_preimage.0);
619 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
621 InvoiceBuilder::new(Currency::Bitcoin)
622 .description("test".into())
623 .payment_hash(payment_hash)
624 .payment_secret(PaymentSecret([0; 32]))
625 .duration_since_epoch(duration_since_epoch())
626 .min_final_cltv_expiry(144)
627 .amount_milli_satoshis(128)
628 .build_signed(|hash| {
629 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
634 fn duration_since_epoch() -> Duration {
635 #[cfg(feature = "std")]
636 let duration_since_epoch =
637 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
638 #[cfg(not(feature = "std"))]
639 let duration_since_epoch = Duration::from_secs(1234567);
643 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
644 let payment_hash = Sha256::hash(&payment_preimage.0);
645 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
647 InvoiceBuilder::new(Currency::Bitcoin)
648 .description("test".into())
649 .payment_hash(payment_hash)
650 .payment_secret(PaymentSecret([0; 32]))
651 .duration_since_epoch(duration_since_epoch())
652 .min_final_cltv_expiry(144)
653 .build_signed(|hash| {
654 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
659 #[cfg(feature = "std")]
660 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
661 let payment_hash = Sha256::hash(&payment_preimage.0);
662 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
663 let duration = duration_since_epoch()
664 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
666 InvoiceBuilder::new(Currency::Bitcoin)
667 .description("test".into())
668 .payment_hash(payment_hash)
669 .payment_secret(PaymentSecret([0; 32]))
670 .duration_since_epoch(duration)
671 .min_final_cltv_expiry(144)
672 .amount_milli_satoshis(128)
673 .build_signed(|hash| {
674 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
679 fn pubkey() -> PublicKey {
680 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
684 fn pays_invoice_on_first_attempt() {
685 let event_handled = core::cell::RefCell::new(false);
686 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
688 let payment_preimage = PaymentPreimage([1; 32]);
689 let invoice = invoice(payment_preimage);
690 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
691 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
693 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
694 let router = TestRouter {};
695 let scorer = RefCell::new(TestScorer::new());
696 let logger = TestLogger::new();
698 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
700 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
701 assert_eq!(*payer.attempts.borrow(), 1);
703 invoice_payer.handle_event(&Event::PaymentSent {
704 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
706 assert_eq!(*event_handled.borrow(), true);
707 assert_eq!(*payer.attempts.borrow(), 1);
711 fn pays_invoice_on_retry() {
712 let event_handled = core::cell::RefCell::new(false);
713 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
715 let payment_preimage = PaymentPreimage([1; 32]);
716 let invoice = invoice(payment_preimage);
717 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
718 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
720 let payer = TestPayer::new()
721 .expect_send(Amount::ForInvoice(final_value_msat))
722 .expect_send(Amount::OnRetry(final_value_msat / 2));
723 let router = TestRouter {};
724 let scorer = RefCell::new(TestScorer::new());
725 let logger = TestLogger::new();
727 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
729 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
730 assert_eq!(*payer.attempts.borrow(), 1);
732 let event = Event::PaymentPathFailed {
735 network_update: None,
736 rejected_by_dest: false,
737 all_paths_failed: false,
738 path: TestRouter::path_for_value(final_value_msat),
739 short_channel_id: None,
740 retry: Some(TestRouter::retry_for_invoice(&invoice)),
742 invoice_payer.handle_event(&event);
743 assert_eq!(*event_handled.borrow(), false);
744 assert_eq!(*payer.attempts.borrow(), 2);
746 invoice_payer.handle_event(&Event::PaymentSent {
747 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
749 assert_eq!(*event_handled.borrow(), true);
750 assert_eq!(*payer.attempts.borrow(), 2);
754 fn pays_invoice_on_partial_failure() {
755 let event_handler = |_: &_| { panic!() };
757 let payment_preimage = PaymentPreimage([1; 32]);
758 let invoice = invoice(payment_preimage);
759 let retry = TestRouter::retry_for_invoice(&invoice);
760 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
762 let payer = TestPayer::new()
763 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
764 .fails_with_partial_failure(retry, OnAttempt(2))
765 .expect_send(Amount::ForInvoice(final_value_msat))
766 .expect_send(Amount::OnRetry(final_value_msat / 2))
767 .expect_send(Amount::OnRetry(final_value_msat / 2));
768 let router = TestRouter {};
769 let scorer = RefCell::new(TestScorer::new());
770 let logger = TestLogger::new();
772 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
774 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
778 fn retries_payment_path_for_unknown_payment() {
779 let event_handled = core::cell::RefCell::new(false);
780 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
782 let payment_preimage = PaymentPreimage([1; 32]);
783 let invoice = invoice(payment_preimage);
784 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
785 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
787 let payer = TestPayer::new()
788 .expect_send(Amount::OnRetry(final_value_msat / 2))
789 .expect_send(Amount::OnRetry(final_value_msat / 2));
790 let router = TestRouter {};
791 let scorer = RefCell::new(TestScorer::new());
792 let logger = TestLogger::new();
794 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
796 let payment_id = Some(PaymentId([1; 32]));
797 let event = Event::PaymentPathFailed {
800 network_update: None,
801 rejected_by_dest: false,
802 all_paths_failed: false,
803 path: TestRouter::path_for_value(final_value_msat),
804 short_channel_id: None,
805 retry: Some(TestRouter::retry_for_invoice(&invoice)),
807 invoice_payer.handle_event(&event);
808 assert_eq!(*event_handled.borrow(), false);
809 assert_eq!(*payer.attempts.borrow(), 1);
811 invoice_payer.handle_event(&event);
812 assert_eq!(*event_handled.borrow(), false);
813 assert_eq!(*payer.attempts.borrow(), 2);
815 invoice_payer.handle_event(&Event::PaymentSent {
816 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
818 assert_eq!(*event_handled.borrow(), true);
819 assert_eq!(*payer.attempts.borrow(), 2);
823 fn fails_paying_invoice_after_max_retry_counts() {
824 let event_handled = core::cell::RefCell::new(false);
825 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
827 let payment_preimage = PaymentPreimage([1; 32]);
828 let invoice = invoice(payment_preimage);
829 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
831 let payer = TestPayer::new()
832 .expect_send(Amount::ForInvoice(final_value_msat))
833 .expect_send(Amount::OnRetry(final_value_msat / 2))
834 .expect_send(Amount::OnRetry(final_value_msat / 2));
835 let router = TestRouter {};
836 let scorer = RefCell::new(TestScorer::new());
837 let logger = TestLogger::new();
839 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
841 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
842 assert_eq!(*payer.attempts.borrow(), 1);
844 let event = Event::PaymentPathFailed {
846 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
847 network_update: None,
848 rejected_by_dest: false,
849 all_paths_failed: true,
850 path: TestRouter::path_for_value(final_value_msat),
851 short_channel_id: None,
852 retry: Some(TestRouter::retry_for_invoice(&invoice)),
854 invoice_payer.handle_event(&event);
855 assert_eq!(*event_handled.borrow(), false);
856 assert_eq!(*payer.attempts.borrow(), 2);
858 let event = Event::PaymentPathFailed {
860 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
861 network_update: None,
862 rejected_by_dest: false,
863 all_paths_failed: false,
864 path: TestRouter::path_for_value(final_value_msat / 2),
865 short_channel_id: None,
866 retry: Some(RouteParameters {
867 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
870 invoice_payer.handle_event(&event);
871 assert_eq!(*event_handled.borrow(), false);
872 assert_eq!(*payer.attempts.borrow(), 3);
874 invoice_payer.handle_event(&event);
875 assert_eq!(*event_handled.borrow(), true);
876 assert_eq!(*payer.attempts.borrow(), 3);
879 #[cfg(feature = "std")]
881 fn fails_paying_invoice_after_max_retry_timeout() {
882 let event_handled = core::cell::RefCell::new(false);
883 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
885 let payment_preimage = PaymentPreimage([1; 32]);
886 let invoice = invoice(payment_preimage);
887 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
889 let payer = TestPayer::new()
890 .expect_send(Amount::ForInvoice(final_value_msat))
891 .expect_send(Amount::OnRetry(final_value_msat / 2));
893 let router = TestRouter {};
894 let scorer = RefCell::new(TestScorer::new());
895 let logger = TestLogger::new();
896 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
899 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
901 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
902 assert_eq!(*payer.attempts.borrow(), 1);
904 let event = Event::PaymentPathFailed {
906 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
907 network_update: None,
908 rejected_by_dest: false,
909 all_paths_failed: true,
910 path: TestRouter::path_for_value(final_value_msat),
911 short_channel_id: None,
912 retry: Some(TestRouter::retry_for_invoice(&invoice)),
914 invoice_payer.handle_event(&event);
915 assert_eq!(*event_handled.borrow(), false);
916 assert_eq!(*payer.attempts.borrow(), 2);
918 SinceEpoch::advance(Duration::from_secs(121));
920 invoice_payer.handle_event(&event);
921 assert_eq!(*event_handled.borrow(), true);
922 assert_eq!(*payer.attempts.borrow(), 2);
926 fn fails_paying_invoice_with_missing_retry_params() {
927 let event_handled = core::cell::RefCell::new(false);
928 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
930 let payment_preimage = PaymentPreimage([1; 32]);
931 let invoice = invoice(payment_preimage);
932 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
934 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
935 let router = TestRouter {};
936 let scorer = RefCell::new(TestScorer::new());
937 let logger = TestLogger::new();
939 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
941 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
942 assert_eq!(*payer.attempts.borrow(), 1);
944 let event = Event::PaymentPathFailed {
946 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
947 network_update: None,
948 rejected_by_dest: false,
949 all_paths_failed: false,
951 short_channel_id: None,
954 invoice_payer.handle_event(&event);
955 assert_eq!(*event_handled.borrow(), true);
956 assert_eq!(*payer.attempts.borrow(), 1);
959 // Expiration is checked only in an std environment
960 #[cfg(feature = "std")]
962 fn fails_paying_invoice_after_expiration() {
963 let event_handled = core::cell::RefCell::new(false);
964 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
966 let payer = TestPayer::new();
967 let router = TestRouter {};
968 let scorer = RefCell::new(TestScorer::new());
969 let logger = TestLogger::new();
971 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
973 let payment_preimage = PaymentPreimage([1; 32]);
974 let invoice = expired_invoice(payment_preimage);
975 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
976 assert_eq!(msg, "Invoice expired prior to send");
977 } else { panic!("Expected Invoice Error"); }
980 // Expiration is checked only in an std environment
981 #[cfg(feature = "std")]
983 fn fails_retrying_invoice_after_expiration() {
984 let event_handled = core::cell::RefCell::new(false);
985 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
987 let payment_preimage = PaymentPreimage([1; 32]);
988 let invoice = invoice(payment_preimage);
989 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
991 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
992 let router = TestRouter {};
993 let scorer = RefCell::new(TestScorer::new());
994 let logger = TestLogger::new();
996 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
998 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
999 assert_eq!(*payer.attempts.borrow(), 1);
1001 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1002 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1003 .checked_sub(Duration::from_secs(2)).unwrap()
1004 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1005 let event = Event::PaymentPathFailed {
1007 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1008 network_update: None,
1009 rejected_by_dest: false,
1010 all_paths_failed: false,
1012 short_channel_id: None,
1013 retry: Some(retry_data),
1015 invoice_payer.handle_event(&event);
1016 assert_eq!(*event_handled.borrow(), true);
1017 assert_eq!(*payer.attempts.borrow(), 1);
1021 fn fails_paying_invoice_after_retry_error() {
1022 let event_handled = core::cell::RefCell::new(false);
1023 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1025 let payment_preimage = PaymentPreimage([1; 32]);
1026 let invoice = invoice(payment_preimage);
1027 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1029 let payer = TestPayer::new()
1030 .fails_on_attempt(2)
1031 .expect_send(Amount::ForInvoice(final_value_msat))
1032 .expect_send(Amount::OnRetry(final_value_msat / 2));
1033 let router = TestRouter {};
1034 let scorer = RefCell::new(TestScorer::new());
1035 let logger = TestLogger::new();
1037 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1039 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1040 assert_eq!(*payer.attempts.borrow(), 1);
1042 let event = Event::PaymentPathFailed {
1044 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1045 network_update: None,
1046 rejected_by_dest: false,
1047 all_paths_failed: false,
1048 path: TestRouter::path_for_value(final_value_msat / 2),
1049 short_channel_id: None,
1050 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1052 invoice_payer.handle_event(&event);
1053 assert_eq!(*event_handled.borrow(), true);
1054 assert_eq!(*payer.attempts.borrow(), 2);
1058 fn fails_paying_invoice_after_rejected_by_payee() {
1059 let event_handled = core::cell::RefCell::new(false);
1060 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1062 let payment_preimage = PaymentPreimage([1; 32]);
1063 let invoice = invoice(payment_preimage);
1064 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1066 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1067 let router = TestRouter {};
1068 let scorer = RefCell::new(TestScorer::new());
1069 let logger = TestLogger::new();
1071 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1073 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1074 assert_eq!(*payer.attempts.borrow(), 1);
1076 let event = Event::PaymentPathFailed {
1078 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1079 network_update: None,
1080 rejected_by_dest: true,
1081 all_paths_failed: false,
1083 short_channel_id: None,
1084 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1086 invoice_payer.handle_event(&event);
1087 assert_eq!(*event_handled.borrow(), true);
1088 assert_eq!(*payer.attempts.borrow(), 1);
1092 fn fails_repaying_invoice_with_pending_payment() {
1093 let event_handled = core::cell::RefCell::new(false);
1094 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1096 let payment_preimage = PaymentPreimage([1; 32]);
1097 let invoice = invoice(payment_preimage);
1098 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1100 let payer = TestPayer::new()
1101 .expect_send(Amount::ForInvoice(final_value_msat))
1102 .expect_send(Amount::ForInvoice(final_value_msat));
1103 let router = TestRouter {};
1104 let scorer = RefCell::new(TestScorer::new());
1105 let logger = TestLogger::new();
1107 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1109 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1111 // Cannot repay an invoice pending payment.
1112 match invoice_payer.pay_invoice(&invoice) {
1113 Err(PaymentError::Invoice("payment pending")) => {},
1114 Err(_) => panic!("unexpected error"),
1115 Ok(_) => panic!("expected invoice error"),
1118 // Can repay an invoice once cleared from cache.
1119 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1120 invoice_payer.remove_cached_payment(&payment_hash);
1121 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1123 // Cannot retry paying an invoice if cleared from cache.
1124 invoice_payer.remove_cached_payment(&payment_hash);
1125 let event = Event::PaymentPathFailed {
1128 network_update: None,
1129 rejected_by_dest: false,
1130 all_paths_failed: false,
1132 short_channel_id: None,
1133 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1135 invoice_payer.handle_event(&event);
1136 assert_eq!(*event_handled.borrow(), true);
1140 fn fails_paying_invoice_with_routing_errors() {
1141 let payer = TestPayer::new();
1142 let router = FailingRouter {};
1143 let scorer = RefCell::new(TestScorer::new());
1144 let logger = TestLogger::new();
1146 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1148 let payment_preimage = PaymentPreimage([1; 32]);
1149 let invoice = invoice(payment_preimage);
1150 match invoice_payer.pay_invoice(&invoice) {
1151 Err(PaymentError::Routing(_)) => {},
1152 Err(_) => panic!("unexpected error"),
1153 Ok(_) => panic!("expected routing error"),
1158 fn fails_paying_invoice_with_sending_errors() {
1159 let payment_preimage = PaymentPreimage([1; 32]);
1160 let invoice = invoice(payment_preimage);
1161 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1163 let payer = TestPayer::new()
1164 .fails_on_attempt(1)
1165 .expect_send(Amount::ForInvoice(final_value_msat));
1166 let router = TestRouter {};
1167 let scorer = RefCell::new(TestScorer::new());
1168 let logger = TestLogger::new();
1170 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1172 match invoice_payer.pay_invoice(&invoice) {
1173 Err(PaymentError::Sending(_)) => {},
1174 Err(_) => panic!("unexpected error"),
1175 Ok(_) => panic!("expected sending error"),
1180 fn pays_zero_value_invoice_using_amount() {
1181 let event_handled = core::cell::RefCell::new(false);
1182 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1184 let payment_preimage = PaymentPreimage([1; 32]);
1185 let invoice = zero_value_invoice(payment_preimage);
1186 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1187 let final_value_msat = 100;
1189 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1190 let router = TestRouter {};
1191 let scorer = RefCell::new(TestScorer::new());
1192 let logger = TestLogger::new();
1194 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1197 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1198 assert_eq!(*payer.attempts.borrow(), 1);
1200 invoice_payer.handle_event(&Event::PaymentSent {
1201 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1203 assert_eq!(*event_handled.borrow(), true);
1204 assert_eq!(*payer.attempts.borrow(), 1);
1208 fn fails_paying_zero_value_invoice_with_amount() {
1209 let event_handled = core::cell::RefCell::new(false);
1210 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1212 let payer = TestPayer::new();
1213 let router = TestRouter {};
1214 let scorer = RefCell::new(TestScorer::new());
1215 let logger = TestLogger::new();
1217 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1219 let payment_preimage = PaymentPreimage([1; 32]);
1220 let invoice = invoice(payment_preimage);
1222 // Cannot repay an invoice pending payment.
1223 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1224 Err(PaymentError::Invoice("amount unexpected")) => {},
1225 Err(_) => panic!("unexpected error"),
1226 Ok(_) => panic!("expected invoice error"),
1231 fn pays_pubkey_with_amount() {
1232 let event_handled = core::cell::RefCell::new(false);
1233 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1235 let pubkey = pubkey();
1236 let payment_preimage = PaymentPreimage([1; 32]);
1237 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1238 let final_value_msat = 100;
1239 let final_cltv_expiry_delta = 42;
1241 let payer = TestPayer::new()
1242 .expect_send(Amount::Spontaneous(final_value_msat))
1243 .expect_send(Amount::OnRetry(final_value_msat));
1244 let router = TestRouter {};
1245 let scorer = RefCell::new(TestScorer::new());
1246 let logger = TestLogger::new();
1248 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1250 let payment_id = Some(invoice_payer.pay_pubkey(
1251 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1253 assert_eq!(*payer.attempts.borrow(), 1);
1255 let retry = RouteParameters {
1256 payment_params: PaymentParameters::for_keysend(pubkey),
1258 final_cltv_expiry_delta,
1260 let event = Event::PaymentPathFailed {
1263 network_update: None,
1264 rejected_by_dest: false,
1265 all_paths_failed: false,
1267 short_channel_id: None,
1270 invoice_payer.handle_event(&event);
1271 assert_eq!(*event_handled.borrow(), false);
1272 assert_eq!(*payer.attempts.borrow(), 2);
1274 invoice_payer.handle_event(&Event::PaymentSent {
1275 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1277 assert_eq!(*event_handled.borrow(), true);
1278 assert_eq!(*payer.attempts.borrow(), 2);
1282 fn scores_failed_channel() {
1283 let event_handled = core::cell::RefCell::new(false);
1284 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1286 let payment_preimage = PaymentPreimage([1; 32]);
1287 let invoice = invoice(payment_preimage);
1288 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1289 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1290 let path = TestRouter::path_for_value(final_value_msat);
1291 let short_channel_id = Some(path[0].short_channel_id);
1293 // Expect that scorer is given short_channel_id upon handling the event.
1294 let payer = TestPayer::new()
1295 .expect_send(Amount::ForInvoice(final_value_msat))
1296 .expect_send(Amount::OnRetry(final_value_msat / 2));
1297 let router = TestRouter {};
1298 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1299 path: path.clone(), short_channel_id: path[0].short_channel_id,
1301 let logger = TestLogger::new();
1303 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1305 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1306 let event = Event::PaymentPathFailed {
1309 network_update: None,
1310 rejected_by_dest: false,
1311 all_paths_failed: false,
1314 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1316 invoice_payer.handle_event(&event);
1320 fn scores_successful_channels() {
1321 let event_handled = core::cell::RefCell::new(false);
1322 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1324 let payment_preimage = PaymentPreimage([1; 32]);
1325 let invoice = invoice(payment_preimage);
1326 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1327 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1328 let route = TestRouter::route_for_value(final_value_msat);
1330 // Expect that scorer is given short_channel_id upon handling the event.
1331 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1332 let router = TestRouter {};
1333 let scorer = RefCell::new(TestScorer::new()
1334 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1335 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1337 let logger = TestLogger::new();
1339 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1341 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1342 let event = Event::PaymentPathSuccessful {
1343 payment_id, payment_hash, path: route.paths[0].clone()
1345 invoice_payer.handle_event(&event);
1346 let event = Event::PaymentPathSuccessful {
1347 payment_id, payment_hash, path: route.paths[1].clone()
1349 invoice_payer.handle_event(&event);
1355 fn route_for_value(final_value_msat: u64) -> Route {
1359 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1360 channel_features: ChannelFeatures::empty(),
1361 node_features: NodeFeatures::empty(),
1362 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1365 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1366 channel_features: ChannelFeatures::empty(),
1367 node_features: NodeFeatures::empty(),
1368 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1371 payment_params: None,
1375 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1376 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1379 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1380 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1381 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1382 .with_route_hints(invoice.route_hints());
1383 if let Some(features) = invoice.features() {
1384 payment_params = payment_params.with_features(features.clone());
1386 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1390 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1395 impl<S: Score> Router<S> for TestRouter {
1397 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1398 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1399 ) -> Result<Route, LightningError> {
1401 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1406 struct FailingRouter;
1408 impl<S: Score> Router<S> for FailingRouter {
1410 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1411 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1412 ) -> Result<Route, LightningError> {
1413 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1418 expectations: Option<VecDeque<PaymentPath>>,
1423 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1424 Success { path: Vec<RouteHop> },
1434 fn expect(mut self, expectation: PaymentPath) -> Self {
1435 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1441 impl lightning::util::ser::Writeable for TestScorer {
1442 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1445 impl Score for TestScorer {
1446 fn channel_penalty_msat(
1447 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
1450 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1451 if let Some(expectations) = &mut self.expectations {
1452 match expectations.pop_front() {
1453 Some(PaymentPath::Failure { path, short_channel_id }) => {
1454 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1455 assert_eq!(actual_short_channel_id, short_channel_id);
1457 Some(PaymentPath::Success { path }) => {
1458 panic!("Unexpected successful payment path: {:?}", path)
1460 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1465 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1466 if let Some(expectations) = &mut self.expectations {
1467 match expectations.pop_front() {
1468 Some(PaymentPath::Failure { path, .. }) => {
1469 panic!("Unexpected payment path failure: {:?}", path)
1471 Some(PaymentPath::Success { path }) => {
1472 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1474 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1480 impl Drop for TestScorer {
1481 fn drop(&mut self) {
1482 if std::thread::panicking() {
1486 if let Some(expectations) = &self.expectations {
1487 if !expectations.is_empty() {
1488 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1495 expectations: core::cell::RefCell<VecDeque<Amount>>,
1496 attempts: core::cell::RefCell<usize>,
1497 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1500 #[derive(Clone, Debug, PartialEq, Eq)]
1507 struct OnAttempt(usize);
1512 expectations: core::cell::RefCell::new(VecDeque::new()),
1513 attempts: core::cell::RefCell::new(0),
1514 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1518 fn expect_send(self, value_msat: Amount) -> Self {
1519 self.expectations.borrow_mut().push_back(value_msat);
1523 fn fails_on_attempt(self, attempt: usize) -> Self {
1524 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1525 self.fails_with(failure, OnAttempt(attempt))
1528 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1529 self.fails_with(PaymentSendFailure::PartialFailure {
1531 failed_paths_retry: Some(retry),
1532 payment_id: PaymentId([1; 32]),
1536 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1537 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1541 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1542 let mut attempts = self.attempts.borrow_mut();
1545 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1546 Some(failure) => Err(failure),
1547 None => Ok(PaymentId([1; 32])),
1551 fn check_value_msats(&self, actual_value_msats: Amount) {
1552 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1553 if let Some(expected_value_msats) = expected_value_msats {
1554 assert_eq!(actual_value_msats, expected_value_msats);
1556 panic!("Unexpected amount: {:?}", actual_value_msats);
1561 impl Drop for TestPayer {
1562 fn drop(&mut self) {
1563 if std::thread::panicking() {
1567 if !self.expectations.borrow().is_empty() {
1568 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1573 impl Payer for TestPayer {
1574 fn node_id(&self) -> PublicKey {
1575 let secp_ctx = Secp256k1::new();
1576 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1579 fn first_hops(&self) -> Vec<ChannelDetails> {
1584 &self, route: &Route, _payment_hash: PaymentHash,
1585 _payment_secret: &Option<PaymentSecret>
1586 ) -> Result<PaymentId, PaymentSendFailure> {
1587 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1588 self.check_attempts()
1591 fn send_spontaneous_payment(
1592 &self, route: &Route, _payment_preimage: PaymentPreimage,
1593 ) -> Result<PaymentId, PaymentSendFailure> {
1594 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1595 self.check_attempts()
1599 &self, route: &Route, _payment_id: PaymentId
1600 ) -> Result<(), PaymentSendFailure> {
1601 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1602 self.check_attempts().map(|_| ())
1605 fn abandon_payment(&self, _payment_id: PaymentId) { }
1608 // *** Full Featured Functional Tests with a Real ChannelManager ***
1609 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1611 impl<S: Score> Router<S> for ManualRouter {
1613 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1614 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1615 ) -> Result<Route, LightningError> {
1616 self.0.borrow_mut().pop_front().unwrap()
1620 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1621 self.0.borrow_mut().push_back(result);
1624 impl Drop for ManualRouter {
1625 fn drop(&mut self) {
1626 if std::thread::panicking() {
1629 assert!(self.0.borrow_mut().is_empty());
1634 fn retry_multi_path_single_failed_payment() {
1635 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1636 let chanmon_cfgs = create_chanmon_cfgs(2);
1637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1639 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1641 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1642 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1643 let chans = nodes[0].node.list_usable_channels();
1644 let mut route = Route {
1647 pubkey: nodes[1].node.get_our_node_id(),
1648 node_features: NodeFeatures::known(),
1649 short_channel_id: chans[0].short_channel_id.unwrap(),
1650 channel_features: ChannelFeatures::known(),
1652 cltv_expiry_delta: 100,
1655 pubkey: nodes[1].node.get_our_node_id(),
1656 node_features: NodeFeatures::known(),
1657 short_channel_id: chans[1].short_channel_id.unwrap(),
1658 channel_features: ChannelFeatures::known(),
1659 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1660 cltv_expiry_delta: 100,
1663 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1665 let router = ManualRouter(RefCell::new(VecDeque::new()));
1666 router.expect_find_route(Ok(route.clone()));
1667 // On retry, split the payment across both channels.
1668 route.paths[0][0].fee_msat = 50_000_001;
1669 route.paths[1][0].fee_msat = 50_000_000;
1670 router.expect_find_route(Ok(route.clone()));
1672 let event_handler = |_: &_| { panic!(); };
1673 let scorer = RefCell::new(TestScorer::new());
1674 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1676 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1677 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1678 duration_since_epoch(), 3600).unwrap())
1680 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1681 assert_eq!(htlc_msgs.len(), 2);
1682 check_added_monitors!(nodes[0], 2);
1686 fn immediate_retry_on_failure() {
1687 // Tests that we can/will retry immediately after a failure
1688 let chanmon_cfgs = create_chanmon_cfgs(2);
1689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1691 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1693 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1694 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1695 let chans = nodes[0].node.list_usable_channels();
1696 let mut route = Route {
1699 pubkey: nodes[1].node.get_our_node_id(),
1700 node_features: NodeFeatures::known(),
1701 short_channel_id: chans[0].short_channel_id.unwrap(),
1702 channel_features: ChannelFeatures::known(),
1703 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1704 cltv_expiry_delta: 100,
1707 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1709 let router = ManualRouter(RefCell::new(VecDeque::new()));
1710 router.expect_find_route(Ok(route.clone()));
1711 // On retry, split the payment across both channels.
1712 route.paths.push(route.paths[0].clone());
1713 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1714 route.paths[0][0].fee_msat = 50_000_000;
1715 route.paths[1][0].fee_msat = 50_000_001;
1716 router.expect_find_route(Ok(route.clone()));
1718 let event_handler = |_: &_| { panic!(); };
1719 let scorer = RefCell::new(TestScorer::new());
1720 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1722 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1723 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1724 duration_since_epoch(), 3600).unwrap())
1726 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1727 assert_eq!(htlc_msgs.len(), 2);
1728 check_added_monitors!(nodes[0], 2);
1732 fn no_extra_retries_on_back_to_back_fail() {
1733 // In a previous release, we had a race where we may exceed the payment retry count if we
1734 // get two failures in a row with the second having `all_paths_failed` set.
1735 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1736 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1737 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1738 // pending which we will see later. Thus, when we previously removed the retry tracking map
1739 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1740 // retry entry even though more events for the same payment were still pending. This led to
1741 // us retrying a payment again even though we'd already given up on it.
1743 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1744 // is used to remove the payment retry counter entries instead. This tests for the specific
1745 // excess-retry case while also testing `PaymentFailed` generation.
1747 let chanmon_cfgs = create_chanmon_cfgs(3);
1748 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1749 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1750 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1752 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;
1753 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;
1755 let mut route = Route {
1758 pubkey: nodes[1].node.get_our_node_id(),
1759 node_features: NodeFeatures::known(),
1760 short_channel_id: chan_1_scid,
1761 channel_features: ChannelFeatures::known(),
1763 cltv_expiry_delta: 100,
1765 pubkey: nodes[2].node.get_our_node_id(),
1766 node_features: NodeFeatures::known(),
1767 short_channel_id: chan_2_scid,
1768 channel_features: ChannelFeatures::known(),
1769 fee_msat: 100_000_000,
1770 cltv_expiry_delta: 100,
1773 pubkey: nodes[1].node.get_our_node_id(),
1774 node_features: NodeFeatures::known(),
1775 short_channel_id: chan_1_scid,
1776 channel_features: ChannelFeatures::known(),
1778 cltv_expiry_delta: 100,
1780 pubkey: nodes[2].node.get_our_node_id(),
1781 node_features: NodeFeatures::known(),
1782 short_channel_id: chan_2_scid,
1783 channel_features: ChannelFeatures::known(),
1784 fee_msat: 100_000_000,
1785 cltv_expiry_delta: 100,
1788 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1790 let router = ManualRouter(RefCell::new(VecDeque::new()));
1791 router.expect_find_route(Ok(route.clone()));
1792 // On retry, we'll only be asked for one path
1793 route.paths.remove(1);
1794 router.expect_find_route(Ok(route.clone()));
1796 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1797 let event_handler = |event: &Event| {
1798 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1799 event_checker(event);
1801 let scorer = RefCell::new(TestScorer::new());
1802 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1804 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1805 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1806 duration_since_epoch(), 3600).unwrap())
1808 let htlc_updates = SendEvent::from_node(&nodes[0]);
1809 check_added_monitors!(nodes[0], 1);
1810 assert_eq!(htlc_updates.msgs.len(), 1);
1812 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1813 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1814 check_added_monitors!(nodes[1], 1);
1815 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1817 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1818 check_added_monitors!(nodes[0], 1);
1819 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1821 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1822 check_added_monitors!(nodes[0], 1);
1823 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1825 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1826 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1827 check_added_monitors!(nodes[1], 1);
1828 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1831 check_added_monitors!(nodes[1], 1);
1832 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1834 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1835 check_added_monitors!(nodes[0], 1);
1837 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1838 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1839 check_added_monitors!(nodes[0], 1);
1840 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1842 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1843 check_added_monitors!(nodes[1], 1);
1844 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1846 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1847 check_added_monitors!(nodes[1], 1);
1848 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1850 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1851 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1852 check_added_monitors!(nodes[0], 1);
1854 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1855 check_added_monitors!(nodes[0], 1);
1856 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1858 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1859 check_added_monitors!(nodes[1], 1);
1860 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1861 check_added_monitors!(nodes[1], 1);
1862 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1864 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1865 check_added_monitors!(nodes[0], 1);
1867 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1868 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1869 // with it set. The first event will use up the only retry we are allowed, with the second
1870 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1871 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1872 // if the final HTLC failed.
1873 expected_events.borrow_mut().push_back(&|ev: &Event| {
1874 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1875 assert!(!rejected_by_dest);
1876 assert!(all_paths_failed);
1877 } else { panic!("Unexpected event"); }
1879 nodes[0].node.process_pending_events(&invoice_payer);
1880 assert!(expected_events.borrow().is_empty());
1882 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1883 check_added_monitors!(nodes[0], 1);
1885 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1886 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1887 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1888 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1889 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1891 expected_events.borrow_mut().push_back(&|ev: &Event| {
1892 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1893 assert!(!rejected_by_dest);
1894 assert!(all_paths_failed);
1895 } else { panic!("Unexpected event"); }
1897 expected_events.borrow_mut().push_back(&|ev: &Event| {
1898 if let Event::PaymentFailed { .. } = ev {
1899 } else { panic!("Unexpected event"); }
1901 nodes[0].node.process_pending_events(&invoice_payer);
1902 assert!(expected_events.borrow().is_empty());