1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! A module for paying Lightning invoices and sending spontaneous payments.
12 //! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and
13 //! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means
14 //! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer
15 //! and payee using information provided by the payer and from the payee's [`Invoice`], when
18 //! [`InvoicePayer`] is parameterized by a [`LockableScore`], which it uses for scoring failed and
19 //! successful payment paths upon receiving [`Event::PaymentPathFailed`] and
20 //! [`Event::PaymentPathSuccessful`] events, respectively.
22 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
23 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
24 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
25 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
26 //! along the events to the user-provided handler.
31 //! # extern crate lightning;
32 //! # extern crate lightning_invoice;
33 //! # extern crate secp256k1;
35 //! # #[cfg(feature = "no-std")]
36 //! # extern crate core2;
38 //! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
39 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
40 //! # use lightning::ln::msgs::LightningError;
41 //! # use lightning::routing::gossip::NodeId;
42 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
43 //! # use lightning::routing::scoring::{ChannelUsage, Score};
44 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
45 //! # use lightning::util::logger::{Logger, Record};
46 //! # use lightning::util::ser::{Writeable, Writer};
47 //! # use lightning_invoice::Invoice;
48 //! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, Router};
49 //! # use secp256k1::PublicKey;
50 //! # use std::cell::RefCell;
51 //! # use std::ops::Deref;
53 //! # #[cfg(not(feature = "std"))]
55 //! # #[cfg(feature = "std")]
58 //! # struct FakeEventProvider {}
59 //! # impl EventsProvider for FakeEventProvider {
60 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
63 //! # struct FakePayer {}
64 //! # impl Payer for FakePayer {
65 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
66 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
67 //! # fn send_payment(
68 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
69 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
70 //! # fn send_spontaneous_payment(
71 //! # &self, route: &Route, payment_preimage: PaymentPreimage
72 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
73 //! # fn retry_payment(
74 //! # &self, route: &Route, payment_id: PaymentId
75 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
76 //! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
79 //! # struct FakeRouter {}
80 //! # impl<S: Score> Router<S> for FakeRouter {
82 //! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash,
83 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
84 //! # ) -> Result<Route, LightningError> { unimplemented!() }
87 //! # struct FakeScorer {}
88 //! # impl Writeable for FakeScorer {
89 //! # fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); }
91 //! # impl Score for FakeScorer {
92 //! # fn channel_penalty_msat(
93 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
95 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
96 //! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {}
97 //! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
98 //! # fn probe_successful(&mut self, _path: &[&RouteHop]) {}
101 //! # struct FakeLogger {}
102 //! # impl Logger for FakeLogger {
103 //! # fn log(&self, record: &Record) { unimplemented!() }
107 //! let event_handler = |event: &Event| {
109 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
110 //! Event::PaymentSent { .. } => println!("payment successful"),
114 //! # let payer = FakePayer {};
115 //! # let router = FakeRouter {};
116 //! # let scorer = RefCell::new(FakeScorer {});
117 //! # let logger = FakeLogger {};
118 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
120 //! let invoice = "...";
121 //! if let Ok(invoice) = invoice.parse::<Invoice>() {
122 //! invoice_payer.pay_invoice(&invoice).unwrap();
124 //! # let event_provider = FakeEventProvider {};
126 //! event_provider.process_pending_events(&invoice_payer);
134 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
135 //! as updates to the network graph or changes to channel scores should be applied prior to
136 //! retries, typically by way of composing [`EventHandler`]s accordingly.
140 use bitcoin_hashes::Hash;
141 use bitcoin_hashes::sha256::Hash as Sha256;
143 use crate::prelude::*;
144 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
145 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
146 use lightning::ln::msgs::LightningError;
147 use lightning::routing::scoring::{LockableScore, Score};
148 use lightning::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters};
149 use lightning::util::events::{Event, EventHandler};
150 use lightning::util::logger::Logger;
151 use time_utils::Time;
152 use crate::sync::Mutex;
154 use secp256k1::PublicKey;
157 use core::fmt::{Debug, Display, Formatter};
158 use core::ops::Deref;
159 use core::time::Duration;
160 #[cfg(feature = "std")]
161 use std::time::SystemTime;
163 /// A utility for paying [`Invoice`]s and sending spontaneous payments.
165 /// See [module-level documentation] for details.
167 /// [module-level documentation]: crate::payment
168 pub type InvoicePayer<P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, ConfiguredTime>;
170 #[cfg(not(feature = "no-std"))]
171 type ConfiguredTime = std::time::Instant;
172 #[cfg(feature = "no-std")]
174 #[cfg(feature = "no-std")]
175 type ConfiguredTime = time_utils::Eternity;
177 /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias.
178 pub struct InvoicePayerUsingTime<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time>
181 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
182 S::Target: for <'a> LockableScore<'a>,
190 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
191 payment_cache: Mutex<HashMap<PaymentHash, PaymentInfo<T>>>,
195 /// Used by [`InvoicePayerUsingTime::payment_cache`] to track the payments that are either
196 /// currently being made, or have outstanding paths that need retrying.
197 struct PaymentInfo<T: Time> {
198 attempts: PaymentAttempts<T>,
199 paths: Vec<Vec<RouteHop>>,
202 impl<T: Time> PaymentInfo<T> {
205 attempts: PaymentAttempts::new(),
210 /// Storing minimal payment attempts information required for determining if a outbound payment can
212 #[derive(Clone, Copy)]
213 struct PaymentAttempts<T: Time> {
214 /// This count will be incremented only after the result of the attempt is known. When it's 0,
215 /// it means the result of the first attempt is now known yet.
217 /// This field is only used when retry is [`Retry::Timeout`] which is only build with feature std
218 first_attempted_at: T
221 impl<T: Time> PaymentAttempts<T> {
225 first_attempted_at: T::now()
230 impl<T: Time> Display for PaymentAttempts<T> {
231 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
232 #[cfg(feature = "no-std")]
233 return write!( f, "attempts: {}", self.count);
234 #[cfg(not(feature = "no-std"))]
237 "attempts: {}, duration: {}s",
239 T::now().duration_since(self.first_attempted_at).as_secs()
244 /// A trait defining behavior of an [`Invoice`] payer.
246 /// Returns the payer's node id.
247 fn node_id(&self) -> PublicKey;
249 /// Returns the payer's channels.
250 fn first_hops(&self) -> Vec<ChannelDetails>;
252 /// Sends a payment over the Lightning Network using the given [`Route`].
254 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
255 ) -> Result<PaymentId, PaymentSendFailure>;
257 /// Sends a spontaneous payment over the Lightning Network using the given [`Route`].
258 fn send_spontaneous_payment(
259 &self, route: &Route, payment_preimage: PaymentPreimage
260 ) -> Result<PaymentId, PaymentSendFailure>;
262 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
263 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
265 /// Signals that no further retries for the given payment will occur.
266 fn abandon_payment(&self, payment_id: PaymentId);
269 /// A trait defining behavior for routing an [`Invoice`] payment.
270 pub trait Router<S: Score> {
271 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
273 &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash,
274 first_hops: Option<&[&ChannelDetails]>, scorer: &S
275 ) -> Result<Route, LightningError>;
278 /// Strategies available to retry payment path failures for an [`Invoice`].
280 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
282 /// Max number of attempts to retry payment.
284 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
285 /// payments, if this is less than the total number of paths, we will never even retry all of the
288 #[cfg(feature = "std")]
289 /// Time elapsed before abandoning retries for a payment.
294 fn is_retryable_now<T: Time>(&self, attempts: &PaymentAttempts<T>) -> bool {
295 match (self, attempts) {
296 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
297 max_retry_count >= &count
299 #[cfg(feature = "std")]
300 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. } ) =>
301 *max_duration >= T::now().duration_since(*first_attempted_at),
306 /// An error that may occur when making a payment.
307 #[derive(Clone, Debug)]
308 pub enum PaymentError {
309 /// An error resulting from the provided [`Invoice`] or payment hash.
310 Invoice(&'static str),
311 /// An error occurring when finding a route.
312 Routing(LightningError),
313 /// An error occurring when sending a payment.
314 Sending(PaymentSendFailure),
317 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> InvoicePayerUsingTime<P, R, S, L, E, T>
320 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
321 S::Target: for <'a> LockableScore<'a>,
324 /// Creates an invoice payer that retries failed payment paths.
326 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
327 /// `retry` has been exceeded for a given [`Invoice`].
329 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry: Retry
337 payment_cache: Mutex::new(HashMap::new()),
342 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
344 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
345 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
347 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
348 if invoice.amount_milli_satoshis().is_none() {
349 Err(PaymentError::Invoice("amount missing"))
351 self.pay_invoice_using_amount(invoice, None)
355 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
356 /// case a retry is needed.
358 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
359 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
361 pub fn pay_zero_value_invoice(
362 &self, invoice: &Invoice, amount_msats: u64
363 ) -> Result<PaymentId, PaymentError> {
364 if invoice.amount_milli_satoshis().is_some() {
365 Err(PaymentError::Invoice("amount unexpected"))
367 self.pay_invoice_using_amount(invoice, Some(amount_msats))
371 fn pay_invoice_using_amount(
372 &self, invoice: &Invoice, amount_msats: Option<u64>
373 ) -> Result<PaymentId, PaymentError> {
374 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
376 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
377 match self.payment_cache.lock().unwrap().entry(payment_hash) {
378 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
379 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
382 let payment_secret = Some(invoice.payment_secret().clone());
383 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
384 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
385 .with_route_hints(invoice.route_hints());
386 if let Some(features) = invoice.features() {
387 payment_params = payment_params.with_features(features.clone());
389 let route_params = RouteParameters {
391 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
392 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
395 let send_payment = |route: &Route| {
396 self.payer.send_payment(route, payment_hash, &payment_secret)
399 self.pay_internal(&route_params, payment_hash, send_payment)
400 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
403 /// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in
404 /// case a retry is needed.
406 /// You should ensure that `payment_preimage` is unique and that its `payment_hash` has never
407 /// been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so for you.
409 &self, pubkey: PublicKey, payment_preimage: PaymentPreimage, amount_msats: u64,
410 final_cltv_expiry_delta: u32
411 ) -> Result<PaymentId, PaymentError> {
412 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
413 match self.payment_cache.lock().unwrap().entry(payment_hash) {
414 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
415 hash_map::Entry::Vacant(entry) => entry.insert(PaymentInfo::new()),
418 let route_params = RouteParameters {
419 payment_params: PaymentParameters::for_keysend(pubkey),
420 final_value_msat: amount_msats,
421 final_cltv_expiry_delta,
424 let send_payment = |route: &Route| {
425 self.payer.send_spontaneous_payment(route, payment_preimage)
427 self.pay_internal(&route_params, payment_hash, send_payment)
428 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
431 fn pay_internal<F: FnOnce(&Route) -> Result<PaymentId, PaymentSendFailure> + Copy>(
432 &self, params: &RouteParameters, payment_hash: PaymentHash, send_payment: F,
433 ) -> Result<PaymentId, PaymentError> {
434 #[cfg(feature = "std")] {
435 if has_expired(params) {
436 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
437 return Err(PaymentError::Invoice("Invoice expired prior to send"));
441 let payer = self.payer.node_id();
442 let first_hops = self.payer.first_hops();
443 let route = self.router.find_route(
444 &payer, params, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
446 ).map_err(|e| PaymentError::Routing(e))?;
448 match send_payment(&route) {
449 Ok(payment_id) => Ok(payment_id),
451 PaymentSendFailure::ParameterError(_) => Err(e),
452 PaymentSendFailure::PathParameterError(_) => Err(e),
453 PaymentSendFailure::AllFailedRetrySafe(_) => {
454 let mut payment_cache = self.payment_cache.lock().unwrap();
455 let payment_info = payment_cache.get_mut(&payment_hash).unwrap();
456 payment_info.attempts.count += 1;
457 if self.retry.is_retryable_now(&payment_info.attempts) {
458 core::mem::drop(payment_cache);
459 Ok(self.pay_internal(params, payment_hash, send_payment)?)
464 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
465 if let Some(retry_data) = failed_paths_retry {
466 // Some paths were sent, even if we failed to send the full MPP value our
467 // recipient may misbehave and claim the funds, at which point we have to
468 // consider the payment sent, so return `Ok()` here, ignoring any retry
470 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
473 // This may happen if we send a payment and some paths fail, but
474 // only due to a temporary monitor failure or the like, implying
475 // they're really in-flight, but we haven't sent the initial
476 // HTLC-Add messages yet.
481 }.map_err(|e| PaymentError::Sending(e))
485 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
486 ) -> Result<(), ()> {
487 let attempts = self.payment_cache.lock().unwrap().entry(payment_hash)
488 .and_modify(|info| info.attempts.count += 1 )
489 .or_insert_with(|| PaymentInfo {
490 attempts: PaymentAttempts {
492 first_attempted_at: T::now(),
497 if !self.retry.is_retryable_now(&attempts) {
498 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying ({})", log_bytes!(payment_hash.0), attempts);
502 #[cfg(feature = "std")] {
503 if has_expired(params) {
504 log_trace!(self.logger, "Invoice expired for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
509 let payer = self.payer.node_id();
510 let first_hops = self.payer.first_hops();
511 let route = self.router.find_route(
512 &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::<Vec<_>>()),
516 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying ({:})", log_bytes!(payment_hash.0), attempts);
520 match self.payer.retry_payment(&route.unwrap(), payment_id) {
522 Err(PaymentSendFailure::ParameterError(_)) |
523 Err(PaymentSendFailure::PathParameterError(_)) => {
524 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
527 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
528 self.retry_payment(payment_id, payment_hash, params)
530 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
531 if let Some(retry) = failed_paths_retry {
532 // Always return Ok for the same reason as noted in pay_internal.
533 let _ = self.retry_payment(payment_id, payment_hash, &retry);
540 /// Removes the payment cached by the given payment hash.
542 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
543 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
544 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
545 self.payment_cache.lock().unwrap().remove(payment_hash);
549 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
550 invoice.signed_invoice.raw_invoice.data.timestamp.0 + invoice.expiry_time()
553 #[cfg(feature = "std")]
554 fn has_expired(route_params: &RouteParameters) -> bool {
555 if let Some(expiry_time) = route_params.payment_params.expiry_time {
556 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
560 impl<P: Deref, R, S: Deref, L: Deref, E: EventHandler, T: Time> EventHandler for InvoicePayerUsingTime<P, R, S, L, E, T>
563 R: for <'a> Router<<<S as Deref>::Target as LockableScore<'a>>::Locked>,
564 S::Target: for <'a> LockableScore<'a>,
567 fn handle_event(&self, event: &Event) {
569 Event::PaymentPathFailed {
570 payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, ..
572 if let Some(short_channel_id) = short_channel_id {
573 let path = path.iter().collect::<Vec<_>>();
574 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
577 if payment_id.is_none() {
578 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
579 } else if *rejected_by_dest {
580 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
581 self.payer.abandon_payment(payment_id.unwrap());
582 } else if retry.is_none() {
583 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
584 self.payer.abandon_payment(payment_id.unwrap());
585 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
586 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
589 self.payer.abandon_payment(payment_id.unwrap());
592 Event::PaymentFailed { payment_hash, .. } => {
593 self.remove_cached_payment(&payment_hash);
595 Event::PaymentPathSuccessful { path, .. } => {
596 let path = path.iter().collect::<Vec<_>>();
597 self.scorer.lock().payment_path_successful(&path);
599 Event::PaymentSent { payment_hash, .. } => {
600 let mut payment_cache = self.payment_cache.lock().unwrap();
601 let attempts = payment_cache
602 .remove(payment_hash)
603 .map_or(1, |payment_info| payment_info.attempts.count + 1);
604 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
606 Event::ProbeSuccessful { payment_hash, path, .. } => {
607 log_trace!(self.logger, "Probe payment {} of {}msat was successful", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat);
608 let path = path.iter().collect::<Vec<_>>();
609 self.scorer.lock().probe_successful(&path);
611 Event::ProbeFailed { payment_hash, path, short_channel_id, .. } => {
612 if let Some(short_channel_id) = short_channel_id {
613 log_trace!(self.logger, "Probe payment {} of {}msat failed at channel {}", log_bytes!(payment_hash.0), path.last().unwrap().fee_msat, *short_channel_id);
614 let path = path.iter().collect::<Vec<_>>();
615 self.scorer.lock().probe_failed(&path, *short_channel_id);
621 // Delegate to the decorated event handler unless the payment is retried.
622 self.event_handler.handle_event(event)
629 use crate::{InvoiceBuilder, Currency};
630 use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
631 use bitcoin_hashes::sha256::Hash as Sha256;
632 use lightning::ln::PaymentPreimage;
633 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
634 use lightning::ln::functional_test_utils::*;
635 use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError};
636 use lightning::routing::gossip::NodeId;
637 use lightning::routing::router::{PaymentParameters, Route, RouteHop};
638 use lightning::routing::scoring::ChannelUsage;
639 use lightning::util::test_utils::TestLogger;
640 use lightning::util::errors::APIError;
641 use lightning::util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
642 use secp256k1::{SecretKey, PublicKey, Secp256k1};
643 use std::cell::RefCell;
644 use std::collections::VecDeque;
645 use std::time::{SystemTime, Duration};
646 use time_utils::tests::SinceEpoch;
647 use DEFAULT_EXPIRY_TIME;
649 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
650 let payment_hash = Sha256::hash(&payment_preimage.0);
651 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
653 InvoiceBuilder::new(Currency::Bitcoin)
654 .description("test".into())
655 .payment_hash(payment_hash)
656 .payment_secret(PaymentSecret([0; 32]))
657 .duration_since_epoch(duration_since_epoch())
658 .min_final_cltv_expiry(144)
659 .amount_milli_satoshis(128)
660 .build_signed(|hash| {
661 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
666 fn duration_since_epoch() -> Duration {
667 #[cfg(feature = "std")]
668 let duration_since_epoch =
669 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
670 #[cfg(not(feature = "std"))]
671 let duration_since_epoch = Duration::from_secs(1234567);
675 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
676 let payment_hash = Sha256::hash(&payment_preimage.0);
677 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
679 InvoiceBuilder::new(Currency::Bitcoin)
680 .description("test".into())
681 .payment_hash(payment_hash)
682 .payment_secret(PaymentSecret([0; 32]))
683 .duration_since_epoch(duration_since_epoch())
684 .min_final_cltv_expiry(144)
685 .build_signed(|hash| {
686 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
691 #[cfg(feature = "std")]
692 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
693 let payment_hash = Sha256::hash(&payment_preimage.0);
694 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
695 let duration = duration_since_epoch()
696 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
698 InvoiceBuilder::new(Currency::Bitcoin)
699 .description("test".into())
700 .payment_hash(payment_hash)
701 .payment_secret(PaymentSecret([0; 32]))
702 .duration_since_epoch(duration)
703 .min_final_cltv_expiry(144)
704 .amount_milli_satoshis(128)
705 .build_signed(|hash| {
706 Secp256k1::new().sign_ecdsa_recoverable(hash, &private_key)
711 fn pubkey() -> PublicKey {
712 PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap()
716 fn pays_invoice_on_first_attempt() {
717 let event_handled = core::cell::RefCell::new(false);
718 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
720 let payment_preimage = PaymentPreimage([1; 32]);
721 let invoice = invoice(payment_preimage);
722 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
723 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
725 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
726 let router = TestRouter {};
727 let scorer = RefCell::new(TestScorer::new());
728 let logger = TestLogger::new();
730 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
732 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
733 assert_eq!(*payer.attempts.borrow(), 1);
735 invoice_payer.handle_event(&Event::PaymentSent {
736 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
738 assert_eq!(*event_handled.borrow(), true);
739 assert_eq!(*payer.attempts.borrow(), 1);
743 fn pays_invoice_on_retry() {
744 let event_handled = core::cell::RefCell::new(false);
745 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
747 let payment_preimage = PaymentPreimage([1; 32]);
748 let invoice = invoice(payment_preimage);
749 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
750 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
752 let payer = TestPayer::new()
753 .expect_send(Amount::ForInvoice(final_value_msat))
754 .expect_send(Amount::OnRetry(final_value_msat / 2));
755 let router = TestRouter {};
756 let scorer = RefCell::new(TestScorer::new());
757 let logger = TestLogger::new();
759 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
761 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
762 assert_eq!(*payer.attempts.borrow(), 1);
764 let event = Event::PaymentPathFailed {
767 network_update: None,
768 rejected_by_dest: false,
769 all_paths_failed: false,
770 path: TestRouter::path_for_value(final_value_msat),
771 short_channel_id: None,
772 retry: Some(TestRouter::retry_for_invoice(&invoice)),
774 invoice_payer.handle_event(&event);
775 assert_eq!(*event_handled.borrow(), false);
776 assert_eq!(*payer.attempts.borrow(), 2);
778 invoice_payer.handle_event(&Event::PaymentSent {
779 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
781 assert_eq!(*event_handled.borrow(), true);
782 assert_eq!(*payer.attempts.borrow(), 2);
786 fn pays_invoice_on_partial_failure() {
787 let event_handler = |_: &_| { panic!() };
789 let payment_preimage = PaymentPreimage([1; 32]);
790 let invoice = invoice(payment_preimage);
791 let retry = TestRouter::retry_for_invoice(&invoice);
792 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
794 let payer = TestPayer::new()
795 .fails_with_partial_failure(retry.clone(), OnAttempt(1))
796 .fails_with_partial_failure(retry, OnAttempt(2))
797 .expect_send(Amount::ForInvoice(final_value_msat))
798 .expect_send(Amount::OnRetry(final_value_msat / 2))
799 .expect_send(Amount::OnRetry(final_value_msat / 2));
800 let router = TestRouter {};
801 let scorer = RefCell::new(TestScorer::new());
802 let logger = TestLogger::new();
804 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
806 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
810 fn retries_payment_path_for_unknown_payment() {
811 let event_handled = core::cell::RefCell::new(false);
812 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
814 let payment_preimage = PaymentPreimage([1; 32]);
815 let invoice = invoice(payment_preimage);
816 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
817 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
819 let payer = TestPayer::new()
820 .expect_send(Amount::OnRetry(final_value_msat / 2))
821 .expect_send(Amount::OnRetry(final_value_msat / 2));
822 let router = TestRouter {};
823 let scorer = RefCell::new(TestScorer::new());
824 let logger = TestLogger::new();
826 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
828 let payment_id = Some(PaymentId([1; 32]));
829 let event = Event::PaymentPathFailed {
832 network_update: None,
833 rejected_by_dest: false,
834 all_paths_failed: false,
835 path: TestRouter::path_for_value(final_value_msat),
836 short_channel_id: None,
837 retry: Some(TestRouter::retry_for_invoice(&invoice)),
839 invoice_payer.handle_event(&event);
840 assert_eq!(*event_handled.borrow(), false);
841 assert_eq!(*payer.attempts.borrow(), 1);
843 invoice_payer.handle_event(&event);
844 assert_eq!(*event_handled.borrow(), false);
845 assert_eq!(*payer.attempts.borrow(), 2);
847 invoice_payer.handle_event(&Event::PaymentSent {
848 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
850 assert_eq!(*event_handled.borrow(), true);
851 assert_eq!(*payer.attempts.borrow(), 2);
855 fn fails_paying_invoice_after_max_retry_counts() {
856 let event_handled = core::cell::RefCell::new(false);
857 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
859 let payment_preimage = PaymentPreimage([1; 32]);
860 let invoice = invoice(payment_preimage);
861 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
863 let payer = TestPayer::new()
864 .expect_send(Amount::ForInvoice(final_value_msat))
865 .expect_send(Amount::OnRetry(final_value_msat / 2))
866 .expect_send(Amount::OnRetry(final_value_msat / 2));
867 let router = TestRouter {};
868 let scorer = RefCell::new(TestScorer::new());
869 let logger = TestLogger::new();
871 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
873 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
874 assert_eq!(*payer.attempts.borrow(), 1);
876 let event = Event::PaymentPathFailed {
878 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
879 network_update: None,
880 rejected_by_dest: false,
881 all_paths_failed: true,
882 path: TestRouter::path_for_value(final_value_msat),
883 short_channel_id: None,
884 retry: Some(TestRouter::retry_for_invoice(&invoice)),
886 invoice_payer.handle_event(&event);
887 assert_eq!(*event_handled.borrow(), false);
888 assert_eq!(*payer.attempts.borrow(), 2);
890 let event = Event::PaymentPathFailed {
892 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
893 network_update: None,
894 rejected_by_dest: false,
895 all_paths_failed: false,
896 path: TestRouter::path_for_value(final_value_msat / 2),
897 short_channel_id: None,
898 retry: Some(RouteParameters {
899 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
902 invoice_payer.handle_event(&event);
903 assert_eq!(*event_handled.borrow(), false);
904 assert_eq!(*payer.attempts.borrow(), 3);
906 invoice_payer.handle_event(&event);
907 assert_eq!(*event_handled.borrow(), true);
908 assert_eq!(*payer.attempts.borrow(), 3);
911 #[cfg(feature = "std")]
913 fn fails_paying_invoice_after_max_retry_timeout() {
914 let event_handled = core::cell::RefCell::new(false);
915 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
917 let payment_preimage = PaymentPreimage([1; 32]);
918 let invoice = invoice(payment_preimage);
919 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
921 let payer = TestPayer::new()
922 .expect_send(Amount::ForInvoice(final_value_msat))
923 .expect_send(Amount::OnRetry(final_value_msat / 2));
925 let router = TestRouter {};
926 let scorer = RefCell::new(TestScorer::new());
927 let logger = TestLogger::new();
928 type InvoicePayerUsingSinceEpoch <P, R, S, L, E> = InvoicePayerUsingTime::<P, R, S, L, E, SinceEpoch>;
931 InvoicePayerUsingSinceEpoch::new(&payer, router, &scorer, &logger, event_handler, Retry::Timeout(Duration::from_secs(120)));
933 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
934 assert_eq!(*payer.attempts.borrow(), 1);
936 let event = Event::PaymentPathFailed {
938 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
939 network_update: None,
940 rejected_by_dest: false,
941 all_paths_failed: true,
942 path: TestRouter::path_for_value(final_value_msat),
943 short_channel_id: None,
944 retry: Some(TestRouter::retry_for_invoice(&invoice)),
946 invoice_payer.handle_event(&event);
947 assert_eq!(*event_handled.borrow(), false);
948 assert_eq!(*payer.attempts.borrow(), 2);
950 SinceEpoch::advance(Duration::from_secs(121));
952 invoice_payer.handle_event(&event);
953 assert_eq!(*event_handled.borrow(), true);
954 assert_eq!(*payer.attempts.borrow(), 2);
958 fn fails_paying_invoice_with_missing_retry_params() {
959 let event_handled = core::cell::RefCell::new(false);
960 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
962 let payment_preimage = PaymentPreimage([1; 32]);
963 let invoice = invoice(payment_preimage);
964 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
966 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
967 let router = TestRouter {};
968 let scorer = RefCell::new(TestScorer::new());
969 let logger = TestLogger::new();
971 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
973 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
974 assert_eq!(*payer.attempts.borrow(), 1);
976 let event = Event::PaymentPathFailed {
978 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
979 network_update: None,
980 rejected_by_dest: false,
981 all_paths_failed: false,
983 short_channel_id: None,
986 invoice_payer.handle_event(&event);
987 assert_eq!(*event_handled.borrow(), true);
988 assert_eq!(*payer.attempts.borrow(), 1);
991 // Expiration is checked only in an std environment
992 #[cfg(feature = "std")]
994 fn fails_paying_invoice_after_expiration() {
995 let event_handled = core::cell::RefCell::new(false);
996 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
998 let payer = TestPayer::new();
999 let router = TestRouter {};
1000 let scorer = RefCell::new(TestScorer::new());
1001 let logger = TestLogger::new();
1003 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1005 let payment_preimage = PaymentPreimage([1; 32]);
1006 let invoice = expired_invoice(payment_preimage);
1007 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
1008 assert_eq!(msg, "Invoice expired prior to send");
1009 } else { panic!("Expected Invoice Error"); }
1012 // Expiration is checked only in an std environment
1013 #[cfg(feature = "std")]
1015 fn fails_retrying_invoice_after_expiration() {
1016 let event_handled = core::cell::RefCell::new(false);
1017 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1019 let payment_preimage = PaymentPreimage([1; 32]);
1020 let invoice = invoice(payment_preimage);
1021 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1023 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1024 let router = TestRouter {};
1025 let scorer = RefCell::new(TestScorer::new());
1026 let logger = TestLogger::new();
1028 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1030 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1031 assert_eq!(*payer.attempts.borrow(), 1);
1033 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
1034 retry_data.payment_params.expiry_time = Some(SystemTime::now()
1035 .checked_sub(Duration::from_secs(2)).unwrap()
1036 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
1037 let event = Event::PaymentPathFailed {
1039 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1040 network_update: None,
1041 rejected_by_dest: false,
1042 all_paths_failed: false,
1044 short_channel_id: None,
1045 retry: Some(retry_data),
1047 invoice_payer.handle_event(&event);
1048 assert_eq!(*event_handled.borrow(), true);
1049 assert_eq!(*payer.attempts.borrow(), 1);
1053 fn fails_paying_invoice_after_retry_error() {
1054 let event_handled = core::cell::RefCell::new(false);
1055 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1057 let payment_preimage = PaymentPreimage([1; 32]);
1058 let invoice = invoice(payment_preimage);
1059 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1061 let payer = TestPayer::new()
1062 .fails_on_attempt(2)
1063 .expect_send(Amount::ForInvoice(final_value_msat))
1064 .expect_send(Amount::OnRetry(final_value_msat / 2));
1065 let router = TestRouter {};
1066 let scorer = RefCell::new(TestScorer::new());
1067 let logger = TestLogger::new();
1069 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1071 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1072 assert_eq!(*payer.attempts.borrow(), 1);
1074 let event = Event::PaymentPathFailed {
1076 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1077 network_update: None,
1078 rejected_by_dest: false,
1079 all_paths_failed: false,
1080 path: TestRouter::path_for_value(final_value_msat / 2),
1081 short_channel_id: None,
1082 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1084 invoice_payer.handle_event(&event);
1085 assert_eq!(*event_handled.borrow(), true);
1086 assert_eq!(*payer.attempts.borrow(), 2);
1090 fn fails_paying_invoice_after_rejected_by_payee() {
1091 let event_handled = core::cell::RefCell::new(false);
1092 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1094 let payment_preimage = PaymentPreimage([1; 32]);
1095 let invoice = invoice(payment_preimage);
1096 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1098 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1099 let router = TestRouter {};
1100 let scorer = RefCell::new(TestScorer::new());
1101 let logger = TestLogger::new();
1103 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1105 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1106 assert_eq!(*payer.attempts.borrow(), 1);
1108 let event = Event::PaymentPathFailed {
1110 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
1111 network_update: None,
1112 rejected_by_dest: true,
1113 all_paths_failed: false,
1115 short_channel_id: None,
1116 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1118 invoice_payer.handle_event(&event);
1119 assert_eq!(*event_handled.borrow(), true);
1120 assert_eq!(*payer.attempts.borrow(), 1);
1124 fn fails_repaying_invoice_with_pending_payment() {
1125 let event_handled = core::cell::RefCell::new(false);
1126 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1128 let payment_preimage = PaymentPreimage([1; 32]);
1129 let invoice = invoice(payment_preimage);
1130 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1132 let payer = TestPayer::new()
1133 .expect_send(Amount::ForInvoice(final_value_msat))
1134 .expect_send(Amount::ForInvoice(final_value_msat));
1135 let router = TestRouter {};
1136 let scorer = RefCell::new(TestScorer::new());
1137 let logger = TestLogger::new();
1139 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1141 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1143 // Cannot repay an invoice pending payment.
1144 match invoice_payer.pay_invoice(&invoice) {
1145 Err(PaymentError::Invoice("payment pending")) => {},
1146 Err(_) => panic!("unexpected error"),
1147 Ok(_) => panic!("expected invoice error"),
1150 // Can repay an invoice once cleared from cache.
1151 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1152 invoice_payer.remove_cached_payment(&payment_hash);
1153 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
1155 // Cannot retry paying an invoice if cleared from cache.
1156 invoice_payer.remove_cached_payment(&payment_hash);
1157 let event = Event::PaymentPathFailed {
1160 network_update: None,
1161 rejected_by_dest: false,
1162 all_paths_failed: false,
1164 short_channel_id: None,
1165 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1167 invoice_payer.handle_event(&event);
1168 assert_eq!(*event_handled.borrow(), true);
1172 fn fails_paying_invoice_with_routing_errors() {
1173 let payer = TestPayer::new();
1174 let router = FailingRouter {};
1175 let scorer = RefCell::new(TestScorer::new());
1176 let logger = TestLogger::new();
1178 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1180 let payment_preimage = PaymentPreimage([1; 32]);
1181 let invoice = invoice(payment_preimage);
1182 match invoice_payer.pay_invoice(&invoice) {
1183 Err(PaymentError::Routing(_)) => {},
1184 Err(_) => panic!("unexpected error"),
1185 Ok(_) => panic!("expected routing error"),
1190 fn fails_paying_invoice_with_sending_errors() {
1191 let payment_preimage = PaymentPreimage([1; 32]);
1192 let invoice = invoice(payment_preimage);
1193 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1195 let payer = TestPayer::new()
1196 .fails_on_attempt(1)
1197 .expect_send(Amount::ForInvoice(final_value_msat));
1198 let router = TestRouter {};
1199 let scorer = RefCell::new(TestScorer::new());
1200 let logger = TestLogger::new();
1202 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, Retry::Attempts(0));
1204 match invoice_payer.pay_invoice(&invoice) {
1205 Err(PaymentError::Sending(_)) => {},
1206 Err(_) => panic!("unexpected error"),
1207 Ok(_) => panic!("expected sending error"),
1212 fn pays_zero_value_invoice_using_amount() {
1213 let event_handled = core::cell::RefCell::new(false);
1214 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1216 let payment_preimage = PaymentPreimage([1; 32]);
1217 let invoice = zero_value_invoice(payment_preimage);
1218 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1219 let final_value_msat = 100;
1221 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1222 let router = TestRouter {};
1223 let scorer = RefCell::new(TestScorer::new());
1224 let logger = TestLogger::new();
1226 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1229 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
1230 assert_eq!(*payer.attempts.borrow(), 1);
1232 invoice_payer.handle_event(&Event::PaymentSent {
1233 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1235 assert_eq!(*event_handled.borrow(), true);
1236 assert_eq!(*payer.attempts.borrow(), 1);
1240 fn fails_paying_zero_value_invoice_with_amount() {
1241 let event_handled = core::cell::RefCell::new(false);
1242 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1244 let payer = TestPayer::new();
1245 let router = TestRouter {};
1246 let scorer = RefCell::new(TestScorer::new());
1247 let logger = TestLogger::new();
1249 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(0));
1251 let payment_preimage = PaymentPreimage([1; 32]);
1252 let invoice = invoice(payment_preimage);
1254 // Cannot repay an invoice pending payment.
1255 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
1256 Err(PaymentError::Invoice("amount unexpected")) => {},
1257 Err(_) => panic!("unexpected error"),
1258 Ok(_) => panic!("expected invoice error"),
1263 fn pays_pubkey_with_amount() {
1264 let event_handled = core::cell::RefCell::new(false);
1265 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1267 let pubkey = pubkey();
1268 let payment_preimage = PaymentPreimage([1; 32]);
1269 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1270 let final_value_msat = 100;
1271 let final_cltv_expiry_delta = 42;
1273 let payer = TestPayer::new()
1274 .expect_send(Amount::Spontaneous(final_value_msat))
1275 .expect_send(Amount::OnRetry(final_value_msat));
1276 let router = TestRouter {};
1277 let scorer = RefCell::new(TestScorer::new());
1278 let logger = TestLogger::new();
1280 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1282 let payment_id = Some(invoice_payer.pay_pubkey(
1283 pubkey, payment_preimage, final_value_msat, final_cltv_expiry_delta
1285 assert_eq!(*payer.attempts.borrow(), 1);
1287 let retry = RouteParameters {
1288 payment_params: PaymentParameters::for_keysend(pubkey),
1290 final_cltv_expiry_delta,
1292 let event = Event::PaymentPathFailed {
1295 network_update: None,
1296 rejected_by_dest: false,
1297 all_paths_failed: false,
1299 short_channel_id: None,
1302 invoice_payer.handle_event(&event);
1303 assert_eq!(*event_handled.borrow(), false);
1304 assert_eq!(*payer.attempts.borrow(), 2);
1306 invoice_payer.handle_event(&Event::PaymentSent {
1307 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
1309 assert_eq!(*event_handled.borrow(), true);
1310 assert_eq!(*payer.attempts.borrow(), 2);
1314 fn scores_failed_channel() {
1315 let event_handled = core::cell::RefCell::new(false);
1316 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1318 let payment_preimage = PaymentPreimage([1; 32]);
1319 let invoice = invoice(payment_preimage);
1320 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
1321 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1322 let path = TestRouter::path_for_value(final_value_msat);
1323 let short_channel_id = Some(path[0].short_channel_id);
1325 // Expect that scorer is given short_channel_id upon handling the event.
1326 let payer = TestPayer::new()
1327 .expect_send(Amount::ForInvoice(final_value_msat))
1328 .expect_send(Amount::OnRetry(final_value_msat / 2));
1329 let router = TestRouter {};
1330 let scorer = RefCell::new(TestScorer::new().expect(TestResult::PaymentFailure {
1331 path: path.clone(), short_channel_id: path[0].short_channel_id,
1333 let logger = TestLogger::new();
1335 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1337 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
1338 let event = Event::PaymentPathFailed {
1341 network_update: None,
1342 rejected_by_dest: false,
1343 all_paths_failed: false,
1346 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1348 invoice_payer.handle_event(&event);
1352 fn scores_successful_channels() {
1353 let event_handled = core::cell::RefCell::new(false);
1354 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1356 let payment_preimage = PaymentPreimage([1; 32]);
1357 let invoice = invoice(payment_preimage);
1358 let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1359 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1360 let route = TestRouter::route_for_value(final_value_msat);
1362 // Expect that scorer is given short_channel_id upon handling the event.
1363 let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1364 let router = TestRouter {};
1365 let scorer = RefCell::new(TestScorer::new()
1366 .expect(TestResult::PaymentSuccess { path: route.paths[0].clone() })
1367 .expect(TestResult::PaymentSuccess { path: route.paths[1].clone() })
1369 let logger = TestLogger::new();
1371 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, Retry::Attempts(2));
1373 let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1374 let event = Event::PaymentPathSuccessful {
1375 payment_id, payment_hash, path: route.paths[0].clone()
1377 invoice_payer.handle_event(&event);
1378 let event = Event::PaymentPathSuccessful {
1379 payment_id, payment_hash, path: route.paths[1].clone()
1381 invoice_payer.handle_event(&event);
1387 fn route_for_value(final_value_msat: u64) -> Route {
1391 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1392 channel_features: ChannelFeatures::empty(),
1393 node_features: NodeFeatures::empty(),
1394 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1397 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1398 channel_features: ChannelFeatures::empty(),
1399 node_features: NodeFeatures::empty(),
1400 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1403 payment_params: None,
1407 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1408 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1411 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1412 let mut payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1413 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1414 .with_route_hints(invoice.route_hints());
1415 if let Some(features) = invoice.features() {
1416 payment_params = payment_params.with_features(features.clone());
1418 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1422 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1427 impl<S: Score> Router<S> for TestRouter {
1429 &self, _payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash,
1430 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1431 ) -> Result<Route, LightningError> {
1433 payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat)
1438 struct FailingRouter;
1440 impl<S: Score> Router<S> for FailingRouter {
1442 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1443 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1444 ) -> Result<Route, LightningError> {
1445 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1450 expectations: Option<VecDeque<TestResult>>,
1455 PaymentFailure { path: Vec<RouteHop>, short_channel_id: u64 },
1456 PaymentSuccess { path: Vec<RouteHop> },
1466 fn expect(mut self, expectation: TestResult) -> Self {
1467 self.expectations.get_or_insert_with(|| VecDeque::new()).push_back(expectation);
1473 impl lightning::util::ser::Writeable for TestScorer {
1474 fn write<W: lightning::util::ser::Writer>(&self, _: &mut W) -> Result<(), std::io::Error> { unreachable!(); }
1477 impl Score for TestScorer {
1478 fn channel_penalty_msat(
1479 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage
1482 fn payment_path_failed(&mut self, actual_path: &[&RouteHop], actual_short_channel_id: u64) {
1483 if let Some(expectations) = &mut self.expectations {
1484 match expectations.pop_front() {
1485 Some(TestResult::PaymentFailure { path, short_channel_id }) => {
1486 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1487 assert_eq!(actual_short_channel_id, short_channel_id);
1489 Some(TestResult::PaymentSuccess { path }) => {
1490 panic!("Unexpected successful payment path: {:?}", path)
1492 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1497 fn payment_path_successful(&mut self, actual_path: &[&RouteHop]) {
1498 if let Some(expectations) = &mut self.expectations {
1499 match expectations.pop_front() {
1500 Some(TestResult::PaymentFailure { path, .. }) => {
1501 panic!("Unexpected payment path failure: {:?}", path)
1503 Some(TestResult::PaymentSuccess { path }) => {
1504 assert_eq!(actual_path, &path.iter().collect::<Vec<_>>()[..]);
1506 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1511 fn probe_failed(&mut self, actual_path: &[&RouteHop], _: u64) {
1512 if let Some(expectations) = &mut self.expectations {
1513 match expectations.pop_front() {
1514 Some(TestResult::PaymentFailure { path, .. }) => {
1515 panic!("Unexpected failed payment path: {:?}", path)
1517 Some(TestResult::PaymentSuccess { path }) => {
1518 panic!("Unexpected successful payment path: {:?}", path)
1520 None => panic!("Unexpected payment_path_failed call: {:?}", actual_path),
1524 fn probe_successful(&mut self, actual_path: &[&RouteHop]) {
1525 if let Some(expectations) = &mut self.expectations {
1526 match expectations.pop_front() {
1527 Some(TestResult::PaymentFailure { path, .. }) => {
1528 panic!("Unexpected payment path failure: {:?}", path)
1530 Some(TestResult::PaymentSuccess { path }) => {
1531 panic!("Unexpected successful payment path: {:?}", path)
1533 None => panic!("Unexpected payment_path_successful call: {:?}", actual_path),
1539 impl Drop for TestScorer {
1540 fn drop(&mut self) {
1541 if std::thread::panicking() {
1545 if let Some(expectations) = &self.expectations {
1546 if !expectations.is_empty() {
1547 panic!("Unsatisfied scorer expectations: {:?}", expectations);
1554 expectations: core::cell::RefCell<VecDeque<Amount>>,
1555 attempts: core::cell::RefCell<usize>,
1556 failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1559 #[derive(Clone, Debug, PartialEq, Eq)]
1566 struct OnAttempt(usize);
1571 expectations: core::cell::RefCell::new(VecDeque::new()),
1572 attempts: core::cell::RefCell::new(0),
1573 failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1577 fn expect_send(self, value_msat: Amount) -> Self {
1578 self.expectations.borrow_mut().push_back(value_msat);
1582 fn fails_on_attempt(self, attempt: usize) -> Self {
1583 let failure = PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed);
1584 self.fails_with(failure, OnAttempt(attempt))
1587 fn fails_with_partial_failure(self, retry: RouteParameters, attempt: OnAttempt) -> Self {
1588 self.fails_with(PaymentSendFailure::PartialFailure {
1590 failed_paths_retry: Some(retry),
1591 payment_id: PaymentId([1; 32]),
1595 fn fails_with(self, failure: PaymentSendFailure, attempt: OnAttempt) -> Self {
1596 self.failing_on_attempt.borrow_mut().insert(attempt.0, failure);
1600 fn check_attempts(&self) -> Result<PaymentId, PaymentSendFailure> {
1601 let mut attempts = self.attempts.borrow_mut();
1604 match self.failing_on_attempt.borrow_mut().remove(&*attempts) {
1605 Some(failure) => Err(failure),
1606 None => Ok(PaymentId([1; 32])),
1610 fn check_value_msats(&self, actual_value_msats: Amount) {
1611 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1612 if let Some(expected_value_msats) = expected_value_msats {
1613 assert_eq!(actual_value_msats, expected_value_msats);
1615 panic!("Unexpected amount: {:?}", actual_value_msats);
1620 impl Drop for TestPayer {
1621 fn drop(&mut self) {
1622 if std::thread::panicking() {
1626 if !self.expectations.borrow().is_empty() {
1627 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1632 impl Payer for TestPayer {
1633 fn node_id(&self) -> PublicKey {
1634 let secp_ctx = Secp256k1::new();
1635 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1638 fn first_hops(&self) -> Vec<ChannelDetails> {
1643 &self, route: &Route, _payment_hash: PaymentHash,
1644 _payment_secret: &Option<PaymentSecret>
1645 ) -> Result<PaymentId, PaymentSendFailure> {
1646 self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
1647 self.check_attempts()
1650 fn send_spontaneous_payment(
1651 &self, route: &Route, _payment_preimage: PaymentPreimage,
1652 ) -> Result<PaymentId, PaymentSendFailure> {
1653 self.check_value_msats(Amount::Spontaneous(route.get_total_amount()));
1654 self.check_attempts()
1658 &self, route: &Route, _payment_id: PaymentId
1659 ) -> Result<(), PaymentSendFailure> {
1660 self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
1661 self.check_attempts().map(|_| ())
1664 fn abandon_payment(&self, _payment_id: PaymentId) { }
1667 // *** Full Featured Functional Tests with a Real ChannelManager ***
1668 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1670 impl<S: Score> Router<S> for ManualRouter {
1672 &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash,
1673 _first_hops: Option<&[&ChannelDetails]>, _scorer: &S
1674 ) -> Result<Route, LightningError> {
1675 self.0.borrow_mut().pop_front().unwrap()
1679 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1680 self.0.borrow_mut().push_back(result);
1683 impl Drop for ManualRouter {
1684 fn drop(&mut self) {
1685 if std::thread::panicking() {
1688 assert!(self.0.borrow_mut().is_empty());
1693 fn retry_multi_path_single_failed_payment() {
1694 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1695 let chanmon_cfgs = create_chanmon_cfgs(2);
1696 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1697 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1698 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1700 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1701 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1702 let chans = nodes[0].node.list_usable_channels();
1703 let mut route = Route {
1706 pubkey: nodes[1].node.get_our_node_id(),
1707 node_features: NodeFeatures::known(),
1708 short_channel_id: chans[0].short_channel_id.unwrap(),
1709 channel_features: ChannelFeatures::known(),
1711 cltv_expiry_delta: 100,
1714 pubkey: nodes[1].node.get_our_node_id(),
1715 node_features: NodeFeatures::known(),
1716 short_channel_id: chans[1].short_channel_id.unwrap(),
1717 channel_features: ChannelFeatures::known(),
1718 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1719 cltv_expiry_delta: 100,
1722 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1724 let router = ManualRouter(RefCell::new(VecDeque::new()));
1725 router.expect_find_route(Ok(route.clone()));
1726 // On retry, split the payment across both channels.
1727 route.paths[0][0].fee_msat = 50_000_001;
1728 route.paths[1][0].fee_msat = 50_000_000;
1729 router.expect_find_route(Ok(route.clone()));
1731 let event_handler = |_: &_| { panic!(); };
1732 let scorer = RefCell::new(TestScorer::new());
1733 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1735 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1736 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1737 duration_since_epoch(), 3600).unwrap())
1739 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1740 assert_eq!(htlc_msgs.len(), 2);
1741 check_added_monitors!(nodes[0], 2);
1745 fn immediate_retry_on_failure() {
1746 // Tests that we can/will retry immediately after a failure
1747 let chanmon_cfgs = create_chanmon_cfgs(2);
1748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1750 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1752 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1753 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1754 let chans = nodes[0].node.list_usable_channels();
1755 let mut route = Route {
1758 pubkey: nodes[1].node.get_our_node_id(),
1759 node_features: NodeFeatures::known(),
1760 short_channel_id: chans[0].short_channel_id.unwrap(),
1761 channel_features: ChannelFeatures::known(),
1762 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1763 cltv_expiry_delta: 100,
1766 payment_params: Some(PaymentParameters::from_node_id(nodes[1].node.get_our_node_id())),
1768 let router = ManualRouter(RefCell::new(VecDeque::new()));
1769 router.expect_find_route(Ok(route.clone()));
1770 // On retry, split the payment across both channels.
1771 route.paths.push(route.paths[0].clone());
1772 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1773 route.paths[0][0].fee_msat = 50_000_000;
1774 route.paths[1][0].fee_msat = 50_000_001;
1775 router.expect_find_route(Ok(route.clone()));
1777 let event_handler = |_: &_| { panic!(); };
1778 let scorer = RefCell::new(TestScorer::new());
1779 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1781 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1782 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1783 duration_since_epoch(), 3600).unwrap())
1785 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1786 assert_eq!(htlc_msgs.len(), 2);
1787 check_added_monitors!(nodes[0], 2);
1791 fn no_extra_retries_on_back_to_back_fail() {
1792 // In a previous release, we had a race where we may exceed the payment retry count if we
1793 // get two failures in a row with the second having `all_paths_failed` set.
1794 // Generally, when we give up trying to retry a payment, we don't know for sure what the
1795 // current state of the ChannelManager event queue is. Specifically, we cannot be sure that
1796 // there are not multiple additional `PaymentPathFailed` or even `PaymentSent` events
1797 // pending which we will see later. Thus, when we previously removed the retry tracking map
1798 // entry after a `all_paths_failed` `PaymentPathFailed` event, we may have dropped the
1799 // retry entry even though more events for the same payment were still pending. This led to
1800 // us retrying a payment again even though we'd already given up on it.
1802 // We now have a separate event - `PaymentFailed` which indicates no HTLCs remain and which
1803 // is used to remove the payment retry counter entries instead. This tests for the specific
1804 // excess-retry case while also testing `PaymentFailed` generation.
1806 let chanmon_cfgs = create_chanmon_cfgs(3);
1807 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1808 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1809 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1811 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;
1812 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;
1814 let mut route = Route {
1817 pubkey: nodes[1].node.get_our_node_id(),
1818 node_features: NodeFeatures::known(),
1819 short_channel_id: chan_1_scid,
1820 channel_features: ChannelFeatures::known(),
1822 cltv_expiry_delta: 100,
1824 pubkey: nodes[2].node.get_our_node_id(),
1825 node_features: NodeFeatures::known(),
1826 short_channel_id: chan_2_scid,
1827 channel_features: ChannelFeatures::known(),
1828 fee_msat: 100_000_000,
1829 cltv_expiry_delta: 100,
1832 pubkey: nodes[1].node.get_our_node_id(),
1833 node_features: NodeFeatures::known(),
1834 short_channel_id: chan_1_scid,
1835 channel_features: ChannelFeatures::known(),
1837 cltv_expiry_delta: 100,
1839 pubkey: nodes[2].node.get_our_node_id(),
1840 node_features: NodeFeatures::known(),
1841 short_channel_id: chan_2_scid,
1842 channel_features: ChannelFeatures::known(),
1843 fee_msat: 100_000_000,
1844 cltv_expiry_delta: 100,
1847 payment_params: Some(PaymentParameters::from_node_id(nodes[2].node.get_our_node_id())),
1849 let router = ManualRouter(RefCell::new(VecDeque::new()));
1850 router.expect_find_route(Ok(route.clone()));
1851 // On retry, we'll only be asked for one path
1852 route.paths.remove(1);
1853 router.expect_find_route(Ok(route.clone()));
1855 let expected_events: RefCell<VecDeque<&dyn Fn(&Event)>> = RefCell::new(VecDeque::new());
1856 let event_handler = |event: &Event| {
1857 let event_checker = expected_events.borrow_mut().pop_front().unwrap();
1858 event_checker(event);
1860 let scorer = RefCell::new(TestScorer::new());
1861 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, Retry::Attempts(1));
1863 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch(
1864 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string(),
1865 duration_since_epoch(), 3600).unwrap())
1867 let htlc_updates = SendEvent::from_node(&nodes[0]);
1868 check_added_monitors!(nodes[0], 1);
1869 assert_eq!(htlc_updates.msgs.len(), 1);
1871 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &htlc_updates.msgs[0]);
1872 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &htlc_updates.commitment_msg);
1873 check_added_monitors!(nodes[1], 1);
1874 let (bs_first_raa, bs_first_cs) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1876 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_first_raa);
1877 check_added_monitors!(nodes[0], 1);
1878 let second_htlc_updates = SendEvent::from_node(&nodes[0]);
1880 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_first_cs);
1881 check_added_monitors!(nodes[0], 1);
1882 let as_first_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1884 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &second_htlc_updates.msgs[0]);
1885 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &second_htlc_updates.commitment_msg);
1886 check_added_monitors!(nodes[1], 1);
1887 let bs_second_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1889 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_first_raa);
1890 check_added_monitors!(nodes[1], 1);
1891 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_raa);
1894 check_added_monitors!(nodes[0], 1);
1896 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1897 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_fail_update.commitment_signed);
1898 check_added_monitors!(nodes[0], 1);
1899 let (as_second_raa, as_third_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1901 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_raa);
1902 check_added_monitors!(nodes[1], 1);
1903 let bs_second_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_third_cs);
1906 check_added_monitors!(nodes[1], 1);
1907 let bs_third_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1909 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.update_fail_htlcs[0]);
1910 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_fail_update.commitment_signed);
1911 check_added_monitors!(nodes[0], 1);
1913 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_third_raa);
1914 check_added_monitors!(nodes[0], 1);
1915 let (as_third_raa, as_fourth_cs) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1917 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_third_raa);
1918 check_added_monitors!(nodes[1], 1);
1919 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_fourth_cs);
1920 check_added_monitors!(nodes[1], 1);
1921 let bs_fourth_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1923 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_fourth_raa);
1924 check_added_monitors!(nodes[0], 1);
1926 // At this point A has sent two HTLCs which both failed due to lack of fee. It now has two
1927 // pending `PaymentPathFailed` events, one with `all_paths_failed` unset, and the second
1928 // with it set. The first event will use up the only retry we are allowed, with the second
1929 // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd
1930 // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again
1931 // if the final HTLC failed.
1932 expected_events.borrow_mut().push_back(&|ev: &Event| {
1933 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1934 assert!(!rejected_by_dest);
1935 assert!(all_paths_failed);
1936 } else { panic!("Unexpected event"); }
1938 nodes[0].node.process_pending_events(&invoice_payer);
1939 assert!(expected_events.borrow().is_empty());
1941 let retry_htlc_updates = SendEvent::from_node(&nodes[0]);
1942 check_added_monitors!(nodes[0], 1);
1944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &retry_htlc_updates.msgs[0]);
1945 commitment_signed_dance!(nodes[1], nodes[0], &retry_htlc_updates.commitment_msg, false, true);
1946 let bs_fail_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1947 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]);
1948 commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true);
1950 expected_events.borrow_mut().push_back(&|ev: &Event| {
1951 if let Event::PaymentPathFailed { rejected_by_dest, all_paths_failed, .. } = ev {
1952 assert!(!rejected_by_dest);
1953 assert!(all_paths_failed);
1954 } else { panic!("Unexpected event"); }
1956 expected_events.borrow_mut().push_back(&|ev: &Event| {
1957 if let Event::PaymentFailed { .. } = ev {
1958 } else { panic!("Unexpected event"); }
1960 nodes[0].node.process_pending_events(&invoice_payer);
1961 assert!(expected_events.borrow().is_empty());