use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
-use crate::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA as LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA;
-use crate::ln::msgs::DecodeError;
use crate::ln::onion_utils::HTLCFailReason;
use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
use crate::util::errors::APIError;
use crate::util::time::Time;
#[cfg(all(not(feature = "no-std"), test))]
use crate::util::time::tests::SinceEpoch;
+use crate::util::ser::ReadableArgs;
use core::cmp;
use core::fmt::{self, Display, Formatter};
payment_hash: Option<PaymentHash>,
timer_ticks_without_htlcs: u8,
},
- /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
- /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
- /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
- /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
- /// downstream event handler as to when a payment has actually failed.
- ///
- /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
+ /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
+ /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
Abandoned {
session_privs: HashSet<[u8; 32]>,
payment_hash: PaymentHash,
/// were retried along a route from a single call to [`Router::find_route`].
Attempts(usize),
#[cfg(not(feature = "no-std"))]
- /// Time elapsed before abandoning retries for a payment.
+ /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
+ /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
+ ///
+ /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
Timeout(core::time::Duration),
}
/// it means the result of the first attempt is not known yet.
pub(crate) count: usize,
/// This field is only used when retry is `Retry::Timeout` which is only build with feature std
- first_attempted_at: T
+ #[cfg(not(feature = "no-std"))]
+ first_attempted_at: T,
+ #[cfg(feature = "no-std")]
+ phantom: core::marker::PhantomData<T>,
+
}
#[cfg(not(any(feature = "no-std", test)))]
pub(crate) fn new() -> Self {
PaymentAttemptsUsingTime {
count: 0,
- first_attempted_at: T::now()
+ #[cfg(not(feature = "no-std"))]
+ first_attempted_at: T::now(),
+ #[cfg(feature = "no-std")]
+ phantom: core::marker::PhantomData,
}
}
}
let mut retry_id_route_params = None;
for (pmt_id, pmt) in outbounds.iter_mut() {
if pmt.is_auto_retryable_now() {
- if let PendingOutboundPayment::Retryable { payment_hash, pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
+ if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
if pending_amt_msat < total_msat {
- retry_id_route_params = Some((*pmt_id, *payment_hash, RouteParameters {
+ retry_id_route_params = Some((*pmt_id, RouteParameters {
final_value_msat: *total_msat - *pending_amt_msat,
- final_cltv_expiry_delta:
- if let Some(delta) = params.final_cltv_expiry_delta { delta }
- else {
- debug_assert!(false, "We always set the final_cltv_expiry_delta when a path fails");
- LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA.into()
- },
payment_params: params.clone(),
}));
break
}
}
core::mem::drop(outbounds);
- if let Some((payment_id, payment_hash, route_params)) = retry_id_route_params {
- self.retry_payment_internal(payment_id, payment_hash, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
+ if let Some((payment_id, route_params)) = retry_id_route_params {
+ self.retry_payment_internal(payment_id, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
} else { break }
}
}
fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
- &self, payment_id: PaymentId, payment_hash: PaymentHash, route_params: RouteParameters,
- router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
- node_signer: &NS, best_block_height: u32, logger: &L,
- pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
+ &self, payment_id: PaymentId, route_params: RouteParameters, router: &R,
+ first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS,
+ best_block_height: u32, logger: &L, pending_events: &Mutex<Vec<events::Event>>,
+ send_payment_along_path: &SP,
)
where
R::Target: Router,
return
}
};
+ for path in route.paths.iter() {
+ if path.len() == 0 {
+ log_error!(logger, "length-0 path in route");
+ self.abandon_payment(payment_id, pending_events);
+ return
+ }
+ }
+
+ const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
+ let mut onion_session_privs = Vec::with_capacity(route.paths.len());
+ for _ in 0..route.paths.len() {
+ onion_session_privs.push(entropy_source.get_secure_random_bytes());
+ }
- let res = self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer,
- best_block_height, send_payment_along_path);
+ macro_rules! abandon_with_entry {
+ ($payment_id: expr, $payment_hash: expr, $payment: expr, $pending_events: expr) => {
+ if $payment.get_mut().mark_abandoned().is_ok() && $payment.get().remaining_parts() == 0 {
+ $pending_events.lock().unwrap().push(events::Event::PaymentFailed {
+ payment_id: $payment_id,
+ payment_hash: $payment_hash,
+ });
+ $payment.remove();
+ }
+ }
+ }
+ let (total_msat, payment_hash, payment_secret, keysend_preimage) = {
+ let mut outbounds = self.pending_outbound_payments.lock().unwrap();
+ match outbounds.entry(payment_id) {
+ hash_map::Entry::Occupied(mut payment) => {
+ let res = match payment.get() {
+ PendingOutboundPayment::Retryable {
+ total_msat, payment_hash, keysend_preimage, payment_secret, pending_amt_msat, ..
+ } => {
+ let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
+ if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
+ log_error!(logger, "retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat);
+ let payment_hash = *payment_hash;
+ abandon_with_entry!(payment_id, payment_hash, payment, pending_events);
+ return
+ }
+ (*total_msat, *payment_hash, *payment_secret, *keysend_preimage)
+ },
+ PendingOutboundPayment::Legacy { .. } => {
+ log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
+ return
+ },
+ PendingOutboundPayment::Fulfilled { .. } => {
+ log_error!(logger, "Payment already completed");
+ return
+ },
+ PendingOutboundPayment::Abandoned { .. } => {
+ log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
+ return
+ },
+ };
+ if !payment.get().is_retryable_now() {
+ log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
+ abandon_with_entry!(payment_id, res.1, payment, pending_events);
+ return
+ }
+ payment.get_mut().increment_attempts();
+ for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
+ assert!(payment.get_mut().insert(*session_priv_bytes, path));
+ }
+ res
+ },
+ hash_map::Entry::Vacant(_) => {
+ log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
+ return
+ }
+ }
+ };
+ let res = self.pay_route_internal(&route, payment_hash, &payment_secret, keysend_preimage,
+ payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
+ &send_payment_along_path);
log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
if let Err(e) = res {
self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
&self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
- route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH,
- entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
+ mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
+ inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
)
where
{
match err {
PaymentSendFailure::AllFailedResendSafe(errs) => {
- Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, errs.into_iter().map(|e| Err(e)), pending_events);
- self.retry_payment_internal(payment_id, payment_hash, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
+ Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, errs.into_iter().map(|e| Err(e)), pending_events);
+ self.retry_payment_internal(payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
},
- PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), results, .. } => {
- Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, results.into_iter(), pending_events);
+ PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
+ Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), pending_events);
// 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.
- self.retry_payment_internal(payment_id, payment_hash, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
+ self.retry_payment_internal(payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
},
PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
// This may happen if we send a payment and some paths fail, but only due to a temporary
// initial HTLC-Add messages yet.
},
PaymentSendFailure::PathParameterError(results) => {
- Self::push_payment_path_failed_evs(payment_id, payment_hash, route.paths, results.into_iter(), pending_events);
+ Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), pending_events);
self.abandon_payment(payment_id, pending_events);
},
PaymentSendFailure::ParameterError(e) => {
}
}
- fn push_payment_path_failed_evs<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>>(
- payment_id: PaymentId, payment_hash: PaymentHash, paths: Vec<Vec<RouteHop>>, path_results: I,
- pending_events: &Mutex<Vec<events::Event>>
+ fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>>(
+ payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
+ paths: Vec<Vec<RouteHop>>, path_results: I, pending_events: &Mutex<Vec<events::Event>>
) {
let mut events = pending_events.lock().unwrap();
debug_assert_eq!(paths.len(), path_results.len());
for (path, path_res) in paths.into_iter().zip(path_results) {
if let Err(e) = path_res {
- let failed_scid = if let APIError::InvalidRoute { .. } = e {
- None
- } else {
- Some(path[0].short_channel_id)
- };
+ if let APIError::MonitorUpdateInProgress = e { continue }
+ let mut failed_scid = None;
+ if let APIError::ChannelUnavailable { .. } = e {
+ let scid = path[0].short_channel_id;
+ failed_scid = Some(scid);
+ route_params.payment_params.previously_failed_channels.push(scid);
+ }
events.push(events::Event::PaymentPathFailed {
payment_id: Some(payment_id),
payment_hash,
payment_failed_permanently: false,
- network_update: None,
- all_paths_failed: false,
+ failure: events::PathFailure::InitialSend { err: e },
path,
short_channel_id: failed_scid,
retry: None,
}
}
- pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
- &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
- send_payment_along_path: F
- ) -> Result<(), PaymentSendFailure>
- where
- ES::Target: EntropySource,
- NS::Target: NodeSigner,
- F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
- u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
- {
- const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
- for path in route.paths.iter() {
- if path.len() == 0 {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: "length-0 path in route".to_string()
- }))
- }
- }
-
- let mut onion_session_privs = Vec::with_capacity(route.paths.len());
- for _ in 0..route.paths.len() {
- onion_session_privs.push(entropy_source.get_secure_random_bytes());
- }
-
- let (total_msat, payment_hash, payment_secret, keysend_preimage) = {
- let mut outbounds = self.pending_outbound_payments.lock().unwrap();
- match outbounds.get_mut(&payment_id) {
- Some(payment) => {
- let res = match payment {
- PendingOutboundPayment::Retryable {
- total_msat, payment_hash, keysend_preimage, payment_secret, pending_amt_msat, ..
- } => {
- let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
- if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: format!("retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat).to_string()
- }))
- }
- (*total_msat, *payment_hash, *payment_secret, *keysend_preimage)
- },
- PendingOutboundPayment::Legacy { .. } => {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
- }))
- },
- PendingOutboundPayment::Fulfilled { .. } => {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: "Payment already completed".to_owned()
- }));
- },
- PendingOutboundPayment::Abandoned { .. } => {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
- }));
- },
- };
- if !payment.is_retryable_now() {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
- }))
- }
- payment.increment_attempts();
- for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
- assert!(payment.insert(*session_priv_bytes, path));
- }
- res
- },
- None =>
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
- err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
- })),
- }
- };
- self.pay_route_internal(route, payment_hash, &payment_secret, keysend_preimage, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
- }
-
pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
&self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
node_signer: &NS, best_block_height: u32, send_payment_along_path: F
u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
{
if route.paths.len() < 1 {
- return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
+ return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
}
if payment_secret.is_none() && route.paths.len() > 1 {
- return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
+ return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
}
let mut total_value = 0;
let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
let mut path_errs = Vec::with_capacity(route.paths.len());
'path_check: for path in route.paths.iter() {
if path.len() < 1 || path.len() > 20 {
- path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
+ path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
continue 'path_check;
}
for (idx, hop) in path.iter().enumerate() {
if idx != path.len() - 1 && hop.pubkey == our_node_id {
- path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
+ path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
continue 'path_check;
}
}
Some(RouteParameters {
payment_params: payment_params.clone(),
final_value_msat: pending_amt_unsent,
- final_cltv_expiry_delta:
- if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
- else { max_unsent_cltv_delta },
})
} else { None }
} else { None },
awaiting_retry
});
- let mut all_paths_failed = false;
let mut full_failure_ev = None;
let mut pending_retry_ev = false;
let mut retry = None;
// `payment_params`) back to the user.
let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
if let Some(params) = payment.get_mut().payment_parameters() {
- if params.final_cltv_expiry_delta.is_none() {
- // This should be rare, but a user could provide None for the payment data, and
- // we need it when we go to retry the payment, so fill it in.
- params.final_cltv_expiry_delta = Some(path_last_hop.cltv_expiry_delta);
- }
retry = Some(RouteParameters {
payment_params: params.clone(),
final_value_msat: path_last_hop.fee_msat,
- final_cltv_expiry_delta: params.final_cltv_expiry_delta.unwrap(),
});
} else if let Some(params) = payment_params {
retry = Some(RouteParameters {
payment_params: params.clone(),
final_value_msat: path_last_hop.fee_msat,
- final_cltv_expiry_delta:
- if let Some(delta) = params.final_cltv_expiry_delta { delta }
- else { path_last_hop.cltv_expiry_delta },
});
}
is_retryable_now = false;
}
if payment.get().remaining_parts() == 0 {
- all_paths_failed = true;
if payment.get().abandoned() {
if !payment_is_probe {
full_failure_ev = Some(events::Event::PaymentFailed {
payment_id: Some(*payment_id),
payment_hash: payment_hash.clone(),
payment_failed_permanently: !payment_retryable,
- network_update,
- all_paths_failed,
+ failure: events::PathFailure::OnPath { network_update },
path: path.clone(),
short_channel_id,
retry,
(0, session_privs, required),
(1, pending_fee_msat, option),
(2, payment_hash, required),
- (3, payment_params, option),
+ // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
+ // never see it - `payment_params` was added here after the field was added/required.
+ (3, payment_params, (option: ReadableArgs, 0)),
(4, payment_secret, option),
(5, keysend_preimage, option),
(6, total_msat, required),
#[cfg(test)]
mod tests {
- use bitcoin::blockdata::constants::genesis_block;
use bitcoin::network::constants::Network;
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use crate::ln::PaymentHash;
use crate::ln::channelmanager::PaymentId;
+ use crate::ln::features::{ChannelFeatures, NodeFeatures};
use crate::ln::msgs::{ErrorAction, LightningError};
use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
use crate::routing::gossip::NetworkGraph;
- use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
+ use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters};
use crate::sync::{Arc, Mutex};
- use crate::util::events::Event;
+ use crate::util::errors::APIError;
+ use crate::util::events::{Event, PathFailure};
use crate::util::test_utils;
#[test]
fn do_fails_paying_after_expiration(on_retry: bool) {
let outbound_payments = OutboundPayments::new();
let logger = test_utils::TestLogger::new();
- let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
- let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
+ let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
let scorer = Mutex::new(test_utils::TestScorer::new());
let router = test_utils::TestRouter::new(network_graph, &scorer);
let secp_ctx = Secp256k1::new();
let expired_route_params = RouteParameters {
payment_params,
final_value_msat: 0,
- final_cltv_expiry_delta: 0,
};
let pending_events = Mutex::new(Vec::new());
if on_retry {
&Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
Some(expired_route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
outbound_payments.retry_payment_internal(
- PaymentId([0; 32]), PaymentHash([0; 32]), expired_route_params, &&router, vec![],
- &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
+ PaymentId([0; 32]), expired_route_params, &&router, vec![], &|| InFlightHtlcs::new(),
+ &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
&|_, _, _, _, _, _, _, _, _| Ok(()));
let events = pending_events.lock().unwrap();
assert_eq!(events.len(), 1);
fn do_find_route_error(on_retry: bool) {
let outbound_payments = OutboundPayments::new();
let logger = test_utils::TestLogger::new();
- let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
- let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
+ let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
let scorer = Mutex::new(test_utils::TestScorer::new());
let router = test_utils::TestRouter::new(network_graph, &scorer);
let secp_ctx = Secp256k1::new();
let route_params = RouteParameters {
payment_params,
final_value_msat: 0,
- final_cltv_expiry_delta: 0,
};
router.expect_find_route(route_params.clone(),
Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
&Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
Some(route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
outbound_payments.retry_payment_internal(
- PaymentId([0; 32]), PaymentHash([0; 32]), route_params, &&router, vec![],
- &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
+ PaymentId([0; 32]), route_params, &&router, vec![], &|| InFlightHtlcs::new(),
+ &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
&|_, _, _, _, _, _, _, _, _| Ok(()));
let events = pending_events.lock().unwrap();
assert_eq!(events.len(), 1);
} else { panic!("Unexpected error"); }
}
}
+
+ #[test]
+ fn initial_send_payment_path_failed_evs() {
+ let outbound_payments = OutboundPayments::new();
+ let logger = test_utils::TestLogger::new();
+ let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
+ let scorer = Mutex::new(test_utils::TestScorer::new());
+ let router = test_utils::TestRouter::new(network_graph, &scorer);
+ let secp_ctx = Secp256k1::new();
+ let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
+
+ let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
+ let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
+ let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
+ let route_params = RouteParameters {
+ payment_params: payment_params.clone(),
+ final_value_msat: 0,
+ };
+ let failed_scid = 42;
+ let route = Route {
+ paths: vec![vec![RouteHop {
+ pubkey: receiver_pk,
+ node_features: NodeFeatures::empty(),
+ short_channel_id: failed_scid,
+ channel_features: ChannelFeatures::empty(),
+ fee_msat: 0,
+ cltv_expiry_delta: 0,
+ }]],
+ payment_params: Some(payment_params),
+ };
+ router.expect_find_route(route_params.clone(), Ok(route.clone()));
+ let mut route_params_w_failed_scid = route_params.clone();
+ route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
+ router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
+ router.expect_find_route(route_params.clone(), Ok(route.clone()));
+ router.expect_find_route(route_params.clone(), Ok(route.clone()));
+
+ // Ensure that a ChannelUnavailable error will result in blaming an scid in the
+ // PaymentPathFailed event.
+ let pending_events = Mutex::new(Vec::new());
+ outbound_payments.send_payment(
+ PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params.clone(),
+ &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
+ &pending_events,
+ |_, _, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
+ .unwrap();
+ let mut events = pending_events.lock().unwrap();
+ assert_eq!(events.len(), 2);
+ if let Event::PaymentPathFailed {
+ short_channel_id,
+ failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0]
+ {
+ assert_eq!(short_channel_id, Some(failed_scid));
+ } else { panic!("Unexpected event"); }
+ if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
+ events.clear();
+ core::mem::drop(events);
+
+ // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
+ outbound_payments.send_payment(
+ PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params.clone(),
+ &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
+ &pending_events, |_, _, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress))
+ .unwrap();
+ {
+ let events = pending_events.lock().unwrap();
+ assert_eq!(events.len(), 0);
+ }
+
+ // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
+ outbound_payments.send_payment(
+ PaymentHash([0; 32]), &None, PaymentId([1; 32]), Retry::Attempts(0), route_params.clone(),
+ &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
+ &pending_events,
+ |_, _, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
+ .unwrap();
+ let events = pending_events.lock().unwrap();
+ assert_eq!(events.len(), 2);
+ if let Event::PaymentPathFailed {
+ short_channel_id,
+ failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0]
+ {
+ assert_eq!(short_channel_id, None);
+ } else { panic!("Unexpected event"); }
+ if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
+ }
}