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 //! Utilities to send payments and manage outbound payment information.
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
18 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, MIN_HTLC_RELAY_HOLDING_CELL_MILLIS, PaymentId};
19 use crate::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA as LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA;
20 use crate::ln::msgs::DecodeError;
21 use crate::ln::onion_utils::HTLCFailReason;
22 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
23 use crate::util::errors::APIError;
24 use crate::util::events;
25 use crate::util::logger::Logger;
26 use crate::util::time::Time;
27 #[cfg(all(not(feature = "no-std"), test))]
28 use crate::util::time::tests::SinceEpoch;
31 use core::fmt::{self, Display, Formatter};
33 use core::time::Duration;
35 use crate::prelude::*;
36 use crate::sync::Mutex;
38 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
39 /// and later, also stores information for retrying the payment.
40 pub(crate) enum PendingOutboundPayment {
42 session_privs: HashSet<[u8; 32]>,
45 retry_strategy: Option<Retry>,
46 attempts: PaymentAttempts,
47 payment_params: Option<PaymentParameters>,
48 session_privs: HashSet<[u8; 32]>,
49 payment_hash: PaymentHash,
50 payment_secret: Option<PaymentSecret>,
51 pending_amt_msat: u64,
52 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
53 pending_fee_msat: Option<u64>,
54 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
56 /// Our best known block height at the time this payment was initiated.
57 starting_block_height: u32,
59 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
60 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
61 /// and add a pending payment that was already fulfilled.
63 session_privs: HashSet<[u8; 32]>,
64 payment_hash: Option<PaymentHash>,
65 timer_ticks_without_htlcs: u8,
67 /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
68 /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
69 /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
70 /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
71 /// downstream event handler as to when a payment has actually failed.
73 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
75 session_privs: HashSet<[u8; 32]>,
76 payment_hash: PaymentHash,
80 impl PendingOutboundPayment {
81 fn increment_attempts(&mut self) {
82 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
86 fn is_auto_retryable_now(&self) -> bool {
88 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
89 strategy.is_retryable_now(&attempts)
94 fn is_retryable_now(&self) -> bool {
96 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
97 // We're handling retries manually, we can always retry.
100 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
101 strategy.is_retryable_now(&attempts)
106 fn payment_parameters(&mut self) -> Option<&mut PaymentParameters> {
108 PendingOutboundPayment::Retryable { payment_params: Some(ref mut params), .. } => {
114 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
115 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
116 params.previously_failed_channels.push(scid);
119 pub(super) fn is_fulfilled(&self) -> bool {
121 PendingOutboundPayment::Fulfilled { .. } => true,
125 pub(super) fn abandoned(&self) -> bool {
127 PendingOutboundPayment::Abandoned { .. } => true,
131 fn get_pending_fee_msat(&self) -> Option<u64> {
133 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
138 fn payment_hash(&self) -> Option<PaymentHash> {
140 PendingOutboundPayment::Legacy { .. } => None,
141 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
142 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
143 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
147 fn mark_fulfilled(&mut self) {
148 let mut session_privs = HashSet::new();
149 core::mem::swap(&mut session_privs, match self {
150 PendingOutboundPayment::Legacy { session_privs } |
151 PendingOutboundPayment::Retryable { session_privs, .. } |
152 PendingOutboundPayment::Fulfilled { session_privs, .. } |
153 PendingOutboundPayment::Abandoned { session_privs, .. }
156 let payment_hash = self.payment_hash();
157 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
160 fn mark_abandoned(&mut self) -> Result<(), ()> {
161 let mut session_privs = HashSet::new();
162 let our_payment_hash;
163 core::mem::swap(&mut session_privs, match self {
164 PendingOutboundPayment::Legacy { .. } |
165 PendingOutboundPayment::Fulfilled { .. } =>
167 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
168 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
169 our_payment_hash = *payment_hash;
173 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
177 /// panics if path is None and !self.is_fulfilled
178 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
179 let remove_res = match self {
180 PendingOutboundPayment::Legacy { session_privs } |
181 PendingOutboundPayment::Retryable { session_privs, .. } |
182 PendingOutboundPayment::Fulfilled { session_privs, .. } |
183 PendingOutboundPayment::Abandoned { session_privs, .. } => {
184 session_privs.remove(session_priv)
188 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
189 let path = path.expect("Fulfilling a payment should always come with a path");
190 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
191 *pending_amt_msat -= path_last_hop.fee_msat;
192 if let Some(fee_msat) = pending_fee_msat.as_mut() {
193 *fee_msat -= path.get_path_fees();
200 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
201 let insert_res = match self {
202 PendingOutboundPayment::Legacy { session_privs } |
203 PendingOutboundPayment::Retryable { session_privs, .. } => {
204 session_privs.insert(session_priv)
206 PendingOutboundPayment::Fulfilled { .. } => false,
207 PendingOutboundPayment::Abandoned { .. } => false,
210 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
211 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
212 *pending_amt_msat += path_last_hop.fee_msat;
213 if let Some(fee_msat) = pending_fee_msat.as_mut() {
214 *fee_msat += path.get_path_fees();
221 pub(super) fn remaining_parts(&self) -> usize {
223 PendingOutboundPayment::Legacy { session_privs } |
224 PendingOutboundPayment::Retryable { session_privs, .. } |
225 PendingOutboundPayment::Fulfilled { session_privs, .. } |
226 PendingOutboundPayment::Abandoned { session_privs, .. } => {
233 /// Strategies available to retry payment path failures.
234 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
236 /// Max number of attempts to retry payment.
238 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
239 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
240 /// were retried along a route from a single call to [`Router::find_route`].
242 #[cfg(not(feature = "no-std"))]
243 /// Time elapsed before abandoning retries for a payment.
244 Timeout(core::time::Duration),
248 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
249 match (self, attempts) {
250 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
251 max_retry_count > count
253 #[cfg(all(not(feature = "no-std"), not(test)))]
254 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
255 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
256 #[cfg(all(not(feature = "no-std"), test))]
257 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
258 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
263 #[cfg(feature = "std")]
264 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
265 if let Some(expiry_time) = route_params.payment_params.expiry_time {
266 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
267 return elapsed > core::time::Duration::from_secs(expiry_time)
273 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
275 /// Storing minimal payment attempts information required for determining if a outbound payment can
277 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
278 /// This count will be incremented only after the result of the attempt is known. When it's 0,
279 /// it means the result of the first attempt is not known yet.
280 pub(crate) count: usize,
281 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
282 first_attempted_at: T
285 #[cfg(not(any(feature = "no-std", test)))]
286 type ConfiguredTime = std::time::Instant;
287 #[cfg(feature = "no-std")]
288 type ConfiguredTime = crate::util::time::Eternity;
289 #[cfg(all(not(feature = "no-std"), test))]
290 type ConfiguredTime = SinceEpoch;
292 impl<T: Time> PaymentAttemptsUsingTime<T> {
293 pub(crate) fn new() -> Self {
294 PaymentAttemptsUsingTime {
296 first_attempted_at: T::now()
301 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
302 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
303 #[cfg(feature = "no-std")]
304 return write!(f, "attempts: {}", self.count);
305 #[cfg(not(feature = "no-std"))]
308 "attempts: {}, duration: {}s",
310 T::now().duration_since(self.first_attempted_at).as_secs()
315 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
316 /// Err() type describing which state the payment is in, see the description of individual enum
318 #[derive(Clone, Debug)]
319 pub enum PaymentSendFailure {
320 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
321 /// send the payment at all.
323 /// You can freely resend the payment in full (with the parameter error fixed).
325 /// Because the payment failed outright, no payment tracking is done, you do not need to call
326 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
327 /// for this payment.
329 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
330 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
331 ParameterError(APIError),
332 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
333 /// from attempting to send the payment at all.
335 /// You can freely resend the payment in full (with the parameter error fixed).
337 /// The results here are ordered the same as the paths in the route object which was passed to
340 /// Because the payment failed outright, no payment tracking is done, you do not need to call
341 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
342 /// for this payment.
344 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
345 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
346 PathParameterError(Vec<Result<(), APIError>>),
347 /// All paths which were attempted failed to send, with no channel state change taking place.
348 /// You can freely resend the payment in full (though you probably want to do so over different
349 /// paths than the ones selected).
351 /// Because the payment failed outright, no payment tracking is done, you do not need to call
352 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
353 /// for this payment.
355 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
356 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
357 AllFailedResendSafe(Vec<APIError>),
358 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
359 /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
360 /// [`ChannelManager::abandon_payment`]).
362 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
363 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
364 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
366 /// Some paths which were attempted failed to send, though possibly not all. At least some
367 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
368 /// in over-/re-payment.
370 /// The results here are ordered the same as the paths in the route object which was passed to
371 /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
372 /// safely retried via [`ChannelManager::retry_payment`].
374 /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
375 /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
376 /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
377 /// the next-hop channel with the latest update_id.
379 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
380 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
382 /// The errors themselves, in the same order as the route hops.
383 results: Vec<Result<(), APIError>>,
384 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
385 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
386 /// will pay all remaining unpaid balance.
387 failed_paths_retry: Option<RouteParameters>,
388 /// The payment id for the payment, which is now at least partially pending.
389 payment_id: PaymentId,
393 pub(super) struct OutboundPayments {
394 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
397 impl OutboundPayments {
398 pub(super) fn new() -> Self {
400 pending_outbound_payments: Mutex::new(HashMap::new())
404 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, F, L: Deref>(
405 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
406 retry_strategy: Retry, route_params: RouteParameters, router: &R,
407 first_hops: Vec<ChannelDetails>, inflight_htlcs: InFlightHtlcs, entropy_source: &ES,
408 node_signer: &NS, best_block_height: u32, logger: &L, send_payment_along_path: F,
409 ) -> Result<(), PaymentSendFailure>
412 ES::Target: EntropySource,
413 NS::Target: NodeSigner,
415 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
416 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
418 self.pay_internal(payment_id, Some((payment_hash, payment_secret, retry_strategy)),
419 route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer,
420 best_block_height, logger, &send_payment_along_path)
421 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
424 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
425 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
426 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
427 send_payment_along_path: F
428 ) -> Result<(), PaymentSendFailure>
430 ES::Target: EntropySource,
431 NS::Target: NodeSigner,
432 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
433 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
435 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, None, None, entropy_source, best_block_height)?;
436 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
437 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
438 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
441 pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
442 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
443 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
444 ) -> Result<PaymentHash, PaymentSendFailure>
446 ES::Target: EntropySource,
447 NS::Target: NodeSigner,
448 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
449 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
451 let preimage = match payment_preimage {
453 None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
455 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
456 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
458 match self.pay_route_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
459 Ok(()) => Ok(payment_hash),
461 self.remove_outbound_if_all_failed(payment_id, &e);
467 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
468 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
469 best_block_height: u32, logger: &L, send_payment_along_path: SP,
473 ES::Target: EntropySource,
474 NS::Target: NodeSigner,
475 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
476 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
477 IH: Fn() -> InFlightHtlcs,
478 FH: Fn() -> Vec<ChannelDetails>,
482 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
483 let mut retry_id_route_params = None;
484 for (pmt_id, pmt) in outbounds.iter_mut() {
485 if pmt.is_auto_retryable_now() {
486 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
487 if pending_amt_msat < total_msat {
488 retry_id_route_params = Some((*pmt_id, RouteParameters {
489 final_value_msat: *total_msat - *pending_amt_msat,
490 final_cltv_expiry_delta:
491 if let Some(delta) = params.final_cltv_expiry_delta { delta }
493 debug_assert!(false, "We always set the final_cltv_expiry_delta when a path fails");
494 LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA.into()
496 payment_params: params.clone(),
503 if let Some((payment_id, route_params)) = retry_id_route_params {
504 core::mem::drop(outbounds);
505 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) {
506 log_info!(logger, "Errored retrying payment: {:?}", e);
512 fn pay_internal<R: Deref, NS: Deref, ES: Deref, F, L: Deref>(
513 &self, payment_id: PaymentId,
514 initial_send_info: Option<(PaymentHash, &Option<PaymentSecret>, Retry)>,
515 route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
516 inflight_htlcs: InFlightHtlcs, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
517 logger: &L, send_payment_along_path: &F,
518 ) -> Result<(), PaymentSendFailure>
521 ES::Target: EntropySource,
522 NS::Target: NodeSigner,
524 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
525 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
527 #[cfg(feature = "std")] {
528 if has_expired(&route_params) {
529 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
530 err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
535 let route = router.find_route(
536 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
537 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
538 ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
539 err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
542 let res = if let Some((payment_hash, payment_secret, retry_strategy)) = initial_send_info {
543 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, &route, Some(retry_strategy), Some(route_params.payment_params.clone()), entropy_source, best_block_height)?;
544 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)
546 self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path)
549 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
550 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);
551 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
552 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = &retry_res {
553 if err.starts_with("Retries exhausted ") { return res; }
557 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), .. }) => {
558 // Some paths were sent, even if we failed to send the full MPP value our recipient may
559 // misbehave and claim the funds, at which point we have to consider the payment sent, so
560 // return `Ok()` here, ignoring any retry errors.
561 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);
562 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
565 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
566 // This may happen if we send a payment and some paths fail, but only due to a temporary
567 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
568 // initial HTLC-Add messages yet.
575 pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
576 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
577 send_payment_along_path: F
578 ) -> Result<(), PaymentSendFailure>
580 ES::Target: EntropySource,
581 NS::Target: NodeSigner,
582 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
583 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
585 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
586 for path in route.paths.iter() {
588 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
589 err: "length-0 path in route".to_string()
594 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
595 for _ in 0..route.paths.len() {
596 onion_session_privs.push(entropy_source.get_secure_random_bytes());
599 let (total_msat, payment_hash, payment_secret) = {
600 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
601 match outbounds.get_mut(&payment_id) {
603 let res = match payment {
604 PendingOutboundPayment::Retryable {
605 total_msat, payment_hash, payment_secret, pending_amt_msat, ..
607 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
608 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
609 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
610 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()
613 (*total_msat, *payment_hash, *payment_secret)
615 PendingOutboundPayment::Legacy { .. } => {
616 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
617 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
620 PendingOutboundPayment::Fulfilled { .. } => {
621 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
622 err: "Payment already completed".to_owned()
625 PendingOutboundPayment::Abandoned { .. } => {
626 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
627 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
631 if !payment.is_retryable_now() {
632 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
633 err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
636 payment.increment_attempts();
637 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
638 assert!(payment.insert(*session_priv_bytes, path));
643 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
644 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
648 self.pay_route_internal(route, payment_hash, &payment_secret, None, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
651 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
652 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
653 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
654 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
656 ES::Target: EntropySource,
657 NS::Target: NodeSigner,
658 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
659 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
661 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
663 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
666 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
667 err: "No need probing a path with less than two hops".to_string()
671 let route = Route { paths: vec![hops], payment_params: None };
672 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
674 match self.pay_route_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
675 Ok(()) => Ok((payment_hash, payment_id)),
677 self.remove_outbound_if_all_failed(payment_id, &e);
684 pub(super) fn test_add_new_pending_payment<ES: Deref>(
685 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
686 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
687 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
688 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, retry_strategy, None, entropy_source, best_block_height)
691 pub(super) fn add_new_pending_payment<ES: Deref>(
692 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
693 route: &Route, retry_strategy: Option<Retry>, payment_params: Option<PaymentParameters>,
694 entropy_source: &ES, best_block_height: u32
695 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
696 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
697 for _ in 0..route.paths.len() {
698 onion_session_privs.push(entropy_source.get_secure_random_bytes());
701 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
702 match pending_outbounds.entry(payment_id) {
703 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
704 hash_map::Entry::Vacant(entry) => {
705 let payment = entry.insert(PendingOutboundPayment::Retryable {
707 attempts: PaymentAttempts::new(),
709 session_privs: HashSet::new(),
711 pending_fee_msat: Some(0),
714 starting_block_height: best_block_height,
715 total_msat: route.get_total_amount(),
718 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
719 assert!(payment.insert(*session_priv_bytes, path));
722 Ok(onion_session_privs)
727 fn pay_route_internal<NS: Deref, F>(
728 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
729 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
730 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
731 send_payment_along_path: &F
732 ) -> Result<(), PaymentSendFailure>
734 NS::Target: NodeSigner,
735 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
736 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
738 if route.paths.len() < 1 {
739 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
741 if payment_secret.is_none() && route.paths.len() > 1 {
742 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
744 let mut total_value = 0;
745 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
746 let mut path_errs = Vec::with_capacity(route.paths.len());
747 'path_check: for path in route.paths.iter() {
748 if path.len() < 1 || path.len() > 20 {
749 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
750 continue 'path_check;
752 for (idx, hop) in path.iter().enumerate() {
753 if idx != path.len() - 1 && hop.pubkey == our_node_id {
754 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
755 continue 'path_check;
758 total_value += path.last().unwrap().fee_msat;
759 path_errs.push(Ok(()));
761 if path_errs.iter().any(|e| e.is_err()) {
762 return Err(PaymentSendFailure::PathParameterError(path_errs));
764 if let Some(amt_msat) = recv_value_msat {
765 debug_assert!(amt_msat >= total_value);
766 total_value = amt_msat;
769 let cur_height = best_block_height + 1;
770 let mut results = Vec::new();
771 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
772 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
773 let mut path_res = send_payment_along_path(&path, &route.payment_params, &payment_hash, payment_secret, total_value, cur_height, payment_id, &keysend_preimage, session_priv);
776 Err(APIError::MonitorUpdateInProgress) => {
777 // While a MonitorUpdateInProgress is an Err(_), the payment is still
778 // considered "in flight" and we shouldn't remove it from the
779 // PendingOutboundPayment set.
782 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
783 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
784 let removed = payment.remove(&session_priv, Some(path));
785 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
787 debug_assert!(false, "This can't happen as the payment was added by callers");
788 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
792 results.push(path_res);
794 let mut has_ok = false;
795 let mut has_err = false;
796 let mut pending_amt_unsent = 0;
797 let mut max_unsent_cltv_delta = 0;
798 for (res, path) in results.iter().zip(route.paths.iter()) {
799 if res.is_ok() { has_ok = true; }
800 if res.is_err() { has_err = true; }
801 if let &Err(APIError::MonitorUpdateInProgress) = res {
802 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
806 } else if res.is_err() {
807 pending_amt_unsent += path.last().unwrap().fee_msat;
808 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
811 if has_err && has_ok {
812 Err(PaymentSendFailure::PartialFailure {
815 failed_paths_retry: if pending_amt_unsent != 0 {
816 if let Some(payment_params) = &route.payment_params {
817 Some(RouteParameters {
818 payment_params: payment_params.clone(),
819 final_value_msat: pending_amt_unsent,
820 final_cltv_expiry_delta:
821 if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
822 else { max_unsent_cltv_delta },
828 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
835 pub(super) fn test_send_payment_internal<NS: Deref, F>(
836 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
837 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
838 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
839 send_payment_along_path: F
840 ) -> Result<(), PaymentSendFailure>
842 NS::Target: NodeSigner,
843 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
844 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
846 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
847 recv_value_msat, onion_session_privs, node_signer, best_block_height,
848 &send_payment_along_path)
849 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
852 // If we failed to send any paths, we should remove the new PaymentId from the
853 // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
854 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
855 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
856 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
857 debug_assert!(removed, "We should always have a pending payment to remove here");
861 pub(super) fn claim_htlc<L: Deref>(
862 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
863 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
864 ) where L::Target: Logger {
865 let mut session_priv_bytes = [0; 32];
866 session_priv_bytes.copy_from_slice(&session_priv[..]);
867 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
868 let mut pending_events = pending_events.lock().unwrap();
869 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
870 if !payment.get().is_fulfilled() {
871 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
872 let fee_paid_msat = payment.get().get_pending_fee_msat();
874 events::Event::PaymentSent {
875 payment_id: Some(payment_id),
881 payment.get_mut().mark_fulfilled();
885 // We currently immediately remove HTLCs which were fulfilled on-chain.
886 // This could potentially lead to removing a pending payment too early,
887 // with a reorg of one block causing us to re-add the fulfilled payment on
889 // TODO: We should have a second monitor event that informs us of payments
890 // irrevocably fulfilled.
891 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
892 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
894 events::Event::PaymentPathSuccessful {
903 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
907 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
908 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
909 let mut pending_events = pending_events.lock().unwrap();
910 for source in sources {
911 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
912 let mut session_priv_bytes = [0; 32];
913 session_priv_bytes.copy_from_slice(&session_priv[..]);
914 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
915 assert!(payment.get().is_fulfilled());
916 if payment.get_mut().remove(&session_priv_bytes, None) {
918 events::Event::PaymentPathSuccessful {
920 payment_hash: payment.get().payment_hash(),
930 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
931 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
932 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
933 // this could race the user making a duplicate send_payment call and our idempotency
934 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
935 // removal. This should be more than sufficient to ensure the idempotency of any
936 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
938 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
939 let pending_events = pending_events.lock().unwrap();
940 pending_outbound_payments.retain(|payment_id, payment| {
941 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
942 let mut no_remaining_entries = session_privs.is_empty();
943 if no_remaining_entries {
944 for ev in pending_events.iter() {
946 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
947 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
948 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
949 if payment_id == ev_payment_id {
950 no_remaining_entries = false;
958 if no_remaining_entries {
959 *timer_ticks_without_htlcs += 1;
960 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
962 *timer_ticks_without_htlcs = 0;
969 pub(super) fn fail_htlc<L: Deref>(
970 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
971 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
972 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
973 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
974 ) where L::Target: Logger {
976 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
978 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
980 let mut session_priv_bytes = [0; 32];
981 session_priv_bytes.copy_from_slice(&session_priv[..]);
982 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
983 let mut all_paths_failed = false;
984 let mut full_failure_ev = None;
985 let mut pending_retry_ev = None;
986 let mut retry = None;
987 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
988 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
989 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
992 if payment.get().is_fulfilled() {
993 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
996 let is_retryable_now = payment.get().is_auto_retryable_now();
997 if let Some(scid) = short_channel_id {
998 payment.get_mut().insert_previously_failed_scid(scid);
1001 // We want to move towards only using the `PaymentParameters` in the outbound payments
1002 // map. However, for backwards-compatibility, we still need to support passing the
1003 // `PaymentParameters` data that was shoved in the HTLC (and given to us via
1004 // `payment_params`) back to the user.
1005 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
1006 if let Some(params) = payment.get_mut().payment_parameters() {
1007 if params.final_cltv_expiry_delta.is_none() {
1008 // This should be rare, but a user could provide None for the payment data, and
1009 // we need it when we go to retry the payment, so fill it in.
1010 params.final_cltv_expiry_delta = Some(path_last_hop.cltv_expiry_delta);
1012 retry = Some(RouteParameters {
1013 payment_params: params.clone(),
1014 final_value_msat: path_last_hop.fee_msat,
1015 final_cltv_expiry_delta: params.final_cltv_expiry_delta.unwrap(),
1017 } else if let Some(params) = payment_params {
1018 retry = Some(RouteParameters {
1019 payment_params: params.clone(),
1020 final_value_msat: path_last_hop.fee_msat,
1021 final_cltv_expiry_delta:
1022 if let Some(delta) = params.final_cltv_expiry_delta { delta }
1023 else { path_last_hop.cltv_expiry_delta },
1027 if payment.get().remaining_parts() == 0 {
1028 all_paths_failed = true;
1029 if payment.get().abandoned() {
1030 full_failure_ev = Some(events::Event::PaymentFailed {
1031 payment_id: *payment_id,
1032 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1039 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1042 core::mem::drop(outbounds);
1043 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1045 let path_failure = {
1046 if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
1047 if !payment_retryable {
1048 events::Event::ProbeSuccessful {
1049 payment_id: *payment_id,
1050 payment_hash: payment_hash.clone(),
1054 events::Event::ProbeFailed {
1055 payment_id: *payment_id,
1056 payment_hash: payment_hash.clone(),
1062 // TODO: If we decided to blame ourselves (or one of our channels) in
1063 // process_onion_failure we should close that channel as it implies our
1064 // next-hop is needlessly blaming us!
1065 if let Some(scid) = short_channel_id {
1066 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1068 if payment_retryable && attempts_remaining && retry.is_some() {
1069 debug_assert!(full_failure_ev.is_none());
1070 pending_retry_ev = Some(events::Event::PendingHTLCsForwardable {
1071 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
1074 events::Event::PaymentPathFailed {
1075 payment_id: Some(*payment_id),
1076 payment_hash: payment_hash.clone(),
1077 payment_failed_permanently: !payment_retryable,
1084 error_code: onion_error_code,
1086 error_data: onion_error_data
1090 let mut pending_events = pending_events.lock().unwrap();
1091 pending_events.push(path_failure);
1092 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1093 if let Some(ev) = pending_retry_ev { pending_events.push(ev); }
1096 pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
1097 let mut failed_ev = None;
1098 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1099 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1100 if let Ok(()) = payment.get_mut().mark_abandoned() {
1101 if payment.get().remaining_parts() == 0 {
1102 failed_ev = Some(events::Event::PaymentFailed {
1104 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1114 pub fn has_pending_payments(&self) -> bool {
1115 !self.pending_outbound_payments.lock().unwrap().is_empty()
1119 pub fn clear_pending_payments(&self) {
1120 self.pending_outbound_payments.lock().unwrap().clear()
1124 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1126 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1127 probing_cookie_secret: [u8; 32]) -> bool
1129 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1130 target_payment_hash == *payment_hash
1133 /// Returns the 'probing cookie' for the given [`PaymentId`].
1134 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1135 let mut preimage = [0u8; 64];
1136 preimage[..32].copy_from_slice(&probing_cookie_secret);
1137 preimage[32..].copy_from_slice(&payment_id.0);
1138 PaymentHash(Sha256::hash(&preimage).into_inner())
1141 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1143 (0, session_privs, required),
1146 (0, session_privs, required),
1147 (1, payment_hash, option),
1148 (3, timer_ticks_without_htlcs, (default_value, 0)),
1151 (0, session_privs, required),
1152 (1, pending_fee_msat, option),
1153 (2, payment_hash, required),
1154 (3, payment_params, option),
1155 (4, payment_secret, option),
1156 (6, total_msat, required),
1157 (8, pending_amt_msat, required),
1158 (10, starting_block_height, required),
1159 (not_written, retry_strategy, (static_value, None)),
1160 (not_written, attempts, (static_value, PaymentAttempts::new())),
1163 (0, session_privs, required),
1164 (2, payment_hash, required),
1170 use bitcoin::blockdata::constants::genesis_block;
1171 use bitcoin::network::constants::Network;
1172 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1174 use crate::ln::PaymentHash;
1175 use crate::ln::channelmanager::{PaymentId, PaymentSendFailure};
1176 use crate::ln::msgs::{ErrorAction, LightningError};
1177 use crate::ln::outbound_payment::{OutboundPayments, Retry};
1178 use crate::routing::gossip::NetworkGraph;
1179 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
1180 use crate::sync::Arc;
1181 use crate::util::errors::APIError;
1182 use crate::util::test_utils;
1185 #[cfg(feature = "std")]
1186 fn fails_paying_after_expiration() {
1187 do_fails_paying_after_expiration(false);
1188 do_fails_paying_after_expiration(true);
1190 #[cfg(feature = "std")]
1191 fn do_fails_paying_after_expiration(on_retry: bool) {
1192 let outbound_payments = OutboundPayments::new();
1193 let logger = test_utils::TestLogger::new();
1194 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1195 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1196 let router = test_utils::TestRouter::new(network_graph);
1197 let secp_ctx = Secp256k1::new();
1198 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1200 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1201 let payment_params = PaymentParameters::from_node_id(
1202 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1204 ).with_expiry_time(past_expiry_time);
1205 let expired_route_params = RouteParameters {
1207 final_value_msat: 0,
1208 final_cltv_expiry_delta: 0,
1210 let err = if on_retry {
1211 outbound_payments.pay_internal(
1212 PaymentId([0; 32]), None, expired_route_params, &&router, vec![], InFlightHtlcs::new(),
1213 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1215 outbound_payments.send_payment(
1216 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1217 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1218 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1220 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1221 assert!(err.contains("Invoice expired"));
1222 } else { panic!("Unexpected error"); }
1226 fn find_route_error() {
1227 do_find_route_error(false);
1228 do_find_route_error(true);
1230 fn do_find_route_error(on_retry: bool) {
1231 let outbound_payments = OutboundPayments::new();
1232 let logger = test_utils::TestLogger::new();
1233 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1234 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1235 let router = test_utils::TestRouter::new(network_graph);
1236 let secp_ctx = Secp256k1::new();
1237 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1239 let payment_params = PaymentParameters::from_node_id(
1240 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1241 let route_params = RouteParameters {
1243 final_value_msat: 0,
1244 final_cltv_expiry_delta: 0,
1246 router.expect_find_route(route_params.clone(),
1247 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1249 let err = if on_retry {
1250 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]),
1251 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1252 &&keys_manager, 0).unwrap();
1253 outbound_payments.pay_internal(
1254 PaymentId([0; 32]), None, route_params, &&router, vec![], InFlightHtlcs::new(),
1255 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1257 outbound_payments.send_payment(
1258 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1259 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1260 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1262 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1263 assert!(err.contains("Failed to find a route"));
1264 } else { panic!("Unexpected error"); }