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 keysend_preimage: Option<PaymentPreimage>,
52 pending_amt_msat: u64,
53 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
54 pending_fee_msat: Option<u64>,
55 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
57 /// Our best known block height at the time this payment was initiated.
58 starting_block_height: u32,
60 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
61 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
62 /// and add a pending payment that was already fulfilled.
64 session_privs: HashSet<[u8; 32]>,
65 payment_hash: Option<PaymentHash>,
66 timer_ticks_without_htlcs: u8,
68 /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
69 /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
70 /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
71 /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
72 /// downstream event handler as to when a payment has actually failed.
74 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
76 session_privs: HashSet<[u8; 32]>,
77 payment_hash: PaymentHash,
81 impl PendingOutboundPayment {
82 fn increment_attempts(&mut self) {
83 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
87 fn is_auto_retryable_now(&self) -> bool {
89 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
90 strategy.is_retryable_now(&attempts)
95 fn is_retryable_now(&self) -> bool {
97 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
98 // We're handling retries manually, we can always retry.
101 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
102 strategy.is_retryable_now(&attempts)
107 fn payment_parameters(&mut self) -> Option<&mut PaymentParameters> {
109 PendingOutboundPayment::Retryable { payment_params: Some(ref mut params), .. } => {
115 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
116 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
117 params.previously_failed_channels.push(scid);
120 pub(super) fn is_fulfilled(&self) -> bool {
122 PendingOutboundPayment::Fulfilled { .. } => true,
126 pub(super) fn abandoned(&self) -> bool {
128 PendingOutboundPayment::Abandoned { .. } => true,
132 fn get_pending_fee_msat(&self) -> Option<u64> {
134 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
139 fn payment_hash(&self) -> Option<PaymentHash> {
141 PendingOutboundPayment::Legacy { .. } => None,
142 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
143 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
144 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
148 fn mark_fulfilled(&mut self) {
149 let mut session_privs = HashSet::new();
150 core::mem::swap(&mut session_privs, match self {
151 PendingOutboundPayment::Legacy { session_privs } |
152 PendingOutboundPayment::Retryable { session_privs, .. } |
153 PendingOutboundPayment::Fulfilled { session_privs, .. } |
154 PendingOutboundPayment::Abandoned { session_privs, .. }
157 let payment_hash = self.payment_hash();
158 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
161 fn mark_abandoned(&mut self) -> Result<(), ()> {
162 let mut session_privs = HashSet::new();
163 let our_payment_hash;
164 core::mem::swap(&mut session_privs, match self {
165 PendingOutboundPayment::Legacy { .. } |
166 PendingOutboundPayment::Fulfilled { .. } =>
168 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
169 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
170 our_payment_hash = *payment_hash;
174 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
178 /// panics if path is None and !self.is_fulfilled
179 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
180 let remove_res = match self {
181 PendingOutboundPayment::Legacy { session_privs } |
182 PendingOutboundPayment::Retryable { session_privs, .. } |
183 PendingOutboundPayment::Fulfilled { session_privs, .. } |
184 PendingOutboundPayment::Abandoned { session_privs, .. } => {
185 session_privs.remove(session_priv)
189 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
190 let path = path.expect("Fulfilling a payment should always come with a path");
191 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
192 *pending_amt_msat -= path_last_hop.fee_msat;
193 if let Some(fee_msat) = pending_fee_msat.as_mut() {
194 *fee_msat -= path.get_path_fees();
201 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
202 let insert_res = match self {
203 PendingOutboundPayment::Legacy { session_privs } |
204 PendingOutboundPayment::Retryable { session_privs, .. } => {
205 session_privs.insert(session_priv)
207 PendingOutboundPayment::Fulfilled { .. } => false,
208 PendingOutboundPayment::Abandoned { .. } => false,
211 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
212 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
213 *pending_amt_msat += path_last_hop.fee_msat;
214 if let Some(fee_msat) = pending_fee_msat.as_mut() {
215 *fee_msat += path.get_path_fees();
222 pub(super) fn remaining_parts(&self) -> usize {
224 PendingOutboundPayment::Legacy { session_privs } |
225 PendingOutboundPayment::Retryable { session_privs, .. } |
226 PendingOutboundPayment::Fulfilled { session_privs, .. } |
227 PendingOutboundPayment::Abandoned { session_privs, .. } => {
234 /// Strategies available to retry payment path failures.
235 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
237 /// Max number of attempts to retry payment.
239 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
240 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
241 /// were retried along a route from a single call to [`Router::find_route`].
243 #[cfg(not(feature = "no-std"))]
244 /// Time elapsed before abandoning retries for a payment.
245 Timeout(core::time::Duration),
249 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
250 match (self, attempts) {
251 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
252 max_retry_count > count
254 #[cfg(all(not(feature = "no-std"), not(test)))]
255 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
256 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
257 #[cfg(all(not(feature = "no-std"), test))]
258 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
259 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
264 #[cfg(feature = "std")]
265 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
266 if let Some(expiry_time) = route_params.payment_params.expiry_time {
267 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
268 return elapsed > core::time::Duration::from_secs(expiry_time)
274 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
276 /// Storing minimal payment attempts information required for determining if a outbound payment can
278 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
279 /// This count will be incremented only after the result of the attempt is known. When it's 0,
280 /// it means the result of the first attempt is not known yet.
281 pub(crate) count: usize,
282 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
283 first_attempted_at: T
286 #[cfg(not(any(feature = "no-std", test)))]
287 type ConfiguredTime = std::time::Instant;
288 #[cfg(feature = "no-std")]
289 type ConfiguredTime = crate::util::time::Eternity;
290 #[cfg(all(not(feature = "no-std"), test))]
291 type ConfiguredTime = SinceEpoch;
293 impl<T: Time> PaymentAttemptsUsingTime<T> {
294 pub(crate) fn new() -> Self {
295 PaymentAttemptsUsingTime {
297 first_attempted_at: T::now()
302 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
303 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
304 #[cfg(feature = "no-std")]
305 return write!(f, "attempts: {}", self.count);
306 #[cfg(not(feature = "no-std"))]
309 "attempts: {}, duration: {}s",
311 T::now().duration_since(self.first_attempted_at).as_secs()
316 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
317 /// Err() type describing which state the payment is in, see the description of individual enum
319 #[derive(Clone, Debug)]
320 pub enum PaymentSendFailure {
321 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
322 /// send the payment at all.
324 /// You can freely resend the payment in full (with the parameter error fixed).
326 /// Because the payment failed outright, no payment tracking is done and no
327 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
329 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
330 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
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 /// Because the payment failed outright, no payment tracking is done and no
338 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
340 /// The results here are ordered the same as the paths in the route object which was passed to
343 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
344 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
345 PathParameterError(Vec<Result<(), APIError>>),
346 /// All paths which were attempted failed to send, with no channel state change taking place.
347 /// You can freely resend the payment in full (though you probably want to do so over different
348 /// paths than the ones selected).
350 /// Because the payment failed outright, no payment tracking is done and no
351 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
353 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
354 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
355 AllFailedResendSafe(Vec<APIError>),
356 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
357 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
359 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
360 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
361 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
363 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
364 /// some paths have irrevocably committed to the HTLC.
366 /// The results here are ordered the same as the paths in the route object that was passed to
369 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
370 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
372 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
374 /// The errors themselves, in the same order as the paths from the route.
375 results: Vec<Result<(), APIError>>,
376 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
377 /// contain a [`RouteParameters`] object for the failing paths.
378 failed_paths_retry: Option<RouteParameters>,
379 /// The payment id for the payment, which is now at least partially pending.
380 payment_id: PaymentId,
384 pub(super) struct OutboundPayments {
385 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
386 pub(super) retry_lock: Mutex<()>,
389 impl OutboundPayments {
390 pub(super) fn new() -> Self {
392 pending_outbound_payments: Mutex::new(HashMap::new()),
393 retry_lock: Mutex::new(()),
397 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
398 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
399 retry_strategy: Retry, route_params: RouteParameters, router: &R,
400 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
401 node_signer: &NS, best_block_height: u32, logger: &L, send_payment_along_path: SP,
402 ) -> Result<(), PaymentSendFailure>
405 ES::Target: EntropySource,
406 NS::Target: NodeSigner,
408 IH: Fn() -> InFlightHtlcs,
409 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
410 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
412 self.pay_internal(payment_id, Some((payment_hash, payment_secret, None, retry_strategy)),
413 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
414 best_block_height, logger, &send_payment_along_path)
415 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
418 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
419 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
420 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
421 send_payment_along_path: F
422 ) -> Result<(), PaymentSendFailure>
424 ES::Target: EntropySource,
425 NS::Target: NodeSigner,
426 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
427 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
429 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, None, route, None, None, entropy_source, best_block_height)?;
430 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
431 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
432 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
435 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
436 &self, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
437 retry_strategy: Retry, route_params: RouteParameters, router: &R,
438 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
439 node_signer: &NS, best_block_height: u32, logger: &L, send_payment_along_path: SP
440 ) -> Result<PaymentHash, PaymentSendFailure>
443 ES::Target: EntropySource,
444 NS::Target: NodeSigner,
446 IH: Fn() -> InFlightHtlcs,
447 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
448 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
450 let preimage = payment_preimage
451 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
452 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
453 self.pay_internal(payment_id, Some((payment_hash, &None, Some(preimage), retry_strategy)),
454 route_params, router, first_hops, &inflight_htlcs, entropy_source, node_signer,
455 best_block_height, logger, &send_payment_along_path)
456 .map(|()| payment_hash)
457 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
460 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
461 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
462 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
463 ) -> Result<PaymentHash, PaymentSendFailure>
465 ES::Target: EntropySource,
466 NS::Target: NodeSigner,
467 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
468 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
470 let preimage = payment_preimage
471 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
472 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
473 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
475 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) {
476 Ok(()) => Ok(payment_hash),
478 self.remove_outbound_if_all_failed(payment_id, &e);
484 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
485 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
486 best_block_height: u32, pending_events: &Mutex<Vec<events::Event>>, logger: &L,
487 send_payment_along_path: SP,
491 ES::Target: EntropySource,
492 NS::Target: NodeSigner,
493 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
494 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
495 IH: Fn() -> InFlightHtlcs,
496 FH: Fn() -> Vec<ChannelDetails>,
499 let _single_thread = self.retry_lock.lock().unwrap();
501 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
502 let mut retry_id_route_params = None;
503 for (pmt_id, pmt) in outbounds.iter_mut() {
504 if pmt.is_auto_retryable_now() {
505 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
506 if pending_amt_msat < total_msat {
507 retry_id_route_params = Some((*pmt_id, RouteParameters {
508 final_value_msat: *total_msat - *pending_amt_msat,
509 final_cltv_expiry_delta:
510 if let Some(delta) = params.final_cltv_expiry_delta { delta }
512 debug_assert!(false, "We always set the final_cltv_expiry_delta when a path fails");
513 LDK_DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA.into()
515 payment_params: params.clone(),
522 core::mem::drop(outbounds);
523 if let Some((payment_id, route_params)) = retry_id_route_params {
524 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) {
525 log_info!(logger, "Errored retrying payment: {:?}", e);
526 // If we error on retry, there is no chance of the payment succeeding and no HTLCs have
527 // been irrevocably committed to, so we can safely abandon.
528 self.abandon_payment(payment_id, pending_events);
533 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
534 outbounds.retain(|pmt_id, pmt| {
535 let mut retain = true;
536 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
537 if pmt.mark_abandoned().is_ok() {
538 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
540 payment_hash: pmt.payment_hash().expect("PendingOutboundPayments::Retryable always has a payment hash set"),
549 pub(super) fn needs_abandon(&self) -> bool {
550 let outbounds = self.pending_outbound_payments.lock().unwrap();
551 outbounds.iter().any(|(_, pmt)|
552 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
555 /// Will return `Ok(())` iff at least one HTLC is sent for the payment.
556 fn pay_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
557 &self, payment_id: PaymentId,
558 initial_send_info: Option<(PaymentHash, &Option<PaymentSecret>, Option<PaymentPreimage>, Retry)>,
559 route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
560 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
561 logger: &L, send_payment_along_path: &SP,
562 ) -> Result<(), PaymentSendFailure>
565 ES::Target: EntropySource,
566 NS::Target: NodeSigner,
568 IH: Fn() -> InFlightHtlcs,
569 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
570 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
572 #[cfg(feature = "std")] {
573 if has_expired(&route_params) {
574 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
575 err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
580 let route = router.find_route(
581 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
582 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
583 ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
584 err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
587 let res = if let Some((payment_hash, payment_secret, keysend_preimage, retry_strategy)) = initial_send_info {
588 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)?;
589 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)
591 self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path)
594 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
595 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);
596 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
597 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = &retry_res {
598 if err.starts_with("Retries exhausted ") { return res; }
602 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), .. }) => {
603 // Some paths were sent, even if we failed to send the full MPP value our recipient may
604 // misbehave and claim the funds, at which point we have to consider the payment sent, so
605 // return `Ok()` here, ignoring any retry errors.
606 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);
607 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
610 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
611 // This may happen if we send a payment and some paths fail, but only due to a temporary
612 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
613 // initial HTLC-Add messages yet.
620 pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
621 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
622 send_payment_along_path: F
623 ) -> Result<(), PaymentSendFailure>
625 ES::Target: EntropySource,
626 NS::Target: NodeSigner,
627 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
628 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
630 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
631 for path in route.paths.iter() {
633 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
634 err: "length-0 path in route".to_string()
639 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
640 for _ in 0..route.paths.len() {
641 onion_session_privs.push(entropy_source.get_secure_random_bytes());
644 let (total_msat, payment_hash, payment_secret, keysend_preimage) = {
645 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
646 match outbounds.get_mut(&payment_id) {
648 let res = match payment {
649 PendingOutboundPayment::Retryable {
650 total_msat, payment_hash, keysend_preimage, payment_secret, pending_amt_msat, ..
652 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
653 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
654 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
655 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()
658 (*total_msat, *payment_hash, *payment_secret, *keysend_preimage)
660 PendingOutboundPayment::Legacy { .. } => {
661 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
662 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
665 PendingOutboundPayment::Fulfilled { .. } => {
666 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
667 err: "Payment already completed".to_owned()
670 PendingOutboundPayment::Abandoned { .. } => {
671 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
672 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
676 if !payment.is_retryable_now() {
677 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
678 err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
681 payment.increment_attempts();
682 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
683 assert!(payment.insert(*session_priv_bytes, path));
688 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
689 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
693 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)
696 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
697 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
698 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
699 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
701 ES::Target: EntropySource,
702 NS::Target: NodeSigner,
703 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
704 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
706 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
708 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
711 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
712 err: "No need probing a path with less than two hops".to_string()
716 let route = Route { paths: vec![hops], payment_params: None };
717 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, None, &route, None, None, entropy_source, best_block_height)?;
719 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) {
720 Ok(()) => Ok((payment_hash, payment_id)),
722 self.remove_outbound_if_all_failed(payment_id, &e);
729 pub(super) fn test_add_new_pending_payment<ES: Deref>(
730 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
731 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
732 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
733 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
736 pub(super) fn add_new_pending_payment<ES: Deref>(
737 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
738 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
739 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
740 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
741 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
742 for _ in 0..route.paths.len() {
743 onion_session_privs.push(entropy_source.get_secure_random_bytes());
746 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
747 match pending_outbounds.entry(payment_id) {
748 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
749 hash_map::Entry::Vacant(entry) => {
750 let payment = entry.insert(PendingOutboundPayment::Retryable {
752 attempts: PaymentAttempts::new(),
754 session_privs: HashSet::new(),
756 pending_fee_msat: Some(0),
760 starting_block_height: best_block_height,
761 total_msat: route.get_total_amount(),
764 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
765 assert!(payment.insert(*session_priv_bytes, path));
768 Ok(onion_session_privs)
773 fn pay_route_internal<NS: Deref, F>(
774 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
775 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
776 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
777 send_payment_along_path: &F
778 ) -> Result<(), PaymentSendFailure>
780 NS::Target: NodeSigner,
781 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
782 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
784 if route.paths.len() < 1 {
785 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
787 if payment_secret.is_none() && route.paths.len() > 1 {
788 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
790 let mut total_value = 0;
791 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
792 let mut path_errs = Vec::with_capacity(route.paths.len());
793 'path_check: for path in route.paths.iter() {
794 if path.len() < 1 || path.len() > 20 {
795 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
796 continue 'path_check;
798 for (idx, hop) in path.iter().enumerate() {
799 if idx != path.len() - 1 && hop.pubkey == our_node_id {
800 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
801 continue 'path_check;
804 total_value += path.last().unwrap().fee_msat;
805 path_errs.push(Ok(()));
807 if path_errs.iter().any(|e| e.is_err()) {
808 return Err(PaymentSendFailure::PathParameterError(path_errs));
810 if let Some(amt_msat) = recv_value_msat {
811 debug_assert!(amt_msat >= total_value);
812 total_value = amt_msat;
815 let cur_height = best_block_height + 1;
816 let mut results = Vec::new();
817 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
818 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
819 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);
822 Err(APIError::MonitorUpdateInProgress) => {
823 // While a MonitorUpdateInProgress is an Err(_), the payment is still
824 // considered "in flight" and we shouldn't remove it from the
825 // PendingOutboundPayment set.
828 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
829 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
830 let removed = payment.remove(&session_priv, Some(path));
831 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
833 debug_assert!(false, "This can't happen as the payment was added by callers");
834 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
838 results.push(path_res);
840 let mut has_ok = false;
841 let mut has_err = false;
842 let mut pending_amt_unsent = 0;
843 let mut max_unsent_cltv_delta = 0;
844 for (res, path) in results.iter().zip(route.paths.iter()) {
845 if res.is_ok() { has_ok = true; }
846 if res.is_err() { has_err = true; }
847 if let &Err(APIError::MonitorUpdateInProgress) = res {
848 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
852 } else if res.is_err() {
853 pending_amt_unsent += path.last().unwrap().fee_msat;
854 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
857 if has_err && has_ok {
858 Err(PaymentSendFailure::PartialFailure {
861 failed_paths_retry: if pending_amt_unsent != 0 {
862 if let Some(payment_params) = &route.payment_params {
863 Some(RouteParameters {
864 payment_params: payment_params.clone(),
865 final_value_msat: pending_amt_unsent,
866 final_cltv_expiry_delta:
867 if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
868 else { max_unsent_cltv_delta },
874 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
881 pub(super) fn test_send_payment_internal<NS: Deref, F>(
882 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
883 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
884 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
885 send_payment_along_path: F
886 ) -> Result<(), PaymentSendFailure>
888 NS::Target: NodeSigner,
889 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
890 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
892 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
893 recv_value_msat, onion_session_privs, node_signer, best_block_height,
894 &send_payment_along_path)
895 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
898 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
899 // map as the payment is free to be resent.
900 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
901 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
902 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
903 debug_assert!(removed, "We should always have a pending payment to remove here");
907 pub(super) fn claim_htlc<L: Deref>(
908 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
909 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
910 ) where L::Target: Logger {
911 let mut session_priv_bytes = [0; 32];
912 session_priv_bytes.copy_from_slice(&session_priv[..]);
913 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
914 let mut pending_events = pending_events.lock().unwrap();
915 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
916 if !payment.get().is_fulfilled() {
917 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
918 let fee_paid_msat = payment.get().get_pending_fee_msat();
920 events::Event::PaymentSent {
921 payment_id: Some(payment_id),
927 payment.get_mut().mark_fulfilled();
931 // We currently immediately remove HTLCs which were fulfilled on-chain.
932 // This could potentially lead to removing a pending payment too early,
933 // with a reorg of one block causing us to re-add the fulfilled payment on
935 // TODO: We should have a second monitor event that informs us of payments
936 // irrevocably fulfilled.
937 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
938 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
940 events::Event::PaymentPathSuccessful {
949 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
953 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
954 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
955 let mut pending_events = pending_events.lock().unwrap();
956 for source in sources {
957 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
958 let mut session_priv_bytes = [0; 32];
959 session_priv_bytes.copy_from_slice(&session_priv[..]);
960 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
961 assert!(payment.get().is_fulfilled());
962 if payment.get_mut().remove(&session_priv_bytes, None) {
964 events::Event::PaymentPathSuccessful {
966 payment_hash: payment.get().payment_hash(),
976 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
977 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
978 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
979 // this could race the user making a duplicate send_payment call and our idempotency
980 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
981 // removal. This should be more than sufficient to ensure the idempotency of any
982 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
984 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
985 let pending_events = pending_events.lock().unwrap();
986 pending_outbound_payments.retain(|payment_id, payment| {
987 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
988 let mut no_remaining_entries = session_privs.is_empty();
989 if no_remaining_entries {
990 for ev in pending_events.iter() {
992 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
993 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
994 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
995 if payment_id == ev_payment_id {
996 no_remaining_entries = false;
1004 if no_remaining_entries {
1005 *timer_ticks_without_htlcs += 1;
1006 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1008 *timer_ticks_without_htlcs = 0;
1015 pub(super) fn fail_htlc<L: Deref>(
1016 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1017 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
1018 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
1019 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1020 ) where L::Target: Logger {
1022 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1024 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1026 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1027 let mut session_priv_bytes = [0; 32];
1028 session_priv_bytes.copy_from_slice(&session_priv[..]);
1029 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1031 // If any payments already need retry, there's no need to generate a redundant
1032 // `PendingHTLCsForwardable`.
1033 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1034 let mut awaiting_retry = false;
1035 if pmt.is_auto_retryable_now() {
1036 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1037 if pending_amt_msat < total_msat {
1038 awaiting_retry = true;
1045 let mut all_paths_failed = false;
1046 let mut full_failure_ev = None;
1047 let mut pending_retry_ev = None;
1048 let mut retry = None;
1049 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1050 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1051 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1054 if payment.get().is_fulfilled() {
1055 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1058 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1059 if let Some(scid) = short_channel_id {
1060 payment.get_mut().insert_previously_failed_scid(scid);
1063 // We want to move towards only using the `PaymentParameters` in the outbound payments
1064 // map. However, for backwards-compatibility, we still need to support passing the
1065 // `PaymentParameters` data that was shoved in the HTLC (and given to us via
1066 // `payment_params`) back to the user.
1067 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
1068 if let Some(params) = payment.get_mut().payment_parameters() {
1069 if params.final_cltv_expiry_delta.is_none() {
1070 // This should be rare, but a user could provide None for the payment data, and
1071 // we need it when we go to retry the payment, so fill it in.
1072 params.final_cltv_expiry_delta = Some(path_last_hop.cltv_expiry_delta);
1074 retry = Some(RouteParameters {
1075 payment_params: params.clone(),
1076 final_value_msat: path_last_hop.fee_msat,
1077 final_cltv_expiry_delta: params.final_cltv_expiry_delta.unwrap(),
1079 } else if let Some(params) = payment_params {
1080 retry = Some(RouteParameters {
1081 payment_params: params.clone(),
1082 final_value_msat: path_last_hop.fee_msat,
1083 final_cltv_expiry_delta:
1084 if let Some(delta) = params.final_cltv_expiry_delta { delta }
1085 else { path_last_hop.cltv_expiry_delta },
1089 if payment_is_probe || !is_retryable_now || !payment_retryable || retry.is_none() {
1090 let _ = payment.get_mut().mark_abandoned(); // we'll only Err if it's a legacy payment
1091 is_retryable_now = false;
1093 if payment.get().remaining_parts() == 0 {
1094 all_paths_failed = true;
1095 if payment.get().abandoned() {
1096 if !payment_is_probe {
1097 full_failure_ev = Some(events::Event::PaymentFailed {
1098 payment_id: *payment_id,
1099 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1107 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1110 core::mem::drop(outbounds);
1111 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1113 let path_failure = {
1114 if payment_is_probe {
1115 if !payment_retryable {
1116 events::Event::ProbeSuccessful {
1117 payment_id: *payment_id,
1118 payment_hash: payment_hash.clone(),
1122 events::Event::ProbeFailed {
1123 payment_id: *payment_id,
1124 payment_hash: payment_hash.clone(),
1130 // TODO: If we decided to blame ourselves (or one of our channels) in
1131 // process_onion_failure we should close that channel as it implies our
1132 // next-hop is needlessly blaming us!
1133 if let Some(scid) = short_channel_id {
1134 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1136 // If we miss abandoning the payment above, we *must* generate an event here or else the
1137 // payment will sit in our outbounds forever.
1138 if attempts_remaining && !already_awaiting_retry {
1139 debug_assert!(full_failure_ev.is_none());
1140 pending_retry_ev = Some(events::Event::PendingHTLCsForwardable {
1141 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
1144 events::Event::PaymentPathFailed {
1145 payment_id: Some(*payment_id),
1146 payment_hash: payment_hash.clone(),
1147 payment_failed_permanently: !payment_retryable,
1154 error_code: onion_error_code,
1156 error_data: onion_error_data
1160 let mut pending_events = pending_events.lock().unwrap();
1161 pending_events.push(path_failure);
1162 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1163 if let Some(ev) = pending_retry_ev { pending_events.push(ev); }
1166 pub(super) fn abandon_payment(
1167 &self, payment_id: PaymentId, pending_events: &Mutex<Vec<events::Event>>
1169 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1170 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1171 if let Ok(()) = payment.get_mut().mark_abandoned() {
1172 if payment.get().remaining_parts() == 0 {
1173 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1175 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1184 pub fn has_pending_payments(&self) -> bool {
1185 !self.pending_outbound_payments.lock().unwrap().is_empty()
1189 pub fn clear_pending_payments(&self) {
1190 self.pending_outbound_payments.lock().unwrap().clear()
1194 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1196 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1197 probing_cookie_secret: [u8; 32]) -> bool
1199 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1200 target_payment_hash == *payment_hash
1203 /// Returns the 'probing cookie' for the given [`PaymentId`].
1204 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1205 let mut preimage = [0u8; 64];
1206 preimage[..32].copy_from_slice(&probing_cookie_secret);
1207 preimage[32..].copy_from_slice(&payment_id.0);
1208 PaymentHash(Sha256::hash(&preimage).into_inner())
1211 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1213 (0, session_privs, required),
1216 (0, session_privs, required),
1217 (1, payment_hash, option),
1218 (3, timer_ticks_without_htlcs, (default_value, 0)),
1221 (0, session_privs, required),
1222 (1, pending_fee_msat, option),
1223 (2, payment_hash, required),
1224 (3, payment_params, option),
1225 (4, payment_secret, option),
1226 (5, keysend_preimage, option),
1227 (6, total_msat, required),
1228 (8, pending_amt_msat, required),
1229 (10, starting_block_height, required),
1230 (not_written, retry_strategy, (static_value, None)),
1231 (not_written, attempts, (static_value, PaymentAttempts::new())),
1234 (0, session_privs, required),
1235 (2, payment_hash, required),
1241 use bitcoin::blockdata::constants::genesis_block;
1242 use bitcoin::network::constants::Network;
1243 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1245 use crate::ln::PaymentHash;
1246 use crate::ln::channelmanager::{PaymentId, PaymentSendFailure};
1247 use crate::ln::msgs::{ErrorAction, LightningError};
1248 use crate::ln::outbound_payment::{OutboundPayments, Retry};
1249 use crate::routing::gossip::NetworkGraph;
1250 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
1251 use crate::sync::{Arc, Mutex};
1252 use crate::util::errors::APIError;
1253 use crate::util::test_utils;
1256 #[cfg(feature = "std")]
1257 fn fails_paying_after_expiration() {
1258 do_fails_paying_after_expiration(false);
1259 do_fails_paying_after_expiration(true);
1261 #[cfg(feature = "std")]
1262 fn do_fails_paying_after_expiration(on_retry: bool) {
1263 let outbound_payments = OutboundPayments::new();
1264 let logger = test_utils::TestLogger::new();
1265 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1266 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1267 let scorer = Mutex::new(test_utils::TestScorer::new());
1268 let router = test_utils::TestRouter::new(network_graph, &scorer);
1269 let secp_ctx = Secp256k1::new();
1270 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1272 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1273 let payment_params = PaymentParameters::from_node_id(
1274 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1276 ).with_expiry_time(past_expiry_time);
1277 let expired_route_params = RouteParameters {
1279 final_value_msat: 0,
1280 final_cltv_expiry_delta: 0,
1282 let err = if on_retry {
1283 outbound_payments.pay_internal(
1284 PaymentId([0; 32]), None, expired_route_params, &&router, vec![], &|| InFlightHtlcs::new(),
1285 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1287 outbound_payments.send_payment(
1288 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1289 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1290 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1292 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1293 assert!(err.contains("Invoice expired"));
1294 } else { panic!("Unexpected error"); }
1298 fn find_route_error() {
1299 do_find_route_error(false);
1300 do_find_route_error(true);
1302 fn do_find_route_error(on_retry: bool) {
1303 let outbound_payments = OutboundPayments::new();
1304 let logger = test_utils::TestLogger::new();
1305 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1306 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1307 let scorer = Mutex::new(test_utils::TestScorer::new());
1308 let router = test_utils::TestRouter::new(network_graph, &scorer);
1309 let secp_ctx = Secp256k1::new();
1310 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1312 let payment_params = PaymentParameters::from_node_id(
1313 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1314 let route_params = RouteParameters {
1316 final_value_msat: 0,
1317 final_cltv_expiry_delta: 0,
1319 router.expect_find_route(route_params.clone(),
1320 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1322 let err = if on_retry {
1323 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]), None,
1324 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
1325 Some(route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
1326 outbound_payments.pay_internal(
1327 PaymentId([0; 32]), None, route_params, &&router, vec![], &|| InFlightHtlcs::new(),
1328 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1330 outbound_payments.send_payment(
1331 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1332 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1333 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1335 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1336 assert!(err.contains("Failed to find a route"));
1337 } else { panic!("Unexpected error"); }