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, RetryAttempts, Router};
49 //! # use secp256k1::key::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, RetryAttempts(2));
118 //! let invoice = "...";
119 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
120 //! invoice_payer.pay_invoice(&invoice).unwrap();
122 //! # let event_provider = FakeEventProvider {};
124 //! event_provider.process_pending_events(&invoice_payer);
132 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
133 //! as updates to the network graph or changes to channel scores should be applied prior to
134 //! retries, typically by way of composing [`EventHandler`]s accordingly.
138 use bitcoin_hashes::Hash;
139 use bitcoin_hashes::sha256::Hash as Sha256;
141 use crate::prelude::*;
142 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
143 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
144 use lightning::ln::msgs::LightningError;
145 use lightning::routing::scoring::{LockableScore, MultiThreadedLockableScore, Score};
146 use lightning::routing::router::{PaymentParameters, Route, RouteParameters};
147 use lightning::util::events::{Event, EventHandler};
148 use lightning::util::logger::Logger;
149 use crate::sync::Mutex;
151 use secp256k1::key::PublicKey;
153 use core::ops::Deref;
154 use core::time::Duration;
155 #[cfg(feature = "std")]
156 use std::time::SystemTime;
158 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
160 /// See [module-level documentation] for details.
162 /// [module-level documentation]: crate::payment
163 pub struct InvoicePayer<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler>
166 R::Target: Router<S>,
174 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
175 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
176 retry_attempts: RetryAttempts,
179 /// A trait defining behavior of an [`Invoice`] payer.
181 /// Returns the payer's node id.
182 fn node_id(&self) -> PublicKey;
184 /// Returns the payer's channels.
185 fn first_hops(&self) -> Vec<ChannelDetails>;
187 /// Sends a payment over the Lightning Network using the given [`Route`].
189 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
190 ) -> Result<PaymentId, PaymentSendFailure>;
192 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
193 fn send_spontaneous_payment(
194 &self, route: &Route, payment_preimage: PaymentPreimage
195 ) -> Result<PaymentId, PaymentSendFailure>;
197 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
198 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
200 /// Signals that no further retries for the given payment will occur.
201 fn abandon_payment(&self, payment_id: PaymentId);
204 /// A trait defining behavior for routing an [`Invoice`] payment.
205 pub trait Router<S: Score> {
206 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
208 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
209 first_hops: Option<&[&ChannelDetails]>, scorer: &S
210 ) -> Result<Route, LightningError>;
213 /// Number of attempts to retry payment path failures for an [`Invoice`].
215 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
216 /// payments, if this is less than the total number of paths, we will never even retry all of the
218 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
219 pub struct RetryAttempts(pub usize);
221 /// An error that may occur when making a payment.
222 #[derive(Clone, Debug)]
223 pub enum PaymentError {
224 /// An error resulting from the provided [`Invoice`] or payment hash.
225 Invoice(&'static str),
226 /// An error occurring when finding a route.
227 Routing(LightningError),
228 /// An error occurring when sending a payment.
229 Sending(PaymentSendFailure),
232 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler> InvoicePayer<P, S, R, SR, L, E>
235 R::Target: Router<S>,
238 /// Creates an invoice payer that retries failed payment paths.
240 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
241 /// `retry_attempts` has been exceeded for a given [`Invoice`].
243 payer: P, router: R, scorer: SR, logger: L, event_handler: E, retry_attempts: RetryAttempts
251 payment_cache: Mutex::new(HashMap::new()),
256 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
258 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
259 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
261 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
262 if invoice.amount_milli_satoshis().is_none() {
263 Err(PaymentError::Invoice("amount missing"))
265 self.pay_invoice_using_amount(invoice, None)
269 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
270 /// case a retry is needed.
272 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
273 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
275 pub fn pay_zero_value_invoice(
276 &self, invoice: &Invoice, amount_msats: u64
277 ) -> Result<PaymentId, PaymentError> {
278 if invoice.amount_milli_satoshis().is_some() {
279 Err(PaymentError::Invoice("amount unexpected"))
281 self.pay_invoice_using_amount(invoice, Some(amount_msats))
285 fn pay_invoice_using_amount(
286 &self, invoice: &Invoice, amount_msats: Option<u64>
287 ) -> Result<PaymentId, PaymentError> {
288 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
290 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
291 match self.payment_cache.lock().unwrap().entry(payment_hash) {
292 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
293 hash_map::Entry::Vacant(entry) => entry.insert(0),
296 let payment_secret = Some(invoice.payment_secret().clone());
297 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
298 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
299 .with_route_hints(invoice.route_hints());
300 if let Some(features) = invoice.features() {
301 payment_params = payment_params.with_features(features.clone());
303 let route_params = RouteParameters {
305 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
306 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
309 let send_payment = |route: &Route| {
310 self.payer.send_payment(route, payment_hash, &payment_secret)
312 self.pay_internal(&route_params, payment_hash, send_payment)
313 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
316 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
317 /// case a retry is needed.
319 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
320 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
322 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
323 final_cltv_expiry_delta: u32
324 ) -> Result<PaymentId, PaymentError> {
325 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
326 match self.payment_cache.lock().unwrap().entry(payment_hash) {
327 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
328 hash_map::Entry::Vacant(entry) => entry.insert(0),
331 let route_params = RouteParameters {
332 payment_params: PaymentParameters::for_keysend(pubkey),
333 final_value_msat: amount_msats,
334 final_cltv_expiry_delta,
337 let send_payment = |route: &Route| {
338 self.payer.send_spontaneous_payment(route, payment_preimage)
340 self.pay_internal(&route_params, payment_hash, send_payment)
341 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
344 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
345 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
346 ) -> Result<PaymentId, PaymentError> {
347 #[cfg(feature = "std")] {
348 if has_expired(params) {
349 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
350 return Err(PaymentError::Invoice("Invoice expired prior to send"));
354 let payer = self.payer.node_id();
355 let first_hops = self.payer.first_hops();
356 let route = self.router.find_route(
357 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
359 ).map_err(|e| PaymentError::Routing(e))?;
361 match send_payment(&route) {
362 Ok(payment_id) => Ok(payment_id),
364 PaymentSendFailure::ParameterError(_) => Err(e),
365 PaymentSendFailure::PathParameterError(_) => Err(e),
366 PaymentSendFailure::AllFailedRetrySafe(_) => {
367 let mut payment_cache = self.payment_cache.lock().unwrap();
368 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
369 if *retry_count >= self.retry_attempts.0 {
373 core::mem::drop(payment_cache);
374 Ok(self.pay_internal(params, payment_hash, send_payment)?)
377 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
378 if let Some(retry_data) = failed_paths_retry {
379 // Some paths were sent, even if we failed to send the full MPP value our
380 // recipient may misbehave and claim the funds, at which point we have to
381 // consider the payment sent, so return `Ok()` here, ignoring any retry
383 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
386 // This may happen if we send a payment and some paths fail, but
387 // only due to a temporary monitor failure or the like, implying
388 // they're really in-flight, but we haven't sent the initial
389 // HTLC-Add messages yet.
394 }.map_err(|e| PaymentError::Sending(e))
398 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
399 ) -> Result<(), ()> {
400 let max_payment_attempts = self.retry_attempts.0 + 1;
401 let attempts = *self.payment_cache.lock().unwrap()
403 .and_modify(|attempts| *attempts += 1)
406 if attempts >= max_payment_attempts {
407 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
411 #[cfg(feature = "std")] {
412 if has_expired(params) {
413 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
418 let payer = self.payer.node_id();
419 let first_hops = self.payer.first_hops();
420 let route = self.router.find_route(
421 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
425 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
429 match self.payer.retry_payment(&route.unwrap(), payment_id) {
431 Err(PaymentSendFailure::ParameterError(_)) |
432 Err(PaymentSendFailure::PathParameterError(_)) => {
433 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
436 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
437 self.retry_payment(payment_id, payment_hash, params)
439 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
440 if let Some(retry) = failed_paths_retry {
441 // Always return Ok for the same reason as noted in pay_internal.
442 let _ = self.retry_payment(payment_id, payment_hash, &retry);
449 /// Removes the payment cached by the given payment hash.
451 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
452 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
453 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
454 self.payment_cache.lock().unwrap().remove(payment_hash);
458 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
459 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
462 #[cfg(feature = "std")]
463 fn has_expired(route_params: &RouteParameters) -> bool {
464 if let Some(expiry_time) = route_params.payment_params.expiry_time {
465 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
469 impl<P: Deref, S: Score, R: Deref, SR: Deref<Target = MultiThreadedLockableScore<S>>, L: Deref, E: EventHandler> EventHandler for InvoicePayer<P, S, R, SR, L, E>
472 R::Target: Router<S>,
475 fn handle_event(&self, event: &Event) {
477 Event::PaymentPathFailed {
478 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
480 if let Some(short_channel_id) = short_channel_id {
481 let path = path.iter().collect::<Vec<_>>();
482 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
485 if payment_id.is_none() {
486 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
487 } else if *rejected_by_dest {
488 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
489 self.payer.abandon_payment(payment_id.unwrap());
490 } else if retry.is_none() {
491 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
492 self.payer.abandon_payment(payment_id.unwrap());
493 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
494 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
497 self.payer.abandon_payment(payment_id.unwrap());
500 Event::PaymentFailed { payment_hash, .. } => {
501 self.remove_cached_payment(&payment_hash);
503 Event::PaymentPathSuccessful { path, .. } => {
504 let path = path.iter().collect::<Vec<_>>();
505 self.scorer.lock().payment_path_successful(&path);
507 Event::PaymentSent { payment_hash, .. } => {
508 let mut payment_cache = self.payment_cache.lock().unwrap();
509 let attempts = payment_cache
510 .remove(payment_hash)
511 .map_or(1, |attempts| attempts + 1);
512 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
517 // Delegate to the decorated event handler unless the payment is retried.
518 self.event_handler.handle_event(event)
525 use crate::{InvoiceBuilder, Currency};
526 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
527 use bitcoin_hashes::sha256::Hash as Sha256;
528 use lightning::ln::PaymentPreimage;
529 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
530 use lightning::ln::functional_test_utils::*;
531 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
532 use lightning::routing::network_graph::NodeId;
533 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
534 use lightning::util::test_utils::TestLogger;
535 use lightning::util::errors::APIError;
536 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
537 use secp256k1::{SecretKey, PublicKey, Secp256k1};
538 use std::cell::RefCell;
539 use std::collections::VecDeque;
540 use std::time::{SystemTime, Duration};
541 use DEFAULT_EXPIRY_TIME;
543 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
544 let payment_hash = Sha256::hash(&payment_preimage.0);
545 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
547 InvoiceBuilder::new(Currency::Bitcoin)
548 .description("test".into())
549 .payment_hash(payment_hash)
550 .payment_secret(PaymentSecret([0; 32]))
551 .duration_since_epoch(duration_since_epoch())
552 .min_final_cltv_expiry(144)
553 .amount_milli_satoshis(128)
554 .build_signed(|hash| {
555 Secp256k1::new().sign_recoverable(hash, &private_key)
560 fn duration_since_epoch() -> Duration {
561 #[cfg(feature = "std")]
562 let duration_since_epoch =
563 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
564 #[cfg(not(feature = "std"))]
565 let duration_since_epoch = Duration::from_secs(1234567);
569 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
570 let payment_hash = Sha256::hash(&payment_preimage.0);
571 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
573 InvoiceBuilder::new(Currency::Bitcoin)
574 .description("test".into())
575 .payment_hash(payment_hash)
576 .payment_secret(PaymentSecret([0; 32]))
577 .duration_since_epoch(duration_since_epoch())
578 .min_final_cltv_expiry(144)
579 .build_signed(|hash| {
580 Secp256k1::new().sign_recoverable(hash, &private_key)
585 #[cfg(feature = "std")]
586 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
587 let payment_hash = Sha256::hash(&payment_preimage.0);
588 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
589 let duration = duration_since_epoch()
590 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
592 InvoiceBuilder::new(Currency::Bitcoin)
593 .description("test".into())
594 .payment_hash(payment_hash)
595 .payment_secret(PaymentSecret([0; 32]))
596 .duration_since_epoch(duration)
597 .min_final_cltv_expiry(144)
598 .amount_milli_satoshis(128)
599 .build_signed(|hash| {
600 Secp256k1::new().sign_recoverable(hash, &private_key)
605 fn pubkey() -> PublicKey {
606 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
610 fn pays_invoice_on_first_attempt() {
611 let event_handled = core::cell::RefCell::new(false);
612 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
614 let payment_preimage = PaymentPreimage([1; 32]);
615 let invoice = invoice(payment_preimage);
616 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
617 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
619 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
620 let router = TestRouter {};
621 let scorer = RefCell::new(TestScorer::new());
622 let logger = TestLogger::new();
624 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
626 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
627 assert_eq!(*payer.attempts.borrow(), 1);
629 invoice_payer.handle_event(&Event::PaymentSent {
630 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
632 assert_eq!(*event_handled.borrow(), true);
633 assert_eq!(*payer.attempts.borrow(), 1);
637 fn pays_invoice_on_retry() {
638 let event_handled = core::cell::RefCell::new(false);
639 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
641 let payment_preimage = PaymentPreimage([1; 32]);
642 let invoice = invoice(payment_preimage);
643 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
644 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
646 let payer = TestPayer::new()
647 .expect_send(Amount::ForInvoice(final_value_msat))
648 .expect_send(Amount::OnRetry(final_value_msat / 2));
649 let router = TestRouter {};
650 let scorer = RefCell::new(TestScorer::new());
651 let logger = TestLogger::new();
653 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
655 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
656 assert_eq!(*payer.attempts.borrow(), 1);
658 let event = Event::PaymentPathFailed {
661 network_update: None,
662 rejected_by_dest: false,
663 all_paths_failed: false,
664 path: TestRouter::path_for_value(final_value_msat),
665 short_channel_id: None,
666 retry: Some(TestRouter::retry_for_invoice(&invoice)),
668 invoice_payer.handle_event(&event);
669 assert_eq!(*event_handled.borrow(), false);
670 assert_eq!(*payer.attempts.borrow(), 2);
672 invoice_payer.handle_event(&Event::PaymentSent {
673 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
675 assert_eq!(*event_handled.borrow(), true);
676 assert_eq!(*payer.attempts.borrow(), 2);
680 fn pays_invoice_on_partial_failure() {
681 let event_handler = |_: &_| { panic!() };
683 let payment_preimage = PaymentPreimage([1; 32]);
684 let invoice = invoice(payment_preimage);
685 let retry = TestRouter::retry_for_invoice(&invoice);
686 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
688 let payer = TestPayer::new()
689 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
690 .fails_with_partial_failure(retry, OnAttempt(2))
691 .expect_send(Amount::ForInvoice(final_value_msat))
692 .expect_send(Amount::OnRetry(final_value_msat / 2))
693 .expect_send(Amount::OnRetry(final_value_msat / 2));
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, RetryAttempts(2));
700 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
704 fn retries_payment_path_for_unknown_payment() {
705 let event_handled = core::cell::RefCell::new(false);
706 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
708 let payment_preimage = PaymentPreimage([1; 32]);
709 let invoice = invoice(payment_preimage);
710 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
711 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
713 let payer = TestPayer::new()
714 .expect_send(Amount::OnRetry(final_value_msat / 2))
715 .expect_send(Amount::OnRetry(final_value_msat / 2));
716 let router = TestRouter {};
717 let scorer = RefCell::new(TestScorer::new());
718 let logger = TestLogger::new();
720 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
722 let payment_id = Some(PaymentId([1; 32]));
723 let event = Event::PaymentPathFailed {
726 network_update: None,
727 rejected_by_dest: false,
728 all_paths_failed: false,
729 path: TestRouter::path_for_value(final_value_msat),
730 short_channel_id: None,
731 retry: Some(TestRouter::retry_for_invoice(&invoice)),
733 invoice_payer.handle_event(&event);
734 assert_eq!(*event_handled.borrow(), false);
735 assert_eq!(*payer.attempts.borrow(), 1);
737 invoice_payer.handle_event(&event);
738 assert_eq!(*event_handled.borrow(), false);
739 assert_eq!(*payer.attempts.borrow(), 2);
741 invoice_payer.handle_event(&Event::PaymentSent {
742 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
744 assert_eq!(*event_handled.borrow(), true);
745 assert_eq!(*payer.attempts.borrow(), 2);
749 fn fails_paying_invoice_after_max_retries() {
750 let event_handled = core::cell::RefCell::new(false);
751 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
753 let payment_preimage = PaymentPreimage([1; 32]);
754 let invoice = invoice(payment_preimage);
755 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
757 let payer = TestPayer::new()
758 .expect_send(Amount::ForInvoice(final_value_msat))
759 .expect_send(Amount::OnRetry(final_value_msat / 2))
760 .expect_send(Amount::OnRetry(final_value_msat / 2));
761 let router = TestRouter {};
762 let scorer = RefCell::new(TestScorer::new());
763 let logger = TestLogger::new();
765 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
767 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
768 assert_eq!(*payer.attempts.borrow(), 1);
770 let event = Event::PaymentPathFailed {
772 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
773 network_update: None,
774 rejected_by_dest: false,
775 all_paths_failed: true,
776 path: TestRouter::path_for_value(final_value_msat),
777 short_channel_id: None,
778 retry: Some(TestRouter::retry_for_invoice(&invoice)),
780 invoice_payer.handle_event(&event);
781 assert_eq!(*event_handled.borrow(), false);
782 assert_eq!(*payer.attempts.borrow(), 2);
784 let event = Event::PaymentPathFailed {
786 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
787 network_update: None,
788 rejected_by_dest: false,
789 all_paths_failed: false,
790 path: TestRouter::path_for_value(final_value_msat / 2),
791 short_channel_id: None,
792 retry: Some(RouteParameters {
793 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
796 invoice_payer.handle_event(&event);
797 assert_eq!(*event_handled.borrow(), false);
798 assert_eq!(*payer.attempts.borrow(), 3);
800 invoice_payer.handle_event(&event);
801 assert_eq!(*event_handled.borrow(), true);
802 assert_eq!(*payer.attempts.borrow(), 3);
806 fn fails_paying_invoice_with_missing_retry_params() {
807 let event_handled = core::cell::RefCell::new(false);
808 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
810 let payment_preimage = PaymentPreimage([1; 32]);
811 let invoice = invoice(payment_preimage);
812 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
814 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
815 let router = TestRouter {};
816 let scorer = RefCell::new(TestScorer::new());
817 let logger = TestLogger::new();
819 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
821 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
822 assert_eq!(*payer.attempts.borrow(), 1);
824 let event = Event::PaymentPathFailed {
826 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
827 network_update: None,
828 rejected_by_dest: false,
829 all_paths_failed: false,
831 short_channel_id: None,
834 invoice_payer.handle_event(&event);
835 assert_eq!(*event_handled.borrow(), true);
836 assert_eq!(*payer.attempts.borrow(), 1);
839 // Expiration is checked only in an std environment
840 #[cfg(feature = "std")]
842 fn fails_paying_invoice_after_expiration() {
843 let event_handled = core::cell::RefCell::new(false);
844 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
846 let payer = TestPayer::new();
847 let router = TestRouter {};
848 let scorer = RefCell::new(TestScorer::new());
849 let logger = TestLogger::new();
851 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
853 let payment_preimage = PaymentPreimage([1; 32]);
854 let invoice = expired_invoice(payment_preimage);
855 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
856 assert_eq!(msg, "Invoice expired prior to send");
857 } else { panic!("Expected Invoice Error"); }
860 // Expiration is checked only in an std environment
861 #[cfg(feature = "std")]
863 fn fails_retrying_invoice_after_expiration() {
864 let event_handled = core::cell::RefCell::new(false);
865 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
867 let payment_preimage = PaymentPreimage([1; 32]);
868 let invoice = invoice(payment_preimage);
869 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
871 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
872 let router = TestRouter {};
873 let scorer = RefCell::new(TestScorer::new());
874 let logger = TestLogger::new();
876 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
878 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
879 assert_eq!(*payer.attempts.borrow(), 1);
881 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
882 retry_data.payment_params.expiry_time = Some(SystemTime::now()
883 .checked_sub(Duration::from_secs(2)).unwrap()
884 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
885 let event = Event::PaymentPathFailed {
887 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
888 network_update: None,
889 rejected_by_dest: false,
890 all_paths_failed: false,
892 short_channel_id: None,
893 retry: Some(retry_data),
895 invoice_payer.handle_event(&event);
896 assert_eq!(*event_handled.borrow(), true);
897 assert_eq!(*payer.attempts.borrow(), 1);
901 fn fails_paying_invoice_after_retry_error() {
902 let event_handled = core::cell::RefCell::new(false);
903 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
905 let payment_preimage = PaymentPreimage([1; 32]);
906 let invoice = invoice(payment_preimage);
907 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
909 let payer = TestPayer::new()
911 .expect_send(Amount::ForInvoice(final_value_msat))
912 .expect_send(Amount::OnRetry(final_value_msat / 2));
913 let router = TestRouter {};
914 let scorer = RefCell::new(TestScorer::new());
915 let logger = TestLogger::new();
917 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
919 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
920 assert_eq!(*payer.attempts.borrow(), 1);
922 let event = Event::PaymentPathFailed {
924 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
925 network_update: None,
926 rejected_by_dest: false,
927 all_paths_failed: false,
928 path: TestRouter::path_for_value(final_value_msat / 2),
929 short_channel_id: None,
930 retry: Some(TestRouter::retry_for_invoice(&invoice)),
932 invoice_payer.handle_event(&event);
933 assert_eq!(*event_handled.borrow(), true);
934 assert_eq!(*payer.attempts.borrow(), 2);
938 fn fails_paying_invoice_after_rejected_by_payee() {
939 let event_handled = core::cell::RefCell::new(false);
940 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
942 let payment_preimage = PaymentPreimage([1; 32]);
943 let invoice = invoice(payment_preimage);
944 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
946 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
947 let router = TestRouter {};
948 let scorer = RefCell::new(TestScorer::new());
949 let logger = TestLogger::new();
951 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
953 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
954 assert_eq!(*payer.attempts.borrow(), 1);
956 let event = Event::PaymentPathFailed {
958 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
959 network_update: None,
960 rejected_by_dest: true,
961 all_paths_failed: false,
963 short_channel_id: None,
964 retry: Some(TestRouter::retry_for_invoice(&invoice)),
966 invoice_payer.handle_event(&event);
967 assert_eq!(*event_handled.borrow(), true);
968 assert_eq!(*payer.attempts.borrow(), 1);
972 fn fails_repaying_invoice_with_pending_payment() {
973 let event_handled = core::cell::RefCell::new(false);
974 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
976 let payment_preimage = PaymentPreimage([1; 32]);
977 let invoice = invoice(payment_preimage);
978 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
980 let payer = TestPayer::new()
981 .expect_send(Amount::ForInvoice(final_value_msat))
982 .expect_send(Amount::ForInvoice(final_value_msat));
983 let router = TestRouter {};
984 let scorer = RefCell::new(TestScorer::new());
985 let logger = TestLogger::new();
987 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
989 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
991 // Cannot repay an invoice pending payment.
992 match invoice_payer.pay_invoice(&invoice) {
993 Err(PaymentError::Invoice("payment pending")) => {},
994 Err(_) => panic!("unexpected error"),
995 Ok(_) => panic!("expected invoice error"),
998 // Can repay an invoice once cleared from cache.
999 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1000 invoice_payer.remove_cached_payment(&payment_hash);
1001 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1003 // Cannot retry paying an invoice if cleared from cache.
1004 invoice_payer.remove_cached_payment(&payment_hash);
1005 let event = Event::PaymentPathFailed {
1008 network_update: None,
1009 rejected_by_dest: false,
1010 all_paths_failed: false,
1012 short_channel_id: None,
1013 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1015 invoice_payer.handle_event(&event);
1016 assert_eq!(*event_handled.borrow(), true);
1020 fn fails_paying_invoice_with_routing_errors() {
1021 let payer = TestPayer::new();
1022 let router = FailingRouter {};
1023 let scorer = RefCell::new(TestScorer::new());
1024 let logger = TestLogger::new();
1026 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1028 let payment_preimage = PaymentPreimage([1; 32]);
1029 let invoice = invoice(payment_preimage);
1030 match invoice_payer.pay_invoice(&invoice) {
1031 Err(PaymentError::Routing(_)) => {},
1032 Err(_) => panic!("unexpected error"),
1033 Ok(_) => panic!("expected routing error"),
1038 fn fails_paying_invoice_with_sending_errors() {
1039 let payment_preimage = PaymentPreimage([1; 32]);
1040 let invoice = invoice(payment_preimage);
1041 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1043 let payer = TestPayer::new()
1044 .fails_on_attempt(1)
1045 .expect_send(Amount::ForInvoice(final_value_msat));
1046 let router = TestRouter {};
1047 let scorer = RefCell::new(TestScorer::new());
1048 let logger = TestLogger::new();
1050 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1052 match invoice_payer.pay_invoice(&invoice) {
1053 Err(PaymentError::Sending(_)) => {},
1054 Err(_) => panic!("unexpected error"),
1055 Ok(_) => panic!("expected sending error"),
1060 fn pays_zero_value_invoice_using_amount() {
1061 let event_handled = core::cell::RefCell::new(false);
1062 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1064 let payment_preimage = PaymentPreimage([1; 32]);
1065 let invoice = zero_value_invoice(payment_preimage);
1066 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1067 let final_value_msat = 100;
1069 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1070 let router = TestRouter {};
1071 let scorer = RefCell::new(TestScorer::new());
1072 let logger = TestLogger::new();
1074 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1077 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1078 assert_eq!(*payer.attempts.borrow(), 1);
1080 invoice_payer.handle_event(&Event::PaymentSent {
1081 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1083 assert_eq!(*event_handled.borrow(), true);
1084 assert_eq!(*payer.attempts.borrow(), 1);
1088 fn fails_paying_zero_value_invoice_with_amount() {
1089 let event_handled = core::cell::RefCell::new(false);
1090 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1092 let payer = TestPayer::new();
1093 let router = TestRouter {};
1094 let scorer = RefCell::new(TestScorer::new());
1095 let logger = TestLogger::new();
1097 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1099 let payment_preimage = PaymentPreimage([1; 32]);
1100 let invoice = invoice(payment_preimage);
1102 // Cannot repay an invoice pending payment.
1103 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1104 Err(PaymentError::Invoice("amount unexpected")) => {},
1105 Err(_) => panic!("unexpected error"),
1106 Ok(_) => panic!("expected invoice error"),
1111 fn pays_pubkey_with_amount() {
1112 let event_handled = core::cell::RefCell::new(false);
1113 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1115 let pubkey = pubkey();
1116 let payment_preimage = PaymentPreimage([1; 32]);
1117 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1118 let final_value_msat = 100;
1119 let final_cltv_expiry_delta = 42;
1121 let payer = TestPayer::new()
1122 .expect_send(Amount::Spontaneous(final_value_msat))
1123 .expect_send(Amount::OnRetry(final_value_msat));
1124 let router = TestRouter {};
1125 let scorer = RefCell::new(TestScorer::new());
1126 let logger = TestLogger::new();
1128 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1130 let payment_id = Some(invoice_payer.pay_pubkey(
1131 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1133 assert_eq!(*payer.attempts.borrow(), 1);
1135 let retry = RouteParameters {
1136 payment_params: PaymentParameters::for_keysend(pubkey),
1138 final_cltv_expiry_delta,
1140 let event = Event::PaymentPathFailed {
1143 network_update: None,
1144 rejected_by_dest: false,
1145 all_paths_failed: false,
1147 short_channel_id: None,
1150 invoice_payer.handle_event(&event);
1151 assert_eq!(*event_handled.borrow(), false);
1152 assert_eq!(*payer.attempts.borrow(), 2);
1154 invoice_payer.handle_event(&Event::PaymentSent {
1155 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1157 assert_eq!(*event_handled.borrow(), true);
1158 assert_eq!(*payer.attempts.borrow(), 2);
1162 fn scores_failed_channel() {
1163 let event_handled = core::cell::RefCell::new(false);
1164 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1166 let payment_preimage = PaymentPreimage([1; 32]);
1167 let invoice = invoice(payment_preimage);
1168 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1169 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1170 let path = TestRouter::path_for_value(final_value_msat);
1171 let short_channel_id = Some(path[0].short_channel_id);
1173 // Expect that scorer is given short_channel_id upon handling the event.
1174 let payer = TestPayer::new()
1175 .expect_send(Amount::ForInvoice(final_value_msat))
1176 .expect_send(Amount::OnRetry(final_value_msat / 2));
1177 let router = TestRouter {};
1178 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1179 path: path.clone(), short_channel_id: path[0].short_channel_id,
1181 let logger = TestLogger::new();
1183 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1185 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1186 let event = Event::PaymentPathFailed {
1189 network_update: None,
1190 rejected_by_dest: false,
1191 all_paths_failed: false,
1194 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1196 invoice_payer.handle_event(&event);
1200 fn scores_successful_channels() {
1201 let event_handled = core::cell::RefCell::new(false);
1202 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1204 let payment_preimage = PaymentPreimage([1; 32]);
1205 let invoice = invoice(payment_preimage);
1206 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1207 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1208 let route = TestRouter::route_for_value(final_value_msat);
1210 // Expect that scorer is given short_channel_id upon handling the event.
1211 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1212 let router = TestRouter {};
1213 let scorer = RefCell::new(TestScorer::new()
1214 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1215 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1217 let logger = TestLogger::new();
1219 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1221 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1222 let event = Event::PaymentPathSuccessful {
1223 payment_id, payment_hash, path: route.paths[0].clone()
1225 invoice_payer.handle_event(&event);
1226 let event = Event::PaymentPathSuccessful {
1227 payment_id, payment_hash, path: route.paths[1].clone()
1229 invoice_payer.handle_event(&event);
1235 fn route_for_value(final_value_msat: u64) -> Route {
1239 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1240 channel_features: ChannelFeatures::empty(),
1241 node_features: NodeFeatures::empty(),
1242 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1245 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1246 channel_features: ChannelFeatures::empty(),
1247 node_features: NodeFeatures::empty(),
1248 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1251 payment_params: None,
1255 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1256 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1259 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1260 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1261 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1262 .with_route_hints(invoice.route_hints());
1263 if let Some(features) = invoice.features() {
1264 payment_params = payment_params.with_features(features.clone());
1266 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1270 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1275 impl<S: Score> Router<S> for TestRouter {
1277 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1278 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1279 ) -> Result<Route, LightningError> {
1281 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1286 struct FailingRouter;
1288 impl<S: Score> Router<S> for FailingRouter {
1290 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1291 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1292 ) -> Result<Route, LightningError> {
1293 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1298 expectations: Option<VecDeque<PaymentPath>>,
1303 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1304 Success { path: Vec<RouteHop> },
1314 fn expect(mut self, expectation: PaymentPath) -> Self {
1315 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1321 impl lightning::util::ser::Writeable for TestScorer {
1322 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1325 impl Score for TestScorer {
1326 fn channel_penalty_msat(
1327 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
1330 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1331 if let Some(expectations) = &mut self.expectations {
1332 match expectations.pop_front() {
1333 Some(PaymentPath::Failure { path, short_channel_id }) => {
1334 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1335 assert_eq!(actual_short_channel_id, short_channel_id);
1337 Some(PaymentPath::Success { path }) => {
1338 panic!("Unexpected successful payment path: {:?}", path)
1340 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1345 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1346 if let Some(expectations) = &mut self.expectations {
1347 match expectations.pop_front() {
1348 Some(PaymentPath::Failure { path, .. }) => {
1349 panic!("Unexpected payment path failure: {:?}", path)
1351 Some(PaymentPath::Success { path }) => {
1352 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1354 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1360 impl Drop for TestScorer {
1361 fn drop(&mut self) {
1362 if std::thread::panicking() {
1366 if let Some(expectations) = &self.expectations {
1367 if !expectations.is_empty() {
1368 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1375 expectations: core::cell::RefCell<VecDeque<Amount>>,
1376 attempts: core::cell::RefCell<usize>,
1377 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1380 #[derive(Clone, Debug, PartialEq, Eq)]
1387 struct OnAttempt(usize);
1392 expectations: core::cell::RefCell::new(VecDeque::new()),
1393 attempts: core::cell::RefCell::new(0),
1394 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1398 fn expect_send(self, value_msat: Amount) -> Self {
1399 self.expectations.borrow_mut().push_back(value_msat);
1403 fn fails_on_attempt(self, attempt: usize) -> Self {
1404 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1405 self.fails_with(failure, OnAttempt(attempt))
1408 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1409 self.fails_with(PaymentSendFailure::PartialFailure {
1411 failed_paths_retry: Some(retry),
1412 payment_id: PaymentId([1; 32]),
1416 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1417 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1421 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1422 let mut attempts = self.attempts.borrow_mut();
1425 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1426 Some(failure) => Err(failure),
1427 None => Ok(PaymentId([1; 32])),
1431 fn check_value_msats(&self, actual_value_msats: Amount) {
1432 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1433 if let Some(expected_value_msats) = expected_value_msats {
1434 assert_eq!(actual_value_msats, expected_value_msats);
1436 panic!("Unexpected amount: {:?}", actual_value_msats);
1441 impl Drop for TestPayer {
1442 fn drop(&mut self) {
1443 if std::thread::panicking() {
1447 if !self.expectations.borrow().is_empty() {
1448 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1453 impl Payer for TestPayer {
1454 fn node_id(&self) -> PublicKey {
1455 let secp_ctx = Secp256k1::new();
1456 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1459 fn first_hops(&self) -> Vec<ChannelDetails> {
1464 &self, route: &Route, _payment_hash: PaymentHash,
1465 _payment_secret: &Option<PaymentSecret>
1466 ) -> Result<PaymentId, PaymentSendFailure> {
1467 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1468 self.check_attempts()
1471 fn send_spontaneous_payment(
1472 &self, route: &Route, _payment_preimage: PaymentPreimage,
1473 ) -> Result<PaymentId, PaymentSendFailure> {
1474 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1475 self.check_attempts()
1479 &self, route: &Route, _payment_id: PaymentId
1480 ) -> Result<(), PaymentSendFailure> {
1481 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1482 self.check_attempts().map(|_| ())
1485 fn abandon_payment(&self, _payment_id: PaymentId) { }
1488 // *** Full Featured Functional Tests with a Real ChannelManager ***
1489 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1491 impl<S: Score> Router<S> for ManualRouter {
1493 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1494 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1495 ) -> Result<Route, LightningError> {
1496 self.0.borrow_mut().pop_front().unwrap()
1500 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1501 self.0.borrow_mut().push_back(result);
1504 impl Drop for ManualRouter {
1505 fn drop(&mut self) {
1506 if std::thread::panicking() {
1509 assert!(self.0.borrow_mut().is_empty());
1514 fn retry_multi_path_single_failed_payment() {
1515 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1516 let chanmon_cfgs = create_chanmon_cfgs(2);
1517 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1518 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1519 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1522 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1523 let chans = nodes[0].node.list_usable_channels();
1524 let mut route = Route {
1527 pubkey: nodes[1].node.get_our_node_id(),
1528 node_features: NodeFeatures::known(),
1529 short_channel_id: chans[0].short_channel_id.unwrap(),
1530 channel_features: ChannelFeatures::known(),
1532 cltv_expiry_delta: 100,
1535 pubkey: nodes[1].node.get_our_node_id(),
1536 node_features: NodeFeatures::known(),
1537 short_channel_id: chans[1].short_channel_id.unwrap(),
1538 channel_features: ChannelFeatures::known(),
1539 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1540 cltv_expiry_delta: 100,
1543 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1545 let router = ManualRouter(RefCell::new(VecDeque::new()));
1546 router.expect_find_route(Ok(route.clone()));
1547 // On retry, split the payment across both channels.
1548 route.paths[0][0].fee_msat = 50_000_001;
1549 route.paths[1][0].fee_msat = 50_000_000;
1550 router.expect_find_route(Ok(route.clone()));
1552 let event_handler = |_: &_| { panic!(); };
1553 let scorer = RefCell::new(TestScorer::new());
1554 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1556 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1557 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1558 duration_since_epoch()).unwrap())
1560 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1561 assert_eq!(htlc_msgs.len(), 2);
1562 check_added_monitors!(nodes[0], 2);
1566 fn immediate_retry_on_failure() {
1567 // Tests that we can/will retry immediately after a failure
1568 let chanmon_cfgs = create_chanmon_cfgs(2);
1569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1573 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1574 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1575 let chans = nodes[0].node.list_usable_channels();
1576 let mut route = Route {
1579 pubkey: nodes[1].node.get_our_node_id(),
1580 node_features: NodeFeatures::known(),
1581 short_channel_id: chans[0].short_channel_id.unwrap(),
1582 channel_features: ChannelFeatures::known(),
1583 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1584 cltv_expiry_delta: 100,
1587 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1589 let router = ManualRouter(RefCell::new(VecDeque::new()));
1590 router.expect_find_route(Ok(route.clone()));
1591 // On retry, split the payment across both channels.
1592 route.paths.push(route.paths[0].clone());
1593 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1594 route.paths[0][0].fee_msat = 50_000_000;
1595 route.paths[1][0].fee_msat = 50_000_001;
1596 router.expect_find_route(Ok(route.clone()));
1598 let event_handler = |_: &_| { panic!(); };
1599 let scorer = RefCell::new(TestScorer::new());
1600 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1602 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1603 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1604 duration_since_epoch()).unwrap())
1606 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1607 assert_eq!(htlc_msgs.len(), 2);
1608 check_added_monitors!(nodes[0], 2);
1612 fn no_extra_retries_on_back_to_back_fail() {
1613 // In a previous release, we had a race where we may exceed the payment retry count if we
1614 // get two failures in a row with the second having `all_paths_failed` set.
1615 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1616 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1617 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1618 // pending which we will see later. Thus, when we previously removed the retry tracking map
1619 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1620 // retry entry even though more events for the same payment were still pending. This led to
1621 // us retrying a payment again even though we'd already given up on it.
1623 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1624 // is used to remove the payment retry counter entries instead. This tests for the specific
1625 // excess-retry case while also testing `PaymentFailed` generation.
1627 let chanmon_cfgs = create_chanmon_cfgs(3);
1628 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1629 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1630 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1632 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;
1633 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;
1635 let mut route = Route {
1638 pubkey: nodes[1].node.get_our_node_id(),
1639 node_features: NodeFeatures::known(),
1640 short_channel_id: chan_1_scid,
1641 channel_features: ChannelFeatures::known(),
1643 cltv_expiry_delta: 100,
1645 pubkey: nodes[2].node.get_our_node_id(),
1646 node_features: NodeFeatures::known(),
1647 short_channel_id: chan_2_scid,
1648 channel_features: ChannelFeatures::known(),
1649 fee_msat: 100_000_000,
1650 cltv_expiry_delta: 100,
1653 pubkey: nodes[1].node.get_our_node_id(),
1654 node_features: NodeFeatures::known(),
1655 short_channel_id: chan_1_scid,
1656 channel_features: ChannelFeatures::known(),
1658 cltv_expiry_delta: 100,
1660 pubkey: nodes[2].node.get_our_node_id(),
1661 node_features: NodeFeatures::known(),
1662 short_channel_id: chan_2_scid,
1663 channel_features: ChannelFeatures::known(),
1664 fee_msat: 100_000_000,
1665 cltv_expiry_delta: 100,
1668 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1670 let router = ManualRouter(RefCell::new(VecDeque::new()));
1671 router.expect_find_route(Ok(route.clone()));
1672 // On retry, we'll only be asked for one path
1673 route.paths.remove(1);
1674 router.expect_find_route(Ok(route.clone()));
1676 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1677 let event_handler = |event: &Event| {
1678 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1679 event_checker(event);
1681 let scorer = RefCell::new(TestScorer::new());
1682 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1684 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1685 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1686 duration_since_epoch()).unwrap())
1688 let htlc_updates = SendEvent::from_node(&nodes[0]);
1689 check_added_monitors!(nodes[0], 1);
1690 assert_eq!(htlc_updates.msgs.len(), 1);
1692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1694 check_added_monitors!(nodes[1], 1);
1695 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1697 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1698 check_added_monitors!(nodes[0], 1);
1699 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1701 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1702 check_added_monitors!(nodes[0], 1);
1703 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1705 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1706 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1707 check_added_monitors!(nodes[1], 1);
1708 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1710 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1711 check_added_monitors!(nodes[1], 1);
1712 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1714 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1715 check_added_monitors!(nodes[0], 1);
1717 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1718 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1719 check_added_monitors!(nodes[0], 1);
1720 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1722 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1723 check_added_monitors!(nodes[1], 1);
1724 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1726 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1727 check_added_monitors!(nodes[1], 1);
1728 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1730 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1731 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1732 check_added_monitors!(nodes[0], 1);
1734 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1735 check_added_monitors!(nodes[0], 1);
1736 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1738 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1739 check_added_monitors!(nodes[1], 1);
1740 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1741 check_added_monitors!(nodes[1], 1);
1742 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1744 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1745 check_added_monitors!(nodes[0], 1);
1747 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1748 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1749 // with it set. The first event will use up the only retry we are allowed, with the second
1750 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1751 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1752 // if the final HTLC failed.
1753 expected_events.borrow_mut().push_back(&|ev: &Event| {
1754 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1755 assert!(!rejected_by_dest);
1756 assert!(all_paths_failed);
1757 } else { panic!("Unexpected event"); }
1759 nodes[0].node.process_pending_events(&invoice_payer);
1760 assert!(expected_events.borrow().is_empty());
1762 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1763 check_added_monitors!(nodes[0], 1);
1765 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1766 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1767 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1768 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1769 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1771 expected_events.borrow_mut().push_back(&|ev: &Event| {
1772 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1773 assert!(!rejected_by_dest);
1774 assert!(all_paths_failed);
1775 } else { panic!("Unexpected event"); }
1777 expected_events.borrow_mut().push_back(&|ev: &Event| {
1778 if let Event::PaymentFailed { .. } = ev {
1779 } else { panic!("Unexpected event"); }
1781 nodes[0].node.process_pending_events(&invoice_payer);
1782 assert!(expected_events.borrow().is_empty());