From 16f742833e66881f05a0573121d74a15866ebf6b Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Tue, 26 Oct 2021 21:38:46 +0000 Subject: [PATCH 1/8] Move PaymentId to a [u8; 32] in bindings as for other hash objects This should allow us to fix https://github.com/lightningdevkit/ldk-garbagecollected/issues/52 --- lightning/src/ln/channelmanager.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 698ef1a975a..53d332be01c 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -173,6 +173,7 @@ struct ClaimableHTLC { } /// A payment identifier used to uniquely identify a payment to LDK. +/// (C-not exported) as we just use [u8; 32] directly #[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)] pub struct PaymentId(pub [u8; 32]); From d73e43428028b691453b0d5fe5e8608e4e9b1190 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Tue, 26 Oct 2021 21:39:31 +0000 Subject: [PATCH 2/8] Provide payment retry data when an MPP payment failed partially This will allow `InvoicePayer` to properly retry payments that only partially failed to send. --- fuzz/src/chanmon_consistency.rs | 4 +-- lightning/src/ln/chanmon_update_fail_tests.rs | 2 +- lightning/src/ln/channelmanager.rs | 33 ++++++++++++++++--- lightning/src/ln/functional_test_utils.rs | 6 ++-- 4 files changed, 35 insertions(+), 10 deletions(-) diff --git a/fuzz/src/chanmon_consistency.rs b/fuzz/src/chanmon_consistency.rs index 464e784d514..acdf3cb3ca2 100644 --- a/fuzz/src/chanmon_consistency.rs +++ b/fuzz/src/chanmon_consistency.rs @@ -271,8 +271,8 @@ fn check_payment_err(send_err: PaymentSendFailure) { PaymentSendFailure::AllFailedRetrySafe(per_path_results) => { for api_err in per_path_results { check_api_err(api_err); } }, - PaymentSendFailure::PartialFailure(per_path_results) => { - for res in per_path_results { if let Err(api_err) = res { check_api_err(api_err); } } + PaymentSendFailure::PartialFailure { results, .. } => { + for res in results { if let Err(api_err) = res { check_api_err(api_err); } } }, } } diff --git a/lightning/src/ln/chanmon_update_fail_tests.rs b/lightning/src/ln/chanmon_update_fail_tests.rs index feefd8c18f1..0ae3ff29d87 100644 --- a/lightning/src/ln/chanmon_update_fail_tests.rs +++ b/lightning/src/ln/chanmon_update_fail_tests.rs @@ -1950,7 +1950,7 @@ fn test_path_paused_mpp() { // Now check that we get the right return value, indicating that the first path succeeded but // the second got a MonitorUpdateFailed err. This implies PaymentSendFailure::PartialFailure as // some paths succeeded, preventing retry. - if let Err(PaymentSendFailure::PartialFailure(results)) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { + if let Err(PaymentSendFailure::PartialFailure { results, ..}) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { assert_eq!(results.len(), 2); if let Ok(()) = results[0] {} else { panic!(); } if let Err(APIError::MonitorUpdateFailed) = results[1] {} else { panic!(); } diff --git a/lightning/src/ln/channelmanager.rs b/lightning/src/ln/channelmanager.rs index 53d332be01c..cdde8bd8532 100644 --- a/lightning/src/ln/channelmanager.rs +++ b/lightning/src/ln/channelmanager.rs @@ -946,7 +946,16 @@ pub enum PaymentSendFailure { /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel /// with the latest update_id. - PartialFailure(Vec>), + PartialFailure { + /// The errors themselves, in the same order as the route hops. + results: Vec>, + /// If some paths failed without irrevocably committing to the new HTLC(s), this will + /// contain a [`RouteParameters`] object which can be used to calculate a new route that + /// will pay all remaining unpaid balance. + failed_paths_retry: Option, + /// The payment id for the payment, which is now at least partially pending. + payment_id: PaymentId, + }, } macro_rules! handle_error { @@ -2236,7 +2245,9 @@ impl ChannelMana } let mut has_ok = false; let mut has_err = false; - for res in results.iter() { + let mut pending_amt_unsent = 0; + let mut max_unsent_cltv_delta = 0; + for (res, path) in results.iter().zip(route.paths.iter()) { if res.is_ok() { has_ok = true; } if res.is_err() { has_err = true; } if let &Err(APIError::MonitorUpdateFailed) = res { @@ -2244,11 +2255,25 @@ impl ChannelMana // PartialFailure. has_err = true; has_ok = true; - break; + } else if res.is_err() { + pending_amt_unsent += path.last().unwrap().fee_msat; + max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta); } } if has_err && has_ok { - Err(PaymentSendFailure::PartialFailure(results)) + Err(PaymentSendFailure::PartialFailure { + results, + payment_id, + failed_paths_retry: if pending_amt_unsent != 0 { + if let Some(payee) = &route.payee { + Some(RouteParameters { + payee: payee.clone(), + final_value_msat: pending_amt_unsent, + final_cltv_expiry_delta: max_unsent_cltv_delta, + }) + } else { None } + } else { None }, + }) } else if has_err { Err(PaymentSendFailure::AllFailedRetrySafe(results.drain(..).map(|r| r.unwrap_err()).collect())) } else { diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index bcb1ac1f1ad..14bc6beec5f 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -482,9 +482,9 @@ macro_rules! unwrap_send_err { _ => panic!(), } }, - &Err(PaymentSendFailure::PartialFailure(ref fails)) if !$all_failed => { - assert_eq!(fails.len(), 1); - match fails[0] { + &Err(PaymentSendFailure::PartialFailure { ref results, .. }) if !$all_failed => { + assert_eq!(results.len(), 1); + match results[0] { Err($type) => { $check }, _ => panic!(), } From 51dd344f26ca31d114fd06608eef4f8e6b6f8b57 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Sat, 30 Oct 2021 01:52:43 +0000 Subject: [PATCH 3/8] Expand `InvoicePayer` documentation somewhat to clarify edge-cases --- lightning-invoice/src/payment.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index eefae3fc1a6..68b06faa0ec 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -175,6 +175,10 @@ pub trait Router { } /// Number of attempts to retry payment path failures for an [`Invoice`]. +/// +/// Note that this is the number of *path* failures, not full payment retries. For multi-path +/// payments, if this is less than the total number of paths, we will never even retry all of the +/// payment's paths. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub struct RetryAttempts(pub usize); @@ -216,6 +220,10 @@ where } /// Pays the given [`Invoice`], caching it for later use in case a retry is needed. + /// + /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has + /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so + /// for you. pub fn pay_invoice(&self, invoice: &Invoice) -> Result { if invoice.amount_milli_satoshis().is_none() { Err(PaymentError::Invoice("amount missing")) @@ -226,6 +234,10 @@ where /// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in /// case a retry is needed. + /// + /// You should ensure that the `invoice.payment_hash()` is unique and the same payment_hash has + /// never been paid before. Because [`InvoicePayer`] is stateless no effort is made to do so + /// for you. pub fn pay_zero_value_invoice( &self, invoice: &Invoice, amount_msats: u64 ) -> Result { From e9e8a7d58d3fd415ad1746b3fee5f332c78d72e9 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 27 Oct 2021 22:12:07 +0000 Subject: [PATCH 4/8] Dont unwrap `RouteParameter::expiry_time` as users can set it Users can provide anything they want as `RouteParameters` so we shouldn't assume any fields are set any particular way, including `expiry_time` set at all. --- lightning-invoice/src/payment.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index 68b06faa0ec..b706deaddd2 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -313,8 +313,9 @@ fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration { } fn has_expired(params: &RouteParameters) -> bool { - let expiry_time = Duration::from_secs(params.payee.expiry_time.unwrap()); - Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, expiry_time) + if let Some(expiry_time) = params.payee.expiry_time { + Invoice::is_expired_from_epoch(&SystemTime::UNIX_EPOCH, Duration::from_secs(expiry_time)) + } else { false } } impl EventHandler for InvoicePayer From 7112661b109b79cdb8e174fdd3ab73c05386212c Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Tue, 26 Oct 2021 22:52:06 +0000 Subject: [PATCH 5/8] Rewrite InvoicePayer retry to correctly handle MPP partial failures This rewrites a good chunk of the retry logic in `InvoicePayer` to address two issues: * it was not considering the return value of `send_payment` (and `retry_payment`) may indicate a failure on some paths but not others, * it was not considering that more failures may still come later when removing elements from the retry count map. This could result in us seeing an MPP-partial-failure, failing to retry, removing the retries count entry, and then retrying other parts, potentially forever. --- lightning-invoice/src/payment.rs | 208 ++++++++++++++++++++----------- 1 file changed, 132 insertions(+), 76 deletions(-) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index b706deaddd2..3ca9262164c 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -228,7 +228,7 @@ where if invoice.amount_milli_satoshis().is_none() { Err(PaymentError::Invoice("amount missing")) } else { - self.pay_invoice_internal(invoice, None) + self.pay_invoice_internal(invoice, None, 0) } } @@ -244,59 +244,138 @@ where if invoice.amount_milli_satoshis().is_some() { Err(PaymentError::Invoice("amount unexpected")) } else { - self.pay_invoice_internal(invoice, Some(amount_msats)) + self.pay_invoice_internal(invoice, Some(amount_msats), 0) } } fn pay_invoice_internal( - &self, invoice: &Invoice, amount_msats: Option + &self, invoice: &Invoice, amount_msats: Option, retry_count: usize ) -> Result { debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some()); let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner()); - let mut payment_cache = self.payment_cache.lock().unwrap(); - match payment_cache.entry(payment_hash) { - hash_map::Entry::Vacant(entry) => { - let payer = self.payer.node_id(); - let mut payee = Payee::new(invoice.recover_payee_pub_key()) - .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs()) - .with_route_hints(invoice.route_hints()); - if let Some(features) = invoice.features() { - payee = payee.with_features(features.clone()); - } - let params = RouteParameters { - payee, - final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(), - final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32, + let retry_data_payment_id = loop { + let mut payment_cache = self.payment_cache.lock().unwrap(); + match payment_cache.entry(payment_hash) { + hash_map::Entry::Vacant(entry) => { + let payer = self.payer.node_id(); + let mut payee = Payee::new(invoice.recover_payee_pub_key()) + .with_expiry_time(expiry_time_from_unix_epoch(&invoice).as_secs()) + .with_route_hints(invoice.route_hints()); + if let Some(features) = invoice.features() { + payee = payee.with_features(features.clone()); + } + let params = RouteParameters { + payee, + final_value_msat: invoice.amount_milli_satoshis().or(amount_msats).unwrap(), + final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32, + }; + let first_hops = self.payer.first_hops(); + let route = self.router.find_route( + &payer, + ¶ms, + Some(&first_hops.iter().collect::>()), + &self.scorer.lock(), + ).map_err(|e| PaymentError::Routing(e))?; + + let payment_secret = Some(invoice.payment_secret().clone()); + let payment_id = match self.payer.send_payment(&route, payment_hash, &payment_secret) { + Ok(payment_id) => payment_id, + Err(PaymentSendFailure::ParameterError(e)) => + return Err(PaymentError::Sending(PaymentSendFailure::ParameterError(e))), + Err(PaymentSendFailure::PathParameterError(e)) => + return Err(PaymentError::Sending(PaymentSendFailure::PathParameterError(e))), + Err(PaymentSendFailure::AllFailedRetrySafe(e)) => { + if retry_count >= self.retry_attempts.0 { + return Err(PaymentError::Sending(PaymentSendFailure::AllFailedRetrySafe(e))) + } + break None; + }, + Err(PaymentSendFailure::PartialFailure { results: _, failed_paths_retry, payment_id }) => { + if let Some(retry_data) = failed_paths_retry { + entry.insert(retry_count); + break Some((retry_data, payment_id)); + } else { + // This may happen if we send a payment and some paths fail, but + // only due to a temporary monitor failure or the like, implying + // they're really in-flight, but we haven't sent the initial + // HTLC-Add messages yet. + payment_id + } + }, + }; + entry.insert(retry_count); + return Ok(payment_id); + }, + hash_map::Entry::Occupied(_) => return Err(PaymentError::Invoice("payment pending")), + } + }; + if let Some((retry_data, payment_id)) = retry_data_payment_id { + // Some paths were sent, even if we failed to send the full MPP value our recipient may + // misbehave and claim the funds, at which point we have to consider the payment sent, + // so return `Ok()` here, ignoring any retry errors. + let _ = self.retry_payment(payment_id, payment_hash, &retry_data); + Ok(payment_id) + } else { + self.pay_invoice_internal(invoice, amount_msats, retry_count + 1) + } + } + + fn retry_payment(&self, payment_id: PaymentId, payment_hash: PaymentHash, params: &RouteParameters) + -> Result<(), ()> { + let route; + { + let mut payment_cache = self.payment_cache.lock().unwrap(); + let entry = loop { + let entry = payment_cache.entry(payment_hash); + match entry { + hash_map::Entry::Occupied(_) => break entry, + hash_map::Entry::Vacant(entry) => entry.insert(0), }; + }; + if let hash_map::Entry::Occupied(mut entry) = entry { + let max_payment_attempts = self.retry_attempts.0 + 1; + let attempts = entry.get_mut(); + *attempts += 1; + + if *attempts >= max_payment_attempts { + log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); + return Err(()); + } else if has_expired(params) { + log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); + return Err(()); + } + + let payer = self.payer.node_id(); let first_hops = self.payer.first_hops(); - let route = self.router.find_route( - &payer, - ¶ms, - Some(&first_hops.iter().collect::>()), - &self.scorer.lock(), - ).map_err(|e| PaymentError::Routing(e))?; - - let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner()); - let payment_secret = Some(invoice.payment_secret().clone()); - let payment_id = self.payer.send_payment(&route, payment_hash, &payment_secret) - .map_err(|e| PaymentError::Sending(e))?; - entry.insert(0); - Ok(payment_id) - }, - hash_map::Entry::Occupied(_) => Err(PaymentError::Invoice("payment pending")), + route = self.router.find_route(&payer, ¶ms, Some(&first_hops.iter().collect::>()), &self.scorer.lock()); + if route.is_err() { + log_trace!(self.logger, "Failed to find a route for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); + return Err(()); + } + } else { + unreachable!(); + } } - } - fn retry_payment( - &self, payment_id: PaymentId, params: &RouteParameters - ) -> Result<(), PaymentError> { - let payer = self.payer.node_id(); - let first_hops = self.payer.first_hops(); - let route = self.router.find_route( - &payer, ¶ms, Some(&first_hops.iter().collect::>()), - &self.scorer.lock() - ).map_err(|e| PaymentError::Routing(e))?; - self.payer.retry_payment(&route, payment_id).map_err(|e| PaymentError::Sending(e)) + let retry_res = self.payer.retry_payment(&route.unwrap(), payment_id); + match retry_res { + Ok(()) => Ok(()), + Err(PaymentSendFailure::ParameterError(_)) | + Err(PaymentSendFailure::PathParameterError(_)) => { + log_trace!(self.logger, "Failed to retry for payment {} due to bogus route/payment data, not retrying.", log_bytes!(payment_hash.0)); + return Err(()); + }, + Err(PaymentSendFailure::AllFailedRetrySafe(_)) => { + self.retry_payment(payment_id, payment_hash, params) + }, + Err(PaymentSendFailure::PartialFailure { results: _, failed_paths_retry, .. }) => { + if let Some(retry) = failed_paths_retry { + self.retry_payment(payment_id, payment_hash, &retry) + } else { + Ok(()) + } + }, + } } /// Removes the payment cached by the given payment hash. @@ -329,48 +408,25 @@ where fn handle_event(&self, event: &Event) { match event { Event::PaymentPathFailed { - payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, .. + all_paths_failed, payment_id, payment_hash, rejected_by_dest, path, short_channel_id, retry, .. } => { if let Some(short_channel_id) = short_channel_id { self.scorer.lock().payment_path_failed(path, *short_channel_id); } - let mut payment_cache = self.payment_cache.lock().unwrap(); - let entry = loop { - let entry = payment_cache.entry(*payment_hash); - match entry { - hash_map::Entry::Occupied(_) => break entry, - hash_map::Entry::Vacant(entry) => entry.insert(0), - }; - }; - if let hash_map::Entry::Occupied(mut entry) = entry { - let max_payment_attempts = self.retry_attempts.0 + 1; - let attempts = entry.get_mut(); - *attempts += 1; - - if *rejected_by_dest { - log_trace!(self.logger, "Payment {} rejected by destination; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else if payment_id.is_none() { - log_trace!(self.logger, "Payment {} has no id; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else if *attempts >= max_payment_attempts { - log_trace!(self.logger, "Payment {} exceeded maximum attempts; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else if retry.is_none() { - log_trace!(self.logger, "Payment {} missing retry params; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else if has_expired(retry.as_ref().unwrap()) { - log_trace!(self.logger, "Invoice expired for payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else if self.retry_payment(*payment_id.as_ref().unwrap(), retry.as_ref().unwrap()).is_err() { - log_trace!(self.logger, "Error retrying payment {}; not retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); - } else { - log_trace!(self.logger, "Payment {} failed; retrying (attempts: {})", log_bytes!(payment_hash.0), attempts); + if *rejected_by_dest { + log_trace!(self.logger, "Payment {} rejected by destination; not retrying", log_bytes!(payment_hash.0)); + } else if payment_id.is_none() { + log_trace!(self.logger, "Payment {} has no id; not retrying", log_bytes!(payment_hash.0)); + } else if let Some(params) = retry { + if self.retry_payment(payment_id.unwrap(), *payment_hash, params).is_ok() { + // We retried at least somewhat, don't provide the PaymentPathFailed event to the user. return; } - - // Either the payment was rejected, the maximum attempts were exceeded, or an - // error occurred when attempting to retry. - entry.remove(); } else { - unreachable!(); + log_trace!(self.logger, "Payment {} missing retry params; not retrying", log_bytes!(payment_hash.0)); } + if *all_paths_failed { self.payment_cache.lock().unwrap().remove(payment_hash); } }, Event::PaymentSent { payment_hash, .. } => { let mut payment_cache = self.payment_cache.lock().unwrap(); From 2b8c287be96c19dfc9d77d892eebc38b90db9849 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 27 Oct 2021 22:15:11 +0000 Subject: [PATCH 6/8] Add an integration test for InvoicePayer paying when one part fails This tests the multi-part-single-failure-immediately fixes in the previous commit. --- lightning-invoice/src/payment.rs | 89 +++++++++++++++++++++++++++++--- 1 file changed, 83 insertions(+), 6 deletions(-) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index 3ca9262164c..028711a630e 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -447,17 +447,20 @@ where mod tests { use super::*; use crate::{DEFAULT_EXPIRY_TIME, InvoiceBuilder, Currency}; + use utils::create_invoice_from_channelmanager; use bitcoin_hashes::sha256::Hash as Sha256; use lightning::ln::PaymentPreimage; - use lightning::ln::features::{ChannelFeatures, NodeFeatures}; + use lightning::ln::features::{ChannelFeatures, NodeFeatures, InitFeatures}; + use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::{ErrorAction, LightningError}; use lightning::routing::network_graph::NodeId; use lightning::routing::router::{Payee, Route, RouteHop}; use lightning::util::test_utils::TestLogger; use lightning::util::errors::APIError; - use lightning::util::events::Event; + use lightning::util::events::{Event, MessageSendEventsProvider}; use secp256k1::{SecretKey, PublicKey, Secp256k1}; use std::cell::RefCell; + use std::collections::VecDeque; use std::time::{SystemTime, Duration}; fn invoice(payment_preimage: PaymentPreimage) -> Invoice { @@ -1048,13 +1051,13 @@ mod tests { } struct TestScorer { - expectations: std::collections::VecDeque, + expectations: VecDeque, } impl TestScorer { fn new() -> Self { Self { - expectations: std::collections::VecDeque::new(), + expectations: VecDeque::new(), } } @@ -1089,7 +1092,7 @@ mod tests { } struct TestPayer { - expectations: core::cell::RefCell>, + expectations: core::cell::RefCell>, attempts: core::cell::RefCell, failing_on_attempt: Option, } @@ -1097,7 +1100,7 @@ mod tests { impl TestPayer { fn new() -> Self { Self { - expectations: core::cell::RefCell::new(std::collections::VecDeque::new()), + expectations: core::cell::RefCell::new(VecDeque::new()), attempts: core::cell::RefCell::new(0), failing_on_attempt: None, } @@ -1182,4 +1185,78 @@ mod tests { } } } + + // *** Full Featured Functional Tests with a Real ChannelManager *** + struct ManualRouter(RefCell>>); + + impl Router for ManualRouter { + fn find_route(&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, _scorer: &S) + -> Result { + self.0.borrow_mut().pop_front().unwrap() + } + } + impl ManualRouter { + fn expect_find_route(&self, result: Result) { + self.0.borrow_mut().push_back(result); + } + } + impl Drop for ManualRouter { + fn drop(&mut self) { + if std::thread::panicking() { + return; + } + assert!(self.0.borrow_mut().is_empty()); + } + } + + #[test] + fn retry_multi_path_single_failed_payment() { + // Tests that we can/will retry after a single path of an MPP payment failed immediately + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known()); + create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known()); + let chans = nodes[0].node.list_usable_channels(); + let mut route = Route { + paths: vec![ + vec![RouteHop { + pubkey: nodes[1].node.get_our_node_id(), + node_features: NodeFeatures::known(), + short_channel_id: chans[0].short_channel_id.unwrap(), + channel_features: ChannelFeatures::known(), + fee_msat: 10_000, + cltv_expiry_delta: 100, + }], + vec![RouteHop { + pubkey: nodes[1].node.get_our_node_id(), + node_features: NodeFeatures::known(), + short_channel_id: chans[1].short_channel_id.unwrap(), + channel_features: ChannelFeatures::known(), + fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than + cltv_expiry_delta: 100, + }], + ], + payee: Some(Payee::new(nodes[1].node.get_our_node_id())), + }; + let router = ManualRouter(RefCell::new(VecDeque::new())); + router.expect_find_route(Ok(route.clone())); + // On retry, split the payment across both channels. + route.paths[0][0].fee_msat = 50_000_001; + route.paths[1][0].fee_msat = 50_000_000; + router.expect_find_route(Ok(route.clone())); + + let event_handler = |_: &_| { panic!(); }; + let scorer = RefCell::new(TestScorer::new()); + let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1)); + + assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager( + &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap()) + .is_ok()); + let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(htlc_msgs.len(), 2); + check_added_monitors!(nodes[0], 2); + } } From 9c5dccd79d80179cb623ea3e244206a8b3e8b39f Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 27 Oct 2021 22:22:48 +0000 Subject: [PATCH 7/8] Add integration test for InvoicePayerretry on an immediate failure --- lightning-invoice/src/payment.rs | 45 ++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index 028711a630e..f75464689ec 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -1259,4 +1259,49 @@ mod tests { assert_eq!(htlc_msgs.len(), 2); check_added_monitors!(nodes[0], 2); } + + #[test] + fn immediate_retry_on_failure() { + // Tests that we can/will retry immediately after a failure + let chanmon_cfgs = create_chanmon_cfgs(2); + let node_cfgs = create_node_cfgs(2, &chanmon_cfgs); + let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]); + let nodes = create_network(2, &node_cfgs, &node_chanmgrs); + + create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known()); + create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known()); + let chans = nodes[0].node.list_usable_channels(); + let mut route = Route { + paths: vec![ + vec![RouteHop { + pubkey: nodes[1].node.get_our_node_id(), + node_features: NodeFeatures::known(), + short_channel_id: chans[0].short_channel_id.unwrap(), + channel_features: ChannelFeatures::known(), + fee_msat: 100_000_001, // Our default max-HTLC-value is 10% of the channel value, which this is one more than + cltv_expiry_delta: 100, + }], + ], + payee: Some(Payee::new(nodes[1].node.get_our_node_id())), + }; + let router = ManualRouter(RefCell::new(VecDeque::new())); + router.expect_find_route(Ok(route.clone())); + // On retry, split the payment across both channels. + route.paths.push(route.paths[0].clone()); + route.paths[0][0].short_channel_id = chans[1].short_channel_id.unwrap(); + route.paths[0][0].fee_msat = 50_000_000; + route.paths[1][0].fee_msat = 50_000_001; + router.expect_find_route(Ok(route.clone())); + + let event_handler = |_: &_| { panic!(); }; + let scorer = RefCell::new(TestScorer::new()); + let invoice_payer = InvoicePayer::new(nodes[0].node, router, &scorer, nodes[0].logger, event_handler, RetryAttempts(1)); + + assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager( + &nodes[1].node, nodes[1].keys_manager, Currency::Bitcoin, Some(100_010_000), "Invoice".to_string()).unwrap()) + .is_ok()); + let htlc_msgs = nodes[0].node.get_and_clear_pending_msg_events(); + assert_eq!(htlc_msgs.len(), 2); + check_added_monitors!(nodes[0], 2); + } } From 199d258bb0f895fa7232a07bcd4387a10bf1e11f Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Thu, 28 Oct 2021 18:46:02 +0000 Subject: [PATCH 8/8] Check for invoice expiry in InvoicePayer before we send any HTLCs --- lightning-invoice/src/payment.rs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index f75464689ec..a5160ea9b69 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -253,6 +253,10 @@ where ) -> Result { debug_assert!(invoice.amount_milli_satoshis().is_some() ^ amount_msats.is_some()); let payment_hash = PaymentHash(invoice.payment_hash().clone().into_inner()); + if invoice.is_expired() { + log_trace!(self.logger, "Invoice expired prior to first send for payment {}", log_bytes!(payment_hash.0)); + return Err(PaymentError::Invoice("Invoice expired prior to send")); + } let retry_data_payment_id = loop { let mut payment_cache = self.payment_cache.lock().unwrap(); match payment_cache.entry(payment_hash) { @@ -728,9 +732,32 @@ mod tests { let payment_preimage = PaymentPreimage([1; 32]); let invoice = expired_invoice(payment_preimage); + if let PaymentError::Invoice(msg) = invoice_payer.pay_invoice(&invoice).unwrap_err() { + assert_eq!(msg, "Invoice expired prior to send"); + } else { panic!("Expected Invoice Error"); } + } + + #[test] + fn fails_retrying_invoice_after_expiration() { + let event_handled = core::cell::RefCell::new(false); + let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + + let payer = TestPayer::new(); + let router = TestRouter {}; + let scorer = RefCell::new(TestScorer::new()); + let logger = TestLogger::new(); + let invoice_payer = + InvoicePayer::new(&payer, router, &scorer, &logger, event_handler, RetryAttempts(2)); + + let payment_preimage = PaymentPreimage([1; 32]); + let invoice = invoice(payment_preimage); let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap()); assert_eq!(*payer.attempts.borrow(), 1); + let mut retry_data = TestRouter::retry_for_invoice(&invoice); + retry_data.payee.expiry_time = Some(SystemTime::now() + .checked_sub(Duration::from_secs(2)).unwrap() + .duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs()); let event = Event::PaymentPathFailed { payment_id, payment_hash: PaymentHash(invoice.payment_hash().clone().into_inner()), @@ -739,7 +766,7 @@ mod tests { all_paths_failed: false, path: vec![], short_channel_id: None, - retry: Some(TestRouter::retry_for_invoice(&invoice)), + retry: Some(retry_data), }; invoice_payer.handle_event(&event); assert_eq!(*event_handled.borrow(), true);