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.
12 //! Defines an [`InvoicePayer`] utility for paying invoices, 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`].
17 //! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing
18 //! [`EventHandler`] which decorates a user-provided handler. It will intercept any
19 //! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total
20 //! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass
21 //! along the events to the user-provided handler.
26 //! # extern crate lightning;
27 //! # extern crate lightning_invoice;
28 //! # extern crate secp256k1;
30 //! # use lightning::ln::{PaymentHash, PaymentSecret};
31 //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
32 //! # use lightning::ln::msgs::LightningError;
33 //! # use lightning::routing;
34 //! # use lightning::routing::network_graph::NodeId;
35 //! # use lightning::routing::router::{Route, RouteHop, RouteParameters};
36 //! # use lightning::util::events::{Event, EventHandler, EventsProvider};
37 //! # use lightning::util::logger::{Logger, Record};
38 //! # use lightning_invoice::Invoice;
39 //! # use lightning_invoice::payment::{InvoicePayer, Payer, RetryAttempts, Router};
40 //! # use secp256k1::key::PublicKey;
41 //! # use std::cell::RefCell;
42 //! # use std::ops::Deref;
44 //! # struct FakeEventProvider {}
45 //! # impl EventsProvider for FakeEventProvider {
46 //! # fn process_pending_events<H: Deref>(&self, handler: H) where H::Target: EventHandler {}
49 //! # struct FakePayer {}
50 //! # impl Payer for FakePayer {
51 //! # fn node_id(&self) -> PublicKey { unimplemented!() }
52 //! # fn first_hops(&self) -> Vec<ChannelDetails> { unimplemented!() }
53 //! # fn send_payment(
54 //! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
55 //! # ) -> Result<PaymentId, PaymentSendFailure> { unimplemented!() }
56 //! # fn retry_payment(
57 //! # &self, route: &Route, payment_id: PaymentId
58 //! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
61 //! # struct FakeRouter {};
62 //! # impl<S: routing::Score> Router<S> for FakeRouter {
64 //! # &self, payer: &PublicKey, params: &RouteParameters,
65 //! # first_hops: Option<&[&ChannelDetails]>, scorer: &S
66 //! # ) -> Result<Route, LightningError> { unimplemented!() }
69 //! # struct FakeScorer {};
70 //! # impl routing::Score for FakeScorer {
71 //! # fn channel_penalty_msat(
72 //! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId
74 //! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {}
77 //! # struct FakeLogger {};
78 //! # impl Logger for FakeLogger {
79 //! # fn log(&self, record: &Record) { unimplemented!() }
83 //! let event_handler = |event: &Event| {
85 //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"),
86 //! Event::PaymentSent { .. } => println!("payment successful"),
90 //! # let payer = FakePayer {};
91 //! # let router = FakeRouter {};
92 //! # let scorer = RefCell::new(FakeScorer {});
93 //! # let logger = FakeLogger {};
94 //! let invoice_payer = InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
96 //! let invoice = "...";
97 //! let invoice = invoice.parse::<Invoice>().unwrap();
98 //! invoice_payer.pay_invoice(&invoice).unwrap();
100 //! # let event_provider = FakeEventProvider {};
102 //! event_provider.process_pending_events(&invoice_payer);
109 //! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such
110 //! as updates to the network graph or changes to channel scores should be applied prior to
111 //! retries, typically by way of composing [`EventHandler`]s accordingly.
115 use bitcoin_hashes::Hash;
117 use lightning::ln::{PaymentHash, PaymentSecret};
118 use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure};
119 use lightning::ln::msgs::LightningError;
120 use lightning::routing;
121 use lightning::routing::{LockableScore, Score};
122 use lightning::routing::router::{Payee, Route, RouteParameters};
123 use lightning::util::events::{Event, EventHandler};
124 use lightning::util::logger::Logger;
126 use secp256k1::key::PublicKey;
128 use std::collections::hash_map::{self, HashMap};
130 use std::sync::Mutex;
131 use std::time::{Duration, SystemTime};
133 /// A utility for paying [`Invoice]`s.
134 pub struct InvoicePayer<P: Deref, R, S: Deref, L: Deref, E>
137 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
138 S::Target: for <'a> routing::LockableScore<'a>,
147 /// Caches the overall attempts at making a payment, which is updated prior to retrying.
148 payment_cache: Mutex<HashMap<PaymentHash, usize>>,
149 retry_attempts: RetryAttempts,
152 /// A trait defining behavior of an [`Invoice`] payer.
154 /// Returns the payer's node id.
155 fn node_id(&self) -> PublicKey;
157 /// Returns the payer's channels.
158 fn first_hops(&self) -> Vec<ChannelDetails>;
160 /// Sends a payment over the Lightning Network using the given [`Route`].
162 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
163 ) -> Result<PaymentId, PaymentSendFailure>;
165 /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`].
166 fn retry_payment(&self, route: &Route, payment_id: PaymentId) -> Result<(), PaymentSendFailure>;
169 /// A trait defining behavior for routing an [`Invoice`] payment.
170 pub trait Router<S: routing::Score> {
171 /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
173 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
175 ) -> Result<Route, LightningError>;
178 /// Number of attempts to retry payment path failures for an [`Invoice`].
180 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
181 /// payments, if this is less than the total number of paths, we will never even retry all of the
183 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
184 pub struct RetryAttempts(pub usize);
186 /// An error that may occur when making a payment.
187 #[derive(Clone, Debug)]
188 pub enum PaymentError {
189 /// An error resulting from the provided [`Invoice`] or payment hash.
190 Invoice(&'static str),
191 /// An error occurring when finding a route.
192 Routing(LightningError),
193 /// An error occurring when sending a payment.
194 Sending(PaymentSendFailure),
197 impl<P: Deref, R, S: Deref, L: Deref, E> InvoicePayer<P, R, S, L, E>
200 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
201 S::Target: for <'a> routing::LockableScore<'a>,
205 /// Creates an invoice payer that retries failed payment paths.
207 /// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once
208 /// `retry_attempts` has been exceeded for a given [`Invoice`].
210 payer: P, router: R, scorer: S, logger: L, event_handler: E, retry_attempts: RetryAttempts
218 payment_cache: Mutex::new(HashMap::new()),
223 /// Pays the given [`Invoice`], caching it for later use in case a retry is needed.
225 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
226 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
228 pub fn pay_invoice(&self, invoice: &Invoice) -> Result<PaymentId, PaymentError> {
229 if invoice.amount_milli_satoshis().is_none() {
230 Err(PaymentError::Invoice("amount missing"))
232 self.pay_invoice_using_amount(invoice, None)
236 /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in
237 /// case a retry is needed.
239 /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has
240 /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so
242 pub fn pay_zero_value_invoice(
243 &self, invoice: &Invoice, amount_msats: u64
244 ) -> Result<PaymentId, PaymentError> {
245 if invoice.amount_milli_satoshis().is_some() {
246 Err(PaymentError::Invoice("amount unexpected"))
248 self.pay_invoice_using_amount(invoice, Some(amount_msats))
252 fn pay_invoice_using_amount(
253 &self, invoice: &Invoice, amount_msats: Option<u64>
254 ) -> Result<PaymentId, PaymentError> {
255 debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some());
257 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
258 match self.payment_cache.lock().unwrap().entry(payment_hash) {
259 hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")),
260 hash_map::Entry::Vacant(entry) => entry.insert(0),
263 let payment_secret = Some(invoice.payment_secret().clone());
264 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
265 .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs())
266 .with_route_hints(invoice.route_hints());
267 if let Some(features) = invoice.features() {
268 payee = payee.with_features(features.clone());
270 let params = RouteParameters {
272 final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(),
273 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
276 self.pay_internal(¶ms, payment_hash, &payment_secret)
277 .map_err(|e| { self.payment_cache.lock().unwrap().remove(&payment_hash); e })
281 &self, params: &RouteParameters, payment_hash: PaymentHash,
282 payment_secret: &Option<PaymentSecret>,
283 ) -> Result<PaymentId, PaymentError> {
284 if has_expired(params) {
285 log_trace!(self.logger, "Invoice expired prior to send for payment {}", log_bytes!(payment_hash.0));
286 return Err(PaymentError::Invoice("Invoice expired prior to send"));
289 let payer = self.payer.node_id();
290 let first_hops = self.payer.first_hops();
291 let route = self.router.find_route(
294 Some(&first_hops.iter().collect::<Vec<_>>()),
296 ).map_err(|e| PaymentError::Routing(e))?;
298 match self.payer.send_payment(&route, payment_hash, payment_secret) {
299 Ok(payment_id) => Ok(payment_id),
301 PaymentSendFailure::ParameterError(_) => Err(e),
302 PaymentSendFailure::PathParameterError(_) => Err(e),
303 PaymentSendFailure::AllFailedRetrySafe(_) => {
304 let mut payment_cache = self.payment_cache.lock().unwrap();
305 let retry_count = payment_cache.get_mut(&payment_hash).unwrap();
306 if *retry_count >= self.retry_attempts.0 {
310 std::mem::drop(payment_cache);
311 Ok(self.pay_internal(params, payment_hash, payment_secret)?)
314 PaymentSendFailure::PartialFailure { failed_paths_retry, payment_id, .. } => {
315 if let Some(retry_data) = failed_paths_retry {
316 // Some paths were sent, even if we failed to send the full MPP value our
317 // recipient may misbehave and claim the funds, at which point we have to
318 // consider the payment sent, so return `Ok()` here, ignoring any retry
320 let _ = self.retry_payment(payment_id, payment_hash, &retry_data);
323 // This may happen if we send a payment and some paths fail, but
324 // only due to a temporary monitor failure or the like, implying
325 // they're really in-flight, but we haven't sent the initial
326 // HTLC-Add messages yet.
331 }.map_err(|e| PaymentError::Sending(e))
335 &self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters
336 ) -> Result<(), ()> {
337 let max_payment_attempts = self.retry_attempts.0 + 1;
338 let attempts = *self.payment_cache.lock().unwrap()
340 .and_modify(|attempts| *attempts += 1)
343 if attempts >= max_payment_attempts {
344 log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
348 if has_expired(params) {
349 log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
353 let payer = self.payer.node_id();
354 let first_hops = self.payer.first_hops();
355 let route = self.router.find_route(&payer, ¶ms, Some(&first_hops.iter().collect::<Vec<_>>()), &self.scorer.lock());
357 log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts);
361 match self.payer.retry_payment(&route.unwrap(), payment_id) {
363 Err(PaymentSendFailure::ParameterError(_)) |
364 Err(PaymentSendFailure::PathParameterError(_)) => {
365 log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0));
368 Err(PaymentSendFailure::AllFailedRetrySafe(_)) => {
369 self.retry_payment(payment_id, payment_hash, params)
371 Err(PaymentSendFailure::PartialFailure { failed_paths_retry, .. }) => {
372 if let Some(retry) = failed_paths_retry {
373 // Always return Ok for the same reason as noted in pay_internal.
374 let _ = self.retry_payment(payment_id, payment_hash, &retry);
381 /// Removes the payment cached by the given payment hash.
383 /// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an
384 /// [`EventHandler`]. Otherwise, calling this method is unnecessary.
385 pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
386 self.payment_cache.lock().unwrap().remove(payment_hash);
390 fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
391 invoice.timestamp().duration_since(SystemTime::UNIX_EPOCH).unwrap() + invoice.expiry_time()
394 fn has_expired(params: &RouteParameters) -> bool {
395 if let Some(expiry_time) = params.payee.expiry_time {
396 Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time))
400 impl<P: Deref, R, S: Deref, L: Deref, E> EventHandler for InvoicePayer<P, R, S, L, E>
403 R: for <'a> Router<<<S as Deref>::Target as routing::LockableScore<'a>>::Locked>,
404 S::Target: for <'a> routing::LockableScore<'a>,
408 fn handle_event(&self, event: &Event) {
410 Event::PaymentPathFailed {
411 all_paths_failed, payment_id, payment_hash, rejected_by_dest, path,
412 short_channel_id, retry, ..
414 if let Some(short_channel_id) = short_channel_id {
415 let path = path.iter().collect::<Vec<_>>();
416 self.scorer.lock().payment_path_failed(&path, *short_channel_id);
419 if *rejected_by_dest {
420 log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0));
421 } else if payment_id.is_none() {
422 log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0));
423 } else if retry.is_none() {
424 log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0));
425 } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() {
426 // We retried at least somewhat, don't provide the PaymentPathFailed event to the user.
430 if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); }
432 Event::PaymentSent { payment_hash, .. } => {
433 let mut payment_cache = self.payment_cache.lock().unwrap();
434 let attempts = payment_cache
435 .remove(payment_hash)
436 .map_or(1, |attempts| attempts + 1);
437 log_trace!(self.logger, "Payment {} succeeded (attempts: {})", log_bytes!(payment_hash.0), attempts);
442 // Delegate to the decorated event handler unless the payment is retried.
443 self.event_handler.handle_event(event)
450 use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency};
451 use utils::create_invoice_from_channelmanager;
452 use bitcoin_hashes::sha256::Hash as Sha256;
453 use lightning::ln::PaymentPreimage;
454 use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures};
455 use lightning::ln::functional_test_utils::*;
456 use lightning::ln::msgs::{ErrorAction, LightningError};
457 use lightning::routing::network_graph::NodeId;
458 use lightning::routing::router::{Payee, Route, RouteHop};
459 use lightning::util::test_utils::TestLogger;
460 use lightning::util::errors::APIError;
461 use lightning::util::events::{Event, MessageSendEventsProvider};
462 use secp256k1::{SecretKey, PublicKey, Secp256k1};
463 use std::cell::RefCell;
464 use std::collections::VecDeque;
465 use std::time::{SystemTime, Duration};
467 fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
468 let payment_hash = Sha256::hash(&payment_preimage.0);
469 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
470 InvoiceBuilder::new(Currency::Bitcoin)
471 .description("test".into())
472 .payment_hash(payment_hash)
473 .payment_secret(PaymentSecret([0; 32]))
475 .min_final_cltv_expiry(144)
476 .amount_milli_satoshis(128)
477 .build_signed(|hash| {
478 Secp256k1::new().sign_recoverable(hash, &private_key)
483 fn zero_value_invoice(payment_preimage: PaymentPreimage) -> Invoice {
484 let payment_hash = Sha256::hash(&payment_preimage.0);
485 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
486 InvoiceBuilder::new(Currency::Bitcoin)
487 .description("test".into())
488 .payment_hash(payment_hash)
489 .payment_secret(PaymentSecret([0; 32]))
491 .min_final_cltv_expiry(144)
492 .build_signed(|hash| {
493 Secp256k1::new().sign_recoverable(hash, &private_key)
498 fn expired_invoice(payment_preimage: PaymentPreimage) -> Invoice {
499 let payment_hash = Sha256::hash(&payment_preimage.0);
500 let private_key = SecretKey::from_slice(&[42; 32]).unwrap();
501 let timestamp = SystemTime::now()
502 .checked_sub(Duration::from_secs(DEFAULT_EXPIRY_TIME * 2))
504 InvoiceBuilder::new(Currency::Bitcoin)
505 .description("test".into())
506 .payment_hash(payment_hash)
507 .payment_secret(PaymentSecret([0; 32]))
508 .timestamp(timestamp)
509 .min_final_cltv_expiry(144)
510 .amount_milli_satoshis(128)
511 .build_signed(|hash| {
512 Secp256k1::new().sign_recoverable(hash, &private_key)
518 fn pays_invoice_on_first_attempt() {
519 let event_handled = core::cell::RefCell::new(false);
520 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
522 let payment_preimage = PaymentPreimage([1; 32]);
523 let invoice = invoice(payment_preimage);
524 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
526 let payer = TestPayer::new();
527 let router = TestRouter {};
528 let scorer = RefCell::new(TestScorer::new());
529 let logger = TestLogger::new();
531 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
533 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
534 assert_eq!(*payer.attempts.borrow(), 1);
536 invoice_payer.handle_event(&Event::PaymentSent {
537 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
539 assert_eq!(*event_handled.borrow(), true);
540 assert_eq!(*payer.attempts.borrow(), 1);
544 fn pays_invoice_on_retry() {
545 let event_handled = core::cell::RefCell::new(false);
546 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
548 let payment_preimage = PaymentPreimage([1; 32]);
549 let invoice = invoice(payment_preimage);
550 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
551 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
553 let payer = TestPayer::new()
554 .expect_value_msat(final_value_msat)
555 .expect_value_msat(final_value_msat / 2);
556 let router = TestRouter {};
557 let scorer = RefCell::new(TestScorer::new());
558 let logger = TestLogger::new();
560 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
562 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
563 assert_eq!(*payer.attempts.borrow(), 1);
565 let event = Event::PaymentPathFailed {
568 network_update: None,
569 rejected_by_dest: false,
570 all_paths_failed: false,
571 path: TestRouter::path_for_value(final_value_msat),
572 short_channel_id: None,
573 retry: Some(TestRouter::retry_for_invoice(&invoice)),
575 invoice_payer.handle_event(&event);
576 assert_eq!(*event_handled.borrow(), false);
577 assert_eq!(*payer.attempts.borrow(), 2);
579 invoice_payer.handle_event(&Event::PaymentSent {
580 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
582 assert_eq!(*event_handled.borrow(), true);
583 assert_eq!(*payer.attempts.borrow(), 2);
587 fn retries_payment_path_for_unknown_payment() {
588 let event_handled = core::cell::RefCell::new(false);
589 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
591 let payment_preimage = PaymentPreimage([1; 32]);
592 let invoice = invoice(payment_preimage);
593 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
594 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
596 let payer = TestPayer::new();
597 let router = TestRouter {};
598 let scorer = RefCell::new(TestScorer::new());
599 let logger = TestLogger::new();
601 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
603 let payment_id = Some(PaymentId([1; 32]));
604 let event = Event::PaymentPathFailed {
607 network_update: None,
608 rejected_by_dest: false,
609 all_paths_failed: false,
610 path: TestRouter::path_for_value(final_value_msat),
611 short_channel_id: None,
612 retry: Some(TestRouter::retry_for_invoice(&invoice)),
614 invoice_payer.handle_event(&event);
615 assert_eq!(*event_handled.borrow(), false);
616 assert_eq!(*payer.attempts.borrow(), 1);
618 invoice_payer.handle_event(&event);
619 assert_eq!(*event_handled.borrow(), false);
620 assert_eq!(*payer.attempts.borrow(), 2);
622 invoice_payer.handle_event(&Event::PaymentSent {
623 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
625 assert_eq!(*event_handled.borrow(), true);
626 assert_eq!(*payer.attempts.borrow(), 2);
630 fn fails_paying_invoice_after_max_retries() {
631 let event_handled = core::cell::RefCell::new(false);
632 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
634 let payment_preimage = PaymentPreimage([1; 32]);
635 let invoice = invoice(payment_preimage);
636 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
638 let payer = TestPayer::new()
639 .expect_value_msat(final_value_msat)
640 .expect_value_msat(final_value_msat / 2)
641 .expect_value_msat(final_value_msat / 2);
642 let router = TestRouter {};
643 let scorer = RefCell::new(TestScorer::new());
644 let logger = TestLogger::new();
646 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
648 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
649 assert_eq!(*payer.attempts.borrow(), 1);
651 let event = Event::PaymentPathFailed {
653 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
654 network_update: None,
655 rejected_by_dest: false,
656 all_paths_failed: true,
657 path: TestRouter::path_for_value(final_value_msat),
658 short_channel_id: None,
659 retry: Some(TestRouter::retry_for_invoice(&invoice)),
661 invoice_payer.handle_event(&event);
662 assert_eq!(*event_handled.borrow(), false);
663 assert_eq!(*payer.attempts.borrow(), 2);
665 let event = Event::PaymentPathFailed {
667 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
668 network_update: None,
669 rejected_by_dest: false,
670 all_paths_failed: false,
671 path: TestRouter::path_for_value(final_value_msat / 2),
672 short_channel_id: None,
673 retry: Some(RouteParameters {
674 final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice)
677 invoice_payer.handle_event(&event);
678 assert_eq!(*event_handled.borrow(), false);
679 assert_eq!(*payer.attempts.borrow(), 3);
681 invoice_payer.handle_event(&event);
682 assert_eq!(*event_handled.borrow(), true);
683 assert_eq!(*payer.attempts.borrow(), 3);
687 fn fails_paying_invoice_with_missing_retry_params() {
688 let event_handled = core::cell::RefCell::new(false);
689 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
691 let payer = TestPayer::new();
692 let router = TestRouter {};
693 let scorer = RefCell::new(TestScorer::new());
694 let logger = TestLogger::new();
696 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
698 let payment_preimage = PaymentPreimage([1; 32]);
699 let invoice = invoice(payment_preimage);
700 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
701 assert_eq!(*payer.attempts.borrow(), 1);
703 let event = Event::PaymentPathFailed {
705 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
706 network_update: None,
707 rejected_by_dest: false,
708 all_paths_failed: false,
710 short_channel_id: None,
713 invoice_payer.handle_event(&event);
714 assert_eq!(*event_handled.borrow(), true);
715 assert_eq!(*payer.attempts.borrow(), 1);
719 fn fails_paying_invoice_after_expiration() {
720 let event_handled = core::cell::RefCell::new(false);
721 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
723 let payer = TestPayer::new();
724 let router = TestRouter {};
725 let scorer = RefCell::new(TestScorer::new());
726 let logger = TestLogger::new();
728 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
730 let payment_preimage = PaymentPreimage([1; 32]);
731 let invoice = expired_invoice(payment_preimage);
732 if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() {
733 assert_eq!(msg, "Invoice expired prior to send");
734 } else { panic!("Expected Invoice Error"); }
738 fn fails_retrying_invoice_after_expiration() {
739 let event_handled = core::cell::RefCell::new(false);
740 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
742 let payer = TestPayer::new();
743 let router = TestRouter {};
744 let scorer = RefCell::new(TestScorer::new());
745 let logger = TestLogger::new();
747 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
749 let payment_preimage = PaymentPreimage([1; 32]);
750 let invoice = invoice(payment_preimage);
751 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
752 assert_eq!(*payer.attempts.borrow(), 1);
754 let mut retry_data = TestRouter::retry_for_invoice(&invoice);
755 retry_data.payee.expiry_time = Some(SystemTime::now()
756 .checked_sub(Duration::from_secs(2)).unwrap()
757 .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs());
758 let event = Event::PaymentPathFailed {
760 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
761 network_update: None,
762 rejected_by_dest: false,
763 all_paths_failed: false,
765 short_channel_id: None,
766 retry: Some(retry_data),
768 invoice_payer.handle_event(&event);
769 assert_eq!(*event_handled.borrow(), true);
770 assert_eq!(*payer.attempts.borrow(), 1);
774 fn fails_paying_invoice_after_retry_error() {
775 let event_handled = core::cell::RefCell::new(false);
776 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
778 let payment_preimage = PaymentPreimage([1; 32]);
779 let invoice = invoice(payment_preimage);
780 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
782 let payer = TestPayer::new()
784 .expect_value_msat(final_value_msat);
785 let router = TestRouter {};
786 let scorer = RefCell::new(TestScorer::new());
787 let logger = TestLogger::new();
789 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
791 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
792 assert_eq!(*payer.attempts.borrow(), 1);
794 let event = Event::PaymentPathFailed {
796 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
797 network_update: None,
798 rejected_by_dest: false,
799 all_paths_failed: false,
800 path: TestRouter::path_for_value(final_value_msat / 2),
801 short_channel_id: None,
802 retry: Some(TestRouter::retry_for_invoice(&invoice)),
804 invoice_payer.handle_event(&event);
805 assert_eq!(*event_handled.borrow(), true);
806 assert_eq!(*payer.attempts.borrow(), 2);
810 fn fails_paying_invoice_after_rejected_by_payee() {
811 let event_handled = core::cell::RefCell::new(false);
812 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
814 let payer = TestPayer::new();
815 let router = TestRouter {};
816 let scorer = RefCell::new(TestScorer::new());
817 let logger = TestLogger::new();
819 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
821 let payment_preimage = PaymentPreimage([1; 32]);
822 let invoice = invoice(payment_preimage);
823 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
824 assert_eq!(*payer.attempts.borrow(), 1);
826 let event = Event::PaymentPathFailed {
828 payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()),
829 network_update: None,
830 rejected_by_dest: true,
831 all_paths_failed: false,
833 short_channel_id: None,
834 retry: Some(TestRouter::retry_for_invoice(&invoice)),
836 invoice_payer.handle_event(&event);
837 assert_eq!(*event_handled.borrow(), true);
838 assert_eq!(*payer.attempts.borrow(), 1);
842 fn fails_repaying_invoice_with_pending_payment() {
843 let event_handled = core::cell::RefCell::new(false);
844 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
846 let payer = TestPayer::new();
847 let router = TestRouter {};
848 let scorer = RefCell::new(TestScorer::new());
849 let logger = TestLogger::new();
851 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
853 let payment_preimage = PaymentPreimage([1; 32]);
854 let invoice = invoice(payment_preimage);
855 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
857 // Cannot repay an invoice pending payment.
858 match invoice_payer.pay_invoice(&invoice) {
859 Err(PaymentError::Invoice("payment pending")) => {},
860 Err(_) => panic!("unexpected error"),
861 Ok(_) => panic!("expected invoice error"),
864 // Can repay an invoice once cleared from cache.
865 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
866 invoice_payer.remove_cached_payment(&payment_hash);
867 assert!(invoice_payer.pay_invoice(&invoice).is_ok());
869 // Cannot retry paying an invoice if cleared from cache.
870 invoice_payer.remove_cached_payment(&payment_hash);
871 let event = Event::PaymentPathFailed {
874 network_update: None,
875 rejected_by_dest: false,
876 all_paths_failed: false,
878 short_channel_id: None,
879 retry: Some(TestRouter::retry_for_invoice(&invoice)),
881 invoice_payer.handle_event(&event);
882 assert_eq!(*event_handled.borrow(), true);
886 fn fails_paying_invoice_with_routing_errors() {
887 let payer = TestPayer::new();
888 let router = FailingRouter {};
889 let scorer = RefCell::new(TestScorer::new());
890 let logger = TestLogger::new();
892 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
894 let payment_preimage = PaymentPreimage([1; 32]);
895 let invoice = invoice(payment_preimage);
896 match invoice_payer.pay_invoice(&invoice) {
897 Err(PaymentError::Routing(_)) => {},
898 Err(_) => panic!("unexpected error"),
899 Ok(_) => panic!("expected routing error"),
904 fn fails_paying_invoice_with_sending_errors() {
905 let payer = TestPayer::new().fails_on_attempt(1);
906 let router = TestRouter {};
907 let scorer = RefCell::new(TestScorer::new());
908 let logger = TestLogger::new();
910 InvoicePayer::new(&payer, router, &scorer, &logger, |_: &_| {}, RetryAttempts(0));
912 let payment_preimage = PaymentPreimage([1; 32]);
913 let invoice = invoice(payment_preimage);
914 match invoice_payer.pay_invoice(&invoice) {
915 Err(PaymentError::Sending(_)) => {},
916 Err(_) => panic!("unexpected error"),
917 Ok(_) => panic!("expected sending error"),
922 fn pays_zero_value_invoice_using_amount() {
923 let event_handled = core::cell::RefCell::new(false);
924 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
926 let payment_preimage = PaymentPreimage([1; 32]);
927 let invoice = zero_value_invoice(payment_preimage);
928 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
929 let final_value_msat = 100;
931 let payer = TestPayer::new().expect_value_msat(final_value_msat);
932 let router = TestRouter {};
933 let scorer = RefCell::new(TestScorer::new());
934 let logger = TestLogger::new();
936 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
939 Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap());
940 assert_eq!(*payer.attempts.borrow(), 1);
942 invoice_payer.handle_event(&Event::PaymentSent {
943 payment_id, payment_preimage, payment_hash, fee_paid_msat: None
945 assert_eq!(*event_handled.borrow(), true);
946 assert_eq!(*payer.attempts.borrow(), 1);
950 fn fails_paying_zero_value_invoice_with_amount() {
951 let event_handled = core::cell::RefCell::new(false);
952 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
954 let payer = TestPayer::new();
955 let router = TestRouter {};
956 let scorer = RefCell::new(TestScorer::new());
957 let logger = TestLogger::new();
959 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(0));
961 let payment_preimage = PaymentPreimage([1; 32]);
962 let invoice = invoice(payment_preimage);
964 // Cannot repay an invoice pending payment.
965 match invoice_payer.pay_zero_value_invoice(&invoice, 100) {
966 Err(PaymentError::Invoice("amount unexpected")) => {},
967 Err(_) => panic!("unexpected error"),
968 Ok(_) => panic!("expected invoice error"),
973 fn scores_failed_channel() {
974 let event_handled = core::cell::RefCell::new(false);
975 let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
977 let payment_preimage = PaymentPreimage([1; 32]);
978 let invoice = invoice(payment_preimage);
979 let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner());
980 let final_value_msat = invoice.amount_milli_satoshis().unwrap();
981 let path = TestRouter::path_for_value(final_value_msat);
982 let short_channel_id = Some(path[0].short_channel_id);
984 // Expect that scorer is given short_channel_id upon handling the event.
985 let payer = TestPayer::new();
986 let router = TestRouter {};
987 let scorer = RefCell::new(TestScorer::new().expect_channel_failure(short_channel_id.unwrap()));
988 let logger = TestLogger::new();
990 InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2));
992 let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap());
993 let event = Event::PaymentPathFailed {
996 network_update: None,
997 rejected_by_dest: false,
998 all_paths_failed: false,
1001 retry: Some(TestRouter::retry_for_invoice(&invoice)),
1003 invoice_payer.handle_event(&event);
1009 fn route_for_value(final_value_msat: u64) -> Route {
1013 pubkey: PublicKey::from_slice(&hex::decode("02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619").unwrap()[..]).unwrap(),
1014 channel_features: ChannelFeatures::empty(),
1015 node_features: NodeFeatures::empty(),
1016 short_channel_id: 0, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1019 pubkey: PublicKey::from_slice(&hex::decode("0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c").unwrap()[..]).unwrap(),
1020 channel_features: ChannelFeatures::empty(),
1021 node_features: NodeFeatures::empty(),
1022 short_channel_id: 1, fee_msat: final_value_msat / 2, cltv_expiry_delta: 144
1029 fn path_for_value(final_value_msat: u64) -> Vec<RouteHop> {
1030 TestRouter::route_for_value(final_value_msat).paths[0].clone()
1033 fn retry_for_invoice(invoice: &Invoice) -> RouteParameters {
1034 let mut payee = Payee::from_node_id(invoice.recover_payee_pub_key())
1035 .with_expiry_time(expiry_time_from_unix_epoch(invoice).as_secs())
1036 .with_route_hints(invoice.route_hints());
1037 if let Some(features) = invoice.features() {
1038 payee = payee.with_features(features.clone());
1040 let final_value_msat = invoice.amount_milli_satoshis().unwrap() / 2;
1044 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1049 impl<S: routing::Score> Router<S> for TestRouter {
1053 params: &RouteParameters,
1054 _first_hops: Option<&[&ChannelDetails]>,
1056 ) -> Result<Route, LightningError> {
1058 payee: Some(params.payee.clone()), ..Self::route_for_value(params.final_value_msat)
1063 struct FailingRouter;
1065 impl<S: routing::Score> Router<S> for FailingRouter {
1069 _params: &RouteParameters,
1070 _first_hops: Option<&[&ChannelDetails]>,
1072 ) -> Result<Route, LightningError> {
1073 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError })
1078 expectations: VecDeque<u64>,
1084 expectations: VecDeque::new(),
1088 fn expect_channel_failure(mut self, short_channel_id: u64) -> Self {
1089 self.expectations.push_back(short_channel_id);
1094 impl routing::Score for TestScorer {
1095 fn channel_penalty_msat(
1096 &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId
1099 fn payment_path_failed(&mut self, _path: &[&RouteHop], short_channel_id: u64) {
1100 if let Some(expected_short_channel_id) = self.expectations.pop_front() {
1101 assert_eq!(short_channel_id, expected_short_channel_id);
1106 impl Drop for TestScorer {
1107 fn drop(&mut self) {
1108 if std::thread::panicking() {
1112 if !self.expectations.is_empty() {
1113 panic!("Unsatisfied channel failure expectations: {:?}", self.expectations);
1119 expectations: core::cell::RefCell<VecDeque<u64>>,
1120 attempts: core::cell::RefCell<usize>,
1121 failing_on_attempt: Option<usize>,
1127 expectations: core::cell::RefCell::new(VecDeque::new()),
1128 attempts: core::cell::RefCell::new(0),
1129 failing_on_attempt: None,
1133 fn expect_value_msat(self, value_msat: u64) -> Self {
1134 self.expectations.borrow_mut().push_back(value_msat);
1138 fn fails_on_attempt(self, attempt: usize) -> Self {
1140 expectations: core::cell::RefCell::new(self.expectations.borrow().clone()),
1141 attempts: core::cell::RefCell::new(0),
1142 failing_on_attempt: Some(attempt),
1146 fn check_attempts(&self) -> bool {
1147 let mut attempts = self.attempts.borrow_mut();
1149 match self.failing_on_attempt {
1151 Some(attempt) if attempt != *attempts => true,
1156 fn check_value_msats(&self, route: &Route) {
1157 let expected_value_msats = self.expectations.borrow_mut().pop_front();
1158 if let Some(expected_value_msats) = expected_value_msats {
1159 let actual_value_msats = route.get_total_amount();
1160 assert_eq!(actual_value_msats, expected_value_msats);
1165 impl Drop for TestPayer {
1166 fn drop(&mut self) {
1167 if std::thread::panicking() {
1171 if !self.expectations.borrow().is_empty() {
1172 panic!("Unsatisfied payment expectations: {:?}", self.expectations.borrow());
1177 impl Payer for TestPayer {
1178 fn node_id(&self) -> PublicKey {
1179 let secp_ctx = Secp256k1::new();
1180 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap())
1183 fn first_hops(&self) -> Vec<ChannelDetails> {
1190 _payment_hash: PaymentHash,
1191 _payment_secret: &Option<PaymentSecret>
1192 ) -> Result<PaymentId, PaymentSendFailure> {
1193 if self.check_attempts() {
1194 self.check_value_msats(route);
1195 Ok(PaymentId([1; 32]))
1197 Err(PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed))
1202 &self, route: &Route, _payment_id: PaymentId
1203 ) -> Result<(), PaymentSendFailure> {
1204 if self.check_attempts() {
1205 self.check_value_msats(route);
1208 Err(PaymentSendFailure::ParameterError(APIError::MonitorUpdateFailed))
1213 // *** Full Featured Functional Tests with a Real ChannelManager ***
1214 struct ManualRouter(RefCell<VecDeque<Result<Route, LightningError>>>);
1216 impl<S: routing::Score> Router<S> for ManualRouter {
1217 fn find_route(&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, _scorer: &S)
1218 -> Result<Route, LightningError> {
1219 self.0.borrow_mut().pop_front().unwrap()
1223 fn expect_find_route(&self, result: Result<Route, LightningError>) {
1224 self.0.borrow_mut().push_back(result);
1227 impl Drop for ManualRouter {
1228 fn drop(&mut self) {
1229 if std::thread::panicking() {
1232 assert!(self.0.borrow_mut().is_empty());
1237 fn retry_multi_path_single_failed_payment() {
1238 // Tests that we can/will retry after a single path of an MPP payment failed immediately
1239 let chanmon_cfgs = create_chanmon_cfgs(2);
1240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1242 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1244 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1245 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1246 let chans = nodes[0].node.list_usable_channels();
1247 let mut route = Route {
1250 pubkey: nodes[1].node.get_our_node_id(),
1251 node_features: NodeFeatures::known(),
1252 short_channel_id: chans[0].short_channel_id.unwrap(),
1253 channel_features: ChannelFeatures::known(),
1255 cltv_expiry_delta: 100,
1258 pubkey: nodes[1].node.get_our_node_id(),
1259 node_features: NodeFeatures::known(),
1260 short_channel_id: chans[1].short_channel_id.unwrap(),
1261 channel_features: ChannelFeatures::known(),
1262 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1263 cltv_expiry_delta: 100,
1266 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1268 let router = ManualRouter(RefCell::new(VecDeque::new()));
1269 router.expect_find_route(Ok(route.clone()));
1270 // On retry, split the payment across both channels.
1271 route.paths[0][0].fee_msat = 50_000_001;
1272 route.paths[1][0].fee_msat = 50_000_000;
1273 router.expect_find_route(Ok(route.clone()));
1275 let event_handler = |_: &_| { panic!(); };
1276 let scorer = RefCell::new(TestScorer::new());
1277 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1279 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1280 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1282 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1283 assert_eq!(htlc_msgs.len(), 2);
1284 check_added_monitors!(nodes[0], 2);
1288 fn immediate_retry_on_failure() {
1289 // Tests that we can/will retry immediately after a failure
1290 let chanmon_cfgs = create_chanmon_cfgs(2);
1291 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1292 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1293 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1295 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1296 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1297 let chans = nodes[0].node.list_usable_channels();
1298 let mut route = Route {
1301 pubkey: nodes[1].node.get_our_node_id(),
1302 node_features: NodeFeatures::known(),
1303 short_channel_id: chans[0].short_channel_id.unwrap(),
1304 channel_features: ChannelFeatures::known(),
1305 fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than
1306 cltv_expiry_delta: 100,
1309 payee: Some(Payee::from_node_id(nodes[1].node.get_our_node_id())),
1311 let router = ManualRouter(RefCell::new(VecDeque::new()));
1312 router.expect_find_route(Ok(route.clone()));
1313 // On retry, split the payment across both channels.
1314 route.paths.push(route.paths[0].clone());
1315 route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap();
1316 route.paths[0][0].fee_msat = 50_000_000;
1317 route.paths[1][0].fee_msat = 50_000_001;
1318 router.expect_find_route(Ok(route.clone()));
1320 let event_handler = |_: &_| { panic!(); };
1321 let scorer = RefCell::new(TestScorer::new());
1322 let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1));
1324 assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager(
1325 &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap())
1327 let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events();
1328 assert_eq!(htlc_msgs.len(), 2);
1329 check_added_monitors!(nodes[0], 2);