+ R::Target: Router,
+ ES::Target: EntropySource,
+ NS::Target: NodeSigner,
+ SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
+ u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
+ IH: Fn() -> InFlightHtlcs,
+ FH: Fn() -> Vec<ChannelDetails>,
+ L::Target: Logger,
+ {
+ let _single_thread = self.retry_lock.lock().unwrap();
+ loop {
+ let mut outbounds = self.pending_outbound_payments.lock().unwrap();
+ 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 { pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
+ if pending_amt_msat < total_msat {
+ 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, route_params)) = retry_id_route_params {
+ if let Err(e) = self.pay_internal(payment_id, None, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, &send_payment_along_path) {
+ log_info!(logger, "Errored retrying payment: {:?}", e);
+ // If we error on retry, there is no chance of the payment succeeding and no HTLCs have
+ // been irrevocably committed to, so we can safely abandon.
+ self.abandon_payment(payment_id, pending_events);
+ }
+ } else { break }
+ }
+
+ let mut outbounds = self.pending_outbound_payments.lock().unwrap();
+ outbounds.retain(|pmt_id, pmt| {
+ let mut retain = true;
+ if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
+ if pmt.mark_abandoned().is_ok() {
+ pending_events.lock().unwrap().push(events::Event::PaymentFailed {
+ payment_id: *pmt_id,
+ payment_hash: pmt.payment_hash().expect("PendingOutboundPayments::Retryable always has a payment hash set"),
+ });
+ retain = false;
+ }
+ }
+ retain
+ });
+ }
+
+ /// Will return `Ok(())` iff at least one HTLC is sent for the payment.
+ fn pay_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
+ &self, payment_id: PaymentId,
+ initial_send_info: Option<(PaymentHash, &Option<PaymentSecret>, Option<PaymentPreimage>, Retry)>,
+ route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
+ inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
+ logger: &L, send_payment_along_path: &SP,
+ ) -> Result<(), PaymentSendFailure>
+ where
+ R::Target: Router,
+ ES::Target: EntropySource,
+ NS::Target: NodeSigner,
+ L::Target: Logger,
+ IH: Fn() -> InFlightHtlcs,
+ SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
+ u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
+ {
+ #[cfg(feature = "std")] {
+ if has_expired(&route_params) {
+ return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
+ err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
+ }))
+ }
+ }
+
+ let route = router.find_route(
+ &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
+ Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
+ ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
+ err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
+ }))?;
+
+ let res = if let Some((payment_hash, payment_secret, keysend_preimage, retry_strategy)) = initial_send_info {
+ let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, keysend_preimage, &route, Some(retry_strategy), Some(route_params.payment_params.clone()), entropy_source, best_block_height)?;
+ self.pay_route_internal(&route, payment_hash, payment_secret, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path)
+ } else {
+ self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path)
+ };
+ match res {
+ Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
+ let retry_res = self.pay_internal(payment_id, None, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
+ log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
+ if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = &retry_res {
+ if err.starts_with("Retries exhausted ") { return res; }
+ }
+ retry_res
+ },
+ Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), .. }) => {
+ // 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 retry_res = self.pay_internal(payment_id, None, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
+ log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
+ Ok(())
+ },
+ Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
+ // 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.
+ Ok(())
+ },
+ res => res,
+ }
+ }
+
+ 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,