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, 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, R, S: Deref, L: Deref, E: EventHandler>
166 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
167 S::Target: for <'a> LockableScore<'a>,
175 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
176 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
177 retry_attempts: RetryAttempts,
180 /// A trait defining behavior of an [`Invoice`] payer.
182 /// Returns the payer's node id.
183 fn node_id(&self) -> PublicKey;
185 /// Returns the payer's channels.
186 fn first_hops(&self) -> Vec<ChannelDetails>;
188 /// Sends a payment over the Lightning Network using the given [`Route`].
190 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
191 ) -> Result<PaymentId, PaymentSendFailure>;
193 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
194 fn send_spontaneous_payment(
195 &self, route: &Route, payment_preimage: PaymentPreimage
196 ) -> Result<PaymentId, PaymentSendFailure>;
198 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
199 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
201 /// Signals that no further retries for the given payment will occur.
202 fn abandon_payment(&self, payment_id: PaymentId);
205 /// A trait defining behavior for routing an [`Invoice`] payment.
206 pub trait Router<S: Score> {
207 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
209 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
210 first_hops: Option<&[&ChannelDetails]>, scorer: &S
211 ) -> Result<Route, LightningError>;
214 /// Number of attempts to retry payment path failures for an [`Invoice`].
216 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
217 /// payments, if this is less than the total number of paths, we will never even retry all of the
219 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
220 pub struct RetryAttempts(pub usize);
222 /// An error that may occur when making a payment.
223 #[derive(Clone, Debug)]
224 pub enum PaymentError {
225 /// An error resulting from the provided [`Invoice`] or payment hash.
226 Invoice(&'static str),
227 /// An error occurring when finding a route.
228 Routing(LightningError),
229 /// An error occurring when sending a payment.
230 Sending(PaymentSendFailure),
233 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> InvoicePayer<P, R, S, L, E>
236 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
237 S::Target: for <'a> LockableScore<'a>,
240 /// Creates an invoice payer that retries failed payment paths.
242 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
243 /// `retry_attempts` has been exceeded for a given [`Invoice`].
245 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
253 payment_cache: Mutex::new(HashMap::new()),
258 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
260 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
261 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
263 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
264 if invoice.amount_milli_satoshis().is_none() {
265 Err(PaymentError::Invoice("amount missing"))
267 self.pay_invoice_using_amount(invoice, None)
271 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
272 /// case a retry is needed.
274 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
275 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
277 pub fn pay_zero_value_invoice(
278 &self, invoice: &Invoice, amount_msats: u64
279 ) -> Result<PaymentId, PaymentError> {
280 if invoice.amount_milli_satoshis().is_some() {
281 Err(PaymentError::Invoice("amount unexpected"))
283 self.pay_invoice_using_amount(invoice, Some(amount_msats))
287 fn pay_invoice_using_amount(
288 &self, invoice: &Invoice, amount_msats: Option<u64>
289 ) -> Result<PaymentId, PaymentError> {
290 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
292 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
293 match self.payment_cache.lock().unwrap().entry(payment_hash) {
294 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
295 hash_map::Entry::Vacant(entry) => entry.insert(0),
298 let payment_secret = Some(invoice.payment_secret().clone());
299 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
300 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
301 .with_route_hints(invoice.route_hints());
302 if let Some(features) = invoice.features() {
303 payment_params = payment_params.with_features(features.clone());
305 let route_params = RouteParameters {
307 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
308 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
311 let send_payment = |route: &Route| {
312 self.payer.send_payment(route, payment_hash, &payment_secret)
314 self.pay_internal(&route_params, payment_hash, send_payment)
315 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
318 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
319 /// case a retry is needed.
321 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
322 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
324 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
325 final_cltv_expiry_delta: u32
326 ) -> Result<PaymentId, PaymentError> {
327 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
328 match self.payment_cache.lock().unwrap().entry(payment_hash) {
329 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
330 hash_map::Entry::Vacant(entry) => entry.insert(0),
333 let route_params = RouteParameters {
334 payment_params: PaymentParameters::for_keysend(pubkey),
335 final_value_msat: amount_msats,
336 final_cltv_expiry_delta,
339 let send_payment = |route: &Route| {
340 self.payer.send_spontaneous_payment(route, payment_preimage)
342 self.pay_internal(&route_params, payment_hash, send_payment)
343 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
346 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
347 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
348 ) -> Result<PaymentId, PaymentError> {
349 #[cfg(feature = "std")] {
350 if has_expired(params) {
351 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
352 return Err(PaymentError::Invoice("Invoice expired prior to send"));
356 let payer = self.payer.node_id();
357 let first_hops = self.payer.first_hops();
358 let route = self.router.find_route(
359 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
361 ).map_err(|e| PaymentError::Routing(e))?;
363 match send_payment(&route) {
364 Ok(payment_id) => Ok(payment_id),
366 PaymentSendFailure::ParameterError(_) => Err(e),
367 PaymentSendFailure::PathParameterError(_) => Err(e),
368 PaymentSendFailure::AllFailedRetrySafe(_) => {
369 let mut payment_cache = self.payment_cache.lock().unwrap();
370 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
371 if *retry_count >= self.retry_attempts.0 {
375 core::mem::drop(payment_cache);
376 Ok(self.pay_internal(params, payment_hash, send_payment)?)
379 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
380 if let Some(retry_data) = failed_paths_retry {
381 // Some paths were sent, even if we failed to send the full MPP value our
382 // recipient may misbehave and claim the funds, at which point we have to
383 // consider the payment sent, so return `Ok()` here, ignoring any retry
385 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
388 // This may happen if we send a payment and some paths fail, but
389 // only due to a temporary monitor failure or the like, implying
390 // they're really in-flight, but we haven't sent the initial
391 // HTLC-Add messages yet.
396 }.map_err(|e| PaymentError::Sending(e))
400 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
401 ) -> Result<(), ()> {
402 let max_payment_attempts = self.retry_attempts.0 + 1;
403 let attempts = *self.payment_cache.lock().unwrap()
405 .and_modify(|attempts| *attempts += 1)
408 if attempts >= max_payment_attempts {
409 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
413 #[cfg(feature = "std")] {
414 if has_expired(params) {
415 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
420 let payer = self.payer.node_id();
421 let first_hops = self.payer.first_hops();
422 let route = self.router.find_route(
423 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
427 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
431 match self.payer.retry_payment(&route.unwrap(), payment_id) {
433 Err(PaymentSendFailure::ParameterError(_)) |
434 Err(PaymentSendFailure::PathParameterError(_)) => {
435 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
438 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
439 self.retry_payment(payment_id, payment_hash, params)
441 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
442 if let Some(retry) = failed_paths_retry {
443 // Always return Ok for the same reason as noted in pay_internal.
444 let _ = self.retry_payment(payment_id, payment_hash, &retry);
451 /// Removes the payment cached by the given payment hash.
453 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
454 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
455 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
456 self.payment_cache.lock().unwrap().remove(payment_hash);
460 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
461 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
464 #[cfg(feature = "std")]
465 fn has_expired(route_params: &RouteParameters) -> bool {
466 if let Some(expiry_time) = route_params.payment_params.expiry_time {
467 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
471 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler> EventHandler for InvoicePayer<P, R, S, L, E>
474 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
475 S::Target: for <'a> LockableScore<'a>,
478 fn handle_event(&self, event: &Event) {
480 Event::PaymentPathFailed {
481 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
483 if let Some(short_channel_id) = short_channel_id {
484 let path = path.iter().collect::<Vec<_>>();
485 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
488 if payment_id.is_none() {
489 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
490 } else if *rejected_by_dest {
491 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
492 self.payer.abandon_payment(payment_id.unwrap());
493 } else if retry.is_none() {
494 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
495 self.payer.abandon_payment(payment_id.unwrap());
496 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
497 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
500 self.payer.abandon_payment(payment_id.unwrap());
503 Event::PaymentFailed { payment_hash, .. } => {
504 self.remove_cached_payment(&payment_hash);
506 Event::PaymentPathSuccessful { path, .. } => {
507 let path = path.iter().collect::<Vec<_>>();
508 self.scorer.lock().payment_path_successful(&path);
510 Event::PaymentSent { payment_hash, .. } => {
511 let mut payment_cache = self.payment_cache.lock().unwrap();
512 let attempts = payment_cache
513 .remove(payment_hash)
514 .map_or(1, |attempts| attempts + 1);
515 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
520 // Delegate to the decorated event handler unless the payment is retried.
521 self.event_handler.handle_event(event)
528 use crate::{InvoiceBuilder, Currency};
529 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
530 use bitcoin_hashes::sha256::Hash as Sha256;
531 use lightning::ln::PaymentPreimage;
532 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
533 use lightning::ln::functional_test_utils::*;
534 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
535 use lightning::routing::network_graph::NodeId;
536 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
537 use lightning::util::test_utils::TestLogger;
538 use lightning::util::errors::APIError;
539 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
540 use secp256k1::{SecretKey, PublicKey, Secp256k1};
541 use std::cell::RefCell;
542 use std::collections::VecDeque;
543 use std::time::{SystemTime, Duration};
544 use DEFAULT_EXPIRY_TIME;
546 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
547 let payment_hash = Sha256::hash(&payment_preimage.0);
548 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
550 InvoiceBuilder::new(Currency::Bitcoin)
551 .description("test".into())
552 .payment_hash(payment_hash)
553 .payment_secret(PaymentSecret([0; 32]))
554 .duration_since_epoch(duration_since_epoch())
555 .min_final_cltv_expiry(144)
556 .amount_milli_satoshis(128)
557 .build_signed(|hash| {
558 Secp256k1::new().sign_recoverable(hash, &private_key)
563 fn duration_since_epoch() -> Duration {
564 #[cfg(feature = "std")]
565 let duration_since_epoch =
566 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
567 #[cfg(not(feature = "std"))]
568 let duration_since_epoch = Duration::from_secs(1234567);
572 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
573 let payment_hash = Sha256::hash(&payment_preimage.0);
574 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
576 InvoiceBuilder::new(Currency::Bitcoin)
577 .description("test".into())
578 .payment_hash(payment_hash)
579 .payment_secret(PaymentSecret([0; 32]))
580 .duration_since_epoch(duration_since_epoch())
581 .min_final_cltv_expiry(144)
582 .build_signed(|hash| {
583 Secp256k1::new().sign_recoverable(hash, &private_key)
588 #[cfg(feature = "std")]
589 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
590 let payment_hash = Sha256::hash(&payment_preimage.0);
591 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
592 let duration = duration_since_epoch()
593 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
595 InvoiceBuilder::new(Currency::Bitcoin)
596 .description("test".into())
597 .payment_hash(payment_hash)
598 .payment_secret(PaymentSecret([0; 32]))
599 .duration_since_epoch(duration)
600 .min_final_cltv_expiry(144)
601 .amount_milli_satoshis(128)
602 .build_signed(|hash| {
603 Secp256k1::new().sign_recoverable(hash, &private_key)
608 fn pubkey() -> PublicKey {
609 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
613 fn pays_invoice_on_first_attempt() {
614 let event_handled = core::cell::RefCell::new(false);
615 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
617 let payment_preimage = PaymentPreimage([1; 32]);
618 let invoice = invoice(payment_preimage);
619 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
620 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
622 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
623 let router = TestRouter {};
624 let scorer = RefCell::new(TestScorer::new());
625 let logger = TestLogger::new();
627 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
629 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
630 assert_eq!(*payer.attempts.borrow(), 1);
632 invoice_payer.handle_event(&Event::PaymentSent {
633 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
635 assert_eq!(*event_handled.borrow(), true);
636 assert_eq!(*payer.attempts.borrow(), 1);
640 fn pays_invoice_on_retry() {
641 let event_handled = core::cell::RefCell::new(false);
642 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
644 let payment_preimage = PaymentPreimage([1; 32]);
645 let invoice = invoice(payment_preimage);
646 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
647 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
649 let payer = TestPayer::new()
650 .expect_send(Amount::ForInvoice(final_value_msat))
651 .expect_send(Amount::OnRetry(final_value_msat / 2));
652 let router = TestRouter {};
653 let scorer = RefCell::new(TestScorer::new());
654 let logger = TestLogger::new();
656 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
658 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
659 assert_eq!(*payer.attempts.borrow(), 1);
661 let event = Event::PaymentPathFailed {
664 network_update: None,
665 rejected_by_dest: false,
666 all_paths_failed: false,
667 path: TestRouter::path_for_value(final_value_msat),
668 short_channel_id: None,
669 retry: Some(TestRouter::retry_for_invoice(&invoice)),
671 invoice_payer.handle_event(&event);
672 assert_eq!(*event_handled.borrow(), false);
673 assert_eq!(*payer.attempts.borrow(), 2);
675 invoice_payer.handle_event(&Event::PaymentSent {
676 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
678 assert_eq!(*event_handled.borrow(), true);
679 assert_eq!(*payer.attempts.borrow(), 2);
683 fn pays_invoice_on_partial_failure() {
684 let event_handler = |_: &_| { panic!() };
686 let payment_preimage = PaymentPreimage([1; 32]);
687 let invoice = invoice(payment_preimage);
688 let retry = TestRouter::retry_for_invoice(&invoice);
689 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
691 let payer = TestPayer::new()
692 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
693 .fails_with_partial_failure(retry, OnAttempt(2))
694 .expect_send(Amount::ForInvoice(final_value_msat))
695 .expect_send(Amount::OnRetry(final_value_msat / 2))
696 .expect_send(Amount::OnRetry(final_value_msat / 2));
697 let router = TestRouter {};
698 let scorer = RefCell::new(TestScorer::new());
699 let logger = TestLogger::new();
701 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
703 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
707 fn retries_payment_path_for_unknown_payment() {
708 let event_handled = core::cell::RefCell::new(false);
709 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
711 let payment_preimage = PaymentPreimage([1; 32]);
712 let invoice = invoice(payment_preimage);
713 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
714 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
716 let payer = TestPayer::new()
717 .expect_send(Amount::OnRetry(final_value_msat / 2))
718 .expect_send(Amount::OnRetry(final_value_msat / 2));
719 let router = TestRouter {};
720 let scorer = RefCell::new(TestScorer::new());
721 let logger = TestLogger::new();
723 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
725 let payment_id = Some(PaymentId([1; 32]));
726 let event = Event::PaymentPathFailed {
729 network_update: None,
730 rejected_by_dest: false,
731 all_paths_failed: false,
732 path: TestRouter::path_for_value(final_value_msat),
733 short_channel_id: None,
734 retry: Some(TestRouter::retry_for_invoice(&invoice)),
736 invoice_payer.handle_event(&event);
737 assert_eq!(*event_handled.borrow(), false);
738 assert_eq!(*payer.attempts.borrow(), 1);
740 invoice_payer.handle_event(&event);
741 assert_eq!(*event_handled.borrow(), false);
742 assert_eq!(*payer.attempts.borrow(), 2);
744 invoice_payer.handle_event(&Event::PaymentSent {
745 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
747 assert_eq!(*event_handled.borrow(), true);
748 assert_eq!(*payer.attempts.borrow(), 2);
752 fn fails_paying_invoice_after_max_retries() {
753 let event_handled = core::cell::RefCell::new(false);
754 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
756 let payment_preimage = PaymentPreimage([1; 32]);
757 let invoice = invoice(payment_preimage);
758 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
760 let payer = TestPayer::new()
761 .expect_send(Amount::ForInvoice(final_value_msat))
762 .expect_send(Amount::OnRetry(final_value_msat / 2))
763 .expect_send(Amount::OnRetry(final_value_msat / 2));
764 let router = TestRouter {};
765 let scorer = RefCell::new(TestScorer::new());
766 let logger = TestLogger::new();
768 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
770 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
771 assert_eq!(*payer.attempts.borrow(), 1);
773 let event = Event::PaymentPathFailed {
775 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
776 network_update: None,
777 rejected_by_dest: false,
778 all_paths_failed: true,
779 path: TestRouter::path_for_value(final_value_msat),
780 short_channel_id: None,
781 retry: Some(TestRouter::retry_for_invoice(&invoice)),
783 invoice_payer.handle_event(&event);
784 assert_eq!(*event_handled.borrow(), false);
785 assert_eq!(*payer.attempts.borrow(), 2);
787 let event = Event::PaymentPathFailed {
789 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
790 network_update: None,
791 rejected_by_dest: false,
792 all_paths_failed: false,
793 path: TestRouter::path_for_value(final_value_msat / 2),
794 short_channel_id: None,
795 retry: Some(RouteParameters {
796 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
799 invoice_payer.handle_event(&event);
800 assert_eq!(*event_handled.borrow(), false);
801 assert_eq!(*payer.attempts.borrow(), 3);
803 invoice_payer.handle_event(&event);
804 assert_eq!(*event_handled.borrow(), true);
805 assert_eq!(*payer.attempts.borrow(), 3);
809 fn fails_paying_invoice_with_missing_retry_params() {
810 let event_handled = core::cell::RefCell::new(false);
811 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
813 let payment_preimage = PaymentPreimage([1; 32]);
814 let invoice = invoice(payment_preimage);
815 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
817 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
818 let router = TestRouter {};
819 let scorer = RefCell::new(TestScorer::new());
820 let logger = TestLogger::new();
822 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
824 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
825 assert_eq!(*payer.attempts.borrow(), 1);
827 let event = Event::PaymentPathFailed {
829 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
830 network_update: None,
831 rejected_by_dest: false,
832 all_paths_failed: false,
834 short_channel_id: None,
837 invoice_payer.handle_event(&event);
838 assert_eq!(*event_handled.borrow(), true);
839 assert_eq!(*payer.attempts.borrow(), 1);
842 // Expiration is checked only in an std environment
843 #[cfg(feature = "std")]
845 fn fails_paying_invoice_after_expiration() {
846 let event_handled = core::cell::RefCell::new(false);
847 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
849 let payer = TestPayer::new();
850 let router = TestRouter {};
851 let scorer = RefCell::new(TestScorer::new());
852 let logger = TestLogger::new();
854 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
856 let payment_preimage = PaymentPreimage([1; 32]);
857 let invoice = expired_invoice(payment_preimage);
858 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
859 assert_eq!(msg, "Invoice expired prior to send");
860 } else { panic!("Expected Invoice Error"); }
863 // Expiration is checked only in an std environment
864 #[cfg(feature = "std")]
866 fn fails_retrying_invoice_after_expiration() {
867 let event_handled = core::cell::RefCell::new(false);
868 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
870 let payment_preimage = PaymentPreimage([1; 32]);
871 let invoice = invoice(payment_preimage);
872 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
874 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
875 let router = TestRouter {};
876 let scorer = RefCell::new(TestScorer::new());
877 let logger = TestLogger::new();
879 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
881 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
882 assert_eq!(*payer.attempts.borrow(), 1);
884 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
885 retry_data.payment_params.expiry_time = Some(SystemTime::now()
886 .checked_sub(Duration::from_secs(2)).unwrap()
887 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
888 let event = Event::PaymentPathFailed {
890 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
891 network_update: None,
892 rejected_by_dest: false,
893 all_paths_failed: false,
895 short_channel_id: None,
896 retry: Some(retry_data),
898 invoice_payer.handle_event(&event);
899 assert_eq!(*event_handled.borrow(), true);
900 assert_eq!(*payer.attempts.borrow(), 1);
904 fn fails_paying_invoice_after_retry_error() {
905 let event_handled = core::cell::RefCell::new(false);
906 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
908 let payment_preimage = PaymentPreimage([1; 32]);
909 let invoice = invoice(payment_preimage);
910 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
912 let payer = TestPayer::new()
914 .expect_send(Amount::ForInvoice(final_value_msat))
915 .expect_send(Amount::OnRetry(final_value_msat / 2));
916 let router = TestRouter {};
917 let scorer = RefCell::new(TestScorer::new());
918 let logger = TestLogger::new();
920 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
922 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
923 assert_eq!(*payer.attempts.borrow(), 1);
925 let event = Event::PaymentPathFailed {
927 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
928 network_update: None,
929 rejected_by_dest: false,
930 all_paths_failed: false,
931 path: TestRouter::path_for_value(final_value_msat / 2),
932 short_channel_id: None,
933 retry: Some(TestRouter::retry_for_invoice(&invoice)),
935 invoice_payer.handle_event(&event);
936 assert_eq!(*event_handled.borrow(), true);
937 assert_eq!(*payer.attempts.borrow(), 2);
941 fn fails_paying_invoice_after_rejected_by_payee() {
942 let event_handled = core::cell::RefCell::new(false);
943 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
945 let payment_preimage = PaymentPreimage([1; 32]);
946 let invoice = invoice(payment_preimage);
947 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
949 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
950 let router = TestRouter {};
951 let scorer = RefCell::new(TestScorer::new());
952 let logger = TestLogger::new();
954 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
956 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
957 assert_eq!(*payer.attempts.borrow(), 1);
959 let event = Event::PaymentPathFailed {
961 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
962 network_update: None,
963 rejected_by_dest: true,
964 all_paths_failed: false,
966 short_channel_id: None,
967 retry: Some(TestRouter::retry_for_invoice(&invoice)),
969 invoice_payer.handle_event(&event);
970 assert_eq!(*event_handled.borrow(), true);
971 assert_eq!(*payer.attempts.borrow(), 1);
975 fn fails_repaying_invoice_with_pending_payment() {
976 let event_handled = core::cell::RefCell::new(false);
977 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
979 let payment_preimage = PaymentPreimage([1; 32]);
980 let invoice = invoice(payment_preimage);
981 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
983 let payer = TestPayer::new()
984 .expect_send(Amount::ForInvoice(final_value_msat))
985 .expect_send(Amount::ForInvoice(final_value_msat));
986 let router = TestRouter {};
987 let scorer = RefCell::new(TestScorer::new());
988 let logger = TestLogger::new();
990 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
992 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
994 // Cannot repay an invoice pending payment.
995 match invoice_payer.pay_invoice(&invoice) {
996 Err(PaymentError::Invoice("payment pending")) => {},
997 Err(_) => panic!("unexpected error"),
998 Ok(_) => panic!("expected invoice error"),
1001 // Can repay an invoice once cleared from cache.
1002 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1003 invoice_payer.remove_cached_payment(&payment_hash);
1004 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1006 // Cannot retry paying an invoice if cleared from cache.
1007 invoice_payer.remove_cached_payment(&payment_hash);
1008 let event = Event::PaymentPathFailed {
1011 network_update: None,
1012 rejected_by_dest: false,
1013 all_paths_failed: false,
1015 short_channel_id: None,
1016 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1018 invoice_payer.handle_event(&event);
1019 assert_eq!(*event_handled.borrow(), true);
1023 fn fails_paying_invoice_with_routing_errors() {
1024 let payer = TestPayer::new();
1025 let router = FailingRouter {};
1026 let scorer = RefCell::new(TestScorer::new());
1027 let logger = TestLogger::new();
1029 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1031 let payment_preimage = PaymentPreimage([1; 32]);
1032 let invoice = invoice(payment_preimage);
1033 match invoice_payer.pay_invoice(&invoice) {
1034 Err(PaymentError::Routing(_)) => {},
1035 Err(_) => panic!("unexpected error"),
1036 Ok(_) => panic!("expected routing error"),
1041 fn fails_paying_invoice_with_sending_errors() {
1042 let payment_preimage = PaymentPreimage([1; 32]);
1043 let invoice = invoice(payment_preimage);
1044 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1046 let payer = TestPayer::new()
1047 .fails_on_attempt(1)
1048 .expect_send(Amount::ForInvoice(final_value_msat));
1049 let router = TestRouter {};
1050 let scorer = RefCell::new(TestScorer::new());
1051 let logger = TestLogger::new();
1053 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
1055 match invoice_payer.pay_invoice(&invoice) {
1056 Err(PaymentError::Sending(_)) => {},
1057 Err(_) => panic!("unexpected error"),
1058 Ok(_) => panic!("expected sending error"),
1063 fn pays_zero_value_invoice_using_amount() {
1064 let event_handled = core::cell::RefCell::new(false);
1065 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1067 let payment_preimage = PaymentPreimage([1; 32]);
1068 let invoice = zero_value_invoice(payment_preimage);
1069 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1070 let final_value_msat = 100;
1072 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1073 let router = TestRouter {};
1074 let scorer = RefCell::new(TestScorer::new());
1075 let logger = TestLogger::new();
1077 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1080 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1081 assert_eq!(*payer.attempts.borrow(), 1);
1083 invoice_payer.handle_event(&Event::PaymentSent {
1084 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1086 assert_eq!(*event_handled.borrow(), true);
1087 assert_eq!(*payer.attempts.borrow(), 1);
1091 fn fails_paying_zero_value_invoice_with_amount() {
1092 let event_handled = core::cell::RefCell::new(false);
1093 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1095 let payer = TestPayer::new();
1096 let router = TestRouter {};
1097 let scorer = RefCell::new(TestScorer::new());
1098 let logger = TestLogger::new();
1100 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
1102 let payment_preimage = PaymentPreimage([1; 32]);
1103 let invoice = invoice(payment_preimage);
1105 // Cannot repay an invoice pending payment.
1106 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1107 Err(PaymentError::Invoice("amount unexpected")) => {},
1108 Err(_) => panic!("unexpected error"),
1109 Ok(_) => panic!("expected invoice error"),
1114 fn pays_pubkey_with_amount() {
1115 let event_handled = core::cell::RefCell::new(false);
1116 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1118 let pubkey = pubkey();
1119 let payment_preimage = PaymentPreimage([1; 32]);
1120 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1121 let final_value_msat = 100;
1122 let final_cltv_expiry_delta = 42;
1124 let payer = TestPayer::new()
1125 .expect_send(Amount::Spontaneous(final_value_msat))
1126 .expect_send(Amount::OnRetry(final_value_msat));
1127 let router = TestRouter {};
1128 let scorer = RefCell::new(TestScorer::new());
1129 let logger = TestLogger::new();
1131 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1133 let payment_id = Some(invoice_payer.pay_pubkey(
1134 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1136 assert_eq!(*payer.attempts.borrow(), 1);
1138 let retry = RouteParameters {
1139 payment_params: PaymentParameters::for_keysend(pubkey),
1141 final_cltv_expiry_delta,
1143 let event = Event::PaymentPathFailed {
1146 network_update: None,
1147 rejected_by_dest: false,
1148 all_paths_failed: false,
1150 short_channel_id: None,
1153 invoice_payer.handle_event(&event);
1154 assert_eq!(*event_handled.borrow(), false);
1155 assert_eq!(*payer.attempts.borrow(), 2);
1157 invoice_payer.handle_event(&Event::PaymentSent {
1158 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1160 assert_eq!(*event_handled.borrow(), true);
1161 assert_eq!(*payer.attempts.borrow(), 2);
1165 fn scores_failed_channel() {
1166 let event_handled = core::cell::RefCell::new(false);
1167 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1169 let payment_preimage = PaymentPreimage([1; 32]);
1170 let invoice = invoice(payment_preimage);
1171 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1172 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1173 let path = TestRouter::path_for_value(final_value_msat);
1174 let short_channel_id = Some(path[0].short_channel_id);
1176 // Expect that scorer is given short_channel_id upon handling the event.
1177 let payer = TestPayer::new()
1178 .expect_send(Amount::ForInvoice(final_value_msat))
1179 .expect_send(Amount::OnRetry(final_value_msat / 2));
1180 let router = TestRouter {};
1181 let scorer = RefCell::new(TestScorer::new().expect(PaymentPath::Failure {
1182 path: path.clone(), short_channel_id: path[0].short_channel_id,
1184 let logger = TestLogger::new();
1186 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1188 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1189 let event = Event::PaymentPathFailed {
1192 network_update: None,
1193 rejected_by_dest: false,
1194 all_paths_failed: false,
1197 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1199 invoice_payer.handle_event(&event);
1203 fn scores_successful_channels() {
1204 let event_handled = core::cell::RefCell::new(false);
1205 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1207 let payment_preimage = PaymentPreimage([1; 32]);
1208 let invoice = invoice(payment_preimage);
1209 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1210 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1211 let route = TestRouter::route_for_value(final_value_msat);
1213 // Expect that scorer is given short_channel_id upon handling the event.
1214 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1215 let router = TestRouter {};
1216 let scorer = RefCell::new(TestScorer::new()
1217 .expect(PaymentPath::Success { path: route.paths[0].clone() })
1218 .expect(PaymentPath::Success { path: route.paths[1].clone() })
1220 let logger = TestLogger::new();
1222 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
1224 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1225 let event = Event::PaymentPathSuccessful {
1226 payment_id, payment_hash, path: route.paths[0].clone()
1228 invoice_payer.handle_event(&event);
1229 let event = Event::PaymentPathSuccessful {
1230 payment_id, payment_hash, path: route.paths[1].clone()
1232 invoice_payer.handle_event(&event);
1238 fn route_for_value(final_value_msat: u64) -> Route {
1242 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1243 channel_features: ChannelFeatures::empty(),
1244 node_features: NodeFeatures::empty(),
1245 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1248 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1249 channel_features: ChannelFeatures::empty(),
1250 node_features: NodeFeatures::empty(),
1251 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1254 payment_params: None,
1258 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1259 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1262 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1263 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1264 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1265 .with_route_hints(invoice.route_hints());
1266 if let Some(features) = invoice.features() {
1267 payment_params = payment_params.with_features(features.clone());
1269 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1273 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1278 impl<S: Score> Router<S> for TestRouter {
1280 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1281 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1282 ) -> Result<Route, LightningError> {
1284 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1289 struct FailingRouter;
1291 impl<S: Score> Router<S> for FailingRouter {
1293 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1294 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1295 ) -> Result<Route, LightningError> {
1296 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1301 expectations: Option<VecDeque<PaymentPath>>,
1306 Failure { path: Vec<RouteHop>, short_channel_id: u64 },
1307 Success { path: Vec<RouteHop> },
1317 fn expect(mut self, expectation: PaymentPath) -> Self {
1318 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1324 impl lightning::util::ser::Writeable for TestScorer {
1325 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1328 impl Score for TestScorer {
1329 fn channel_penalty_msat(
1330 &self, _short_channel_id: u64, _send_amt: u64, _chan_amt: u64, _source: &NodeId, _target: &NodeId
1333 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1334 if let Some(expectations) = &mut self.expectations {
1335 match expectations.pop_front() {
1336 Some(PaymentPath::Failure { path, short_channel_id }) => {
1337 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1338 assert_eq!(actual_short_channel_id, short_channel_id);
1340 Some(PaymentPath::Success { path }) => {
1341 panic!("Unexpected successful payment path: {:?}", path)
1343 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1348 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1349 if let Some(expectations) = &mut self.expectations {
1350 match expectations.pop_front() {
1351 Some(PaymentPath::Failure { path, .. }) => {
1352 panic!("Unexpected payment path failure: {:?}", path)
1354 Some(PaymentPath::Success { path }) => {
1355 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1357 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1363 impl Drop for TestScorer {
1364 fn drop(&mut self) {
1365 if std::thread::panicking() {
1369 if let Some(expectations) = &self.expectations {
1370 if !expectations.is_empty() {
1371 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1378 expectations: core::cell::RefCell<VecDeque<Amount>>,
1379 attempts: core::cell::RefCell<usize>,
1380 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1383 #[derive(Clone, Debug, PartialEq, Eq)]
1390 struct OnAttempt(usize);
1395 expectations: core::cell::RefCell::new(VecDeque::new()),
1396 attempts: core::cell::RefCell::new(0),
1397 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1401 fn expect_send(self, value_msat: Amount) -> Self {
1402 self.expectations.borrow_mut().push_back(value_msat);
1406 fn fails_on_attempt(self, attempt: usize) -> Self {
1407 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1408 self.fails_with(failure, OnAttempt(attempt))
1411 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1412 self.fails_with(PaymentSendFailure::PartialFailure {
1414 failed_paths_retry: Some(retry),
1415 payment_id: PaymentId([1; 32]),
1419 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1420 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1424 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1425 let mut attempts = self.attempts.borrow_mut();
1428 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1429 Some(failure) => Err(failure),
1430 None => Ok(PaymentId([1; 32])),
1434 fn check_value_msats(&self, actual_value_msats: Amount) {
1435 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1436 if let Some(expected_value_msats) = expected_value_msats {
1437 assert_eq!(actual_value_msats, expected_value_msats);
1439 panic!("Unexpected amount: {:?}", actual_value_msats);
1444 impl Drop for TestPayer {
1445 fn drop(&mut self) {
1446 if std::thread::panicking() {
1450 if !self.expectations.borrow().is_empty() {
1451 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1456 impl Payer for TestPayer {
1457 fn node_id(&self) -> PublicKey {
1458 let secp_ctx = Secp256k1::new();
1459 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1462 fn first_hops(&self) -> Vec<ChannelDetails> {
1467 &self, route: &Route, _payment_hash: PaymentHash,
1468 _payment_secret: &Option<PaymentSecret>
1469 ) -> Result<PaymentId, PaymentSendFailure> {
1470 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1471 self.check_attempts()
1474 fn send_spontaneous_payment(
1475 &self, route: &Route, _payment_preimage: PaymentPreimage,
1476 ) -> Result<PaymentId, PaymentSendFailure> {
1477 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1478 self.check_attempts()
1482 &self, route: &Route, _payment_id: PaymentId
1483 ) -> Result<(), PaymentSendFailure> {
1484 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1485 self.check_attempts().map(|_| ())
1488 fn abandon_payment(&self, _payment_id: PaymentId) { }
1491 // *** Full Featured Functional Tests with a Real ChannelManager ***
1492 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1494 impl<S: Score> Router<S> for ManualRouter {
1496 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1497 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1498 ) -> Result<Route, LightningError> {
1499 self.0.borrow_mut().pop_front().unwrap()
1503 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1504 self.0.borrow_mut().push_back(result);
1507 impl Drop for ManualRouter {
1508 fn drop(&mut self) {
1509 if std::thread::panicking() {
1512 assert!(self.0.borrow_mut().is_empty());
1517 fn retry_multi_path_single_failed_payment() {
1518 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1519 let chanmon_cfgs = create_chanmon_cfgs(2);
1520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1524 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1525 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1526 let chans = nodes[0].node.list_usable_channels();
1527 let mut route = Route {
1530 pubkey: nodes[1].node.get_our_node_id(),
1531 node_features: NodeFeatures::known(),
1532 short_channel_id: chans[0].short_channel_id.unwrap(),
1533 channel_features: ChannelFeatures::known(),
1535 cltv_expiry_delta: 100,
1538 pubkey: nodes[1].node.get_our_node_id(),
1539 node_features: NodeFeatures::known(),
1540 short_channel_id: chans[1].short_channel_id.unwrap(),
1541 channel_features: ChannelFeatures::known(),
1542 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1543 cltv_expiry_delta: 100,
1546 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1548 let router = ManualRouter(RefCell::new(VecDeque::new()));
1549 router.expect_find_route(Ok(route.clone()));
1550 // On retry, split the payment across both channels.
1551 route.paths[0][0].fee_msat = 50_000_001;
1552 route.paths[1][0].fee_msat = 50_000_000;
1553 router.expect_find_route(Ok(route.clone()));
1555 let event_handler = |_: &_| { panic!(); };
1556 let scorer = RefCell::new(TestScorer::new());
1557 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1559 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1560 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1561 duration_since_epoch()).unwrap())
1563 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1564 assert_eq!(htlc_msgs.len(), 2);
1565 check_added_monitors!(nodes[0], 2);
1569 fn immediate_retry_on_failure() {
1570 // Tests that we can/will retry immediately after a failure
1571 let chanmon_cfgs = create_chanmon_cfgs(2);
1572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1577 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1578 let chans = nodes[0].node.list_usable_channels();
1579 let mut route = Route {
1582 pubkey: nodes[1].node.get_our_node_id(),
1583 node_features: NodeFeatures::known(),
1584 short_channel_id: chans[0].short_channel_id.unwrap(),
1585 channel_features: ChannelFeatures::known(),
1586 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1587 cltv_expiry_delta: 100,
1590 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1592 let router = ManualRouter(RefCell::new(VecDeque::new()));
1593 router.expect_find_route(Ok(route.clone()));
1594 // On retry, split the payment across both channels.
1595 route.paths.push(route.paths[0].clone());
1596 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1597 route.paths[0][0].fee_msat = 50_000_000;
1598 route.paths[1][0].fee_msat = 50_000_001;
1599 router.expect_find_route(Ok(route.clone()));
1601 let event_handler = |_: &_| { panic!(); };
1602 let scorer = RefCell::new(TestScorer::new());
1603 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1605 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1606 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1607 duration_since_epoch()).unwrap())
1609 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1610 assert_eq!(htlc_msgs.len(), 2);
1611 check_added_monitors!(nodes[0], 2);
1615 fn no_extra_retries_on_back_to_back_fail() {
1616 // In a previous release, we had a race where we may exceed the payment retry count if we
1617 // get two failures in a row with the second having `all_paths_failed` set.
1618 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1619 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1620 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1621 // pending which we will see later. Thus, when we previously removed the retry tracking map
1622 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1623 // retry entry even though more events for the same payment were still pending. This led to
1624 // us retrying a payment again even though we'd already given up on it.
1626 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1627 // is used to remove the payment retry counter entries instead. This tests for the specific
1628 // excess-retry case while also testing `PaymentFailed` generation.
1630 let chanmon_cfgs = create_chanmon_cfgs(3);
1631 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1632 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1633 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1635 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;
1636 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;
1638 let mut route = Route {
1641 pubkey: nodes[1].node.get_our_node_id(),
1642 node_features: NodeFeatures::known(),
1643 short_channel_id: chan_1_scid,
1644 channel_features: ChannelFeatures::known(),
1646 cltv_expiry_delta: 100,
1648 pubkey: nodes[2].node.get_our_node_id(),
1649 node_features: NodeFeatures::known(),
1650 short_channel_id: chan_2_scid,
1651 channel_features: ChannelFeatures::known(),
1652 fee_msat: 100_000_000,
1653 cltv_expiry_delta: 100,
1656 pubkey: nodes[1].node.get_our_node_id(),
1657 node_features: NodeFeatures::known(),
1658 short_channel_id: chan_1_scid,
1659 channel_features: ChannelFeatures::known(),
1661 cltv_expiry_delta: 100,
1663 pubkey: nodes[2].node.get_our_node_id(),
1664 node_features: NodeFeatures::known(),
1665 short_channel_id: chan_2_scid,
1666 channel_features: ChannelFeatures::known(),
1667 fee_msat: 100_000_000,
1668 cltv_expiry_delta: 100,
1671 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1673 let router = ManualRouter(RefCell::new(VecDeque::new()));
1674 router.expect_find_route(Ok(route.clone()));
1675 // On retry, we'll only be asked for one path
1676 route.paths.remove(1);
1677 router.expect_find_route(Ok(route.clone()));
1679 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1680 let event_handler = |event: &Event| {
1681 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1682 event_checker(event);
1684 let scorer = RefCell::new(TestScorer::new());
1685 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1687 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1688 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1689 duration_since_epoch()).unwrap())
1691 let htlc_updates = SendEvent::from_node(&nodes[0]);
1692 check_added_monitors!(nodes[0], 1);
1693 assert_eq!(htlc_updates.msgs.len(), 1);
1695 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1696 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1697 check_added_monitors!(nodes[1], 1);
1698 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1700 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1701 check_added_monitors!(nodes[0], 1);
1702 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1704 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1705 check_added_monitors!(nodes[0], 1);
1706 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1708 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1709 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1710 check_added_monitors!(nodes[1], 1);
1711 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1713 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1714 check_added_monitors!(nodes[1], 1);
1715 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1717 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1718 check_added_monitors!(nodes[0], 1);
1720 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1721 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1722 check_added_monitors!(nodes[0], 1);
1723 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1725 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1726 check_added_monitors!(nodes[1], 1);
1727 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1729 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1730 check_added_monitors!(nodes[1], 1);
1731 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1733 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1734 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1735 check_added_monitors!(nodes[0], 1);
1737 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1738 check_added_monitors!(nodes[0], 1);
1739 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1741 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1742 check_added_monitors!(nodes[1], 1);
1743 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1744 check_added_monitors!(nodes[1], 1);
1745 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1747 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1748 check_added_monitors!(nodes[0], 1);
1750 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1751 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1752 // with it set. The first event will use up the only retry we are allowed, with the second
1753 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1754 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1755 // if the final HTLC failed.
1756 expected_events.borrow_mut().push_back(&|ev: &Event| {
1757 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1758 assert!(!rejected_by_dest);
1759 assert!(all_paths_failed);
1760 } else { panic!("Unexpected event"); }
1762 nodes[0].node.process_pending_events(&invoice_payer);
1763 assert!(expected_events.borrow().is_empty());
1765 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1766 check_added_monitors!(nodes[0], 1);
1768 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1769 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1770 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1771 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1772 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1774 expected_events.borrow_mut().push_back(&|ev: &Event| {
1775 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1776 assert!(!rejected_by_dest);
1777 assert!(all_paths_failed);
1778 } else { panic!("Unexpected event"); }
1780 expected_events.borrow_mut().push_back(&|ev: &Event| {
1781 if let Event::PaymentFailed { .. } = ev {
1782 } else { panic!("Unexpected event"); }
1784 nodes[0].node.process_pending_events(&invoice_payer);
1785 assert!(expected_events.borrow().is_empty());