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::sign::{EntropySource, NodeSigner, Recipient};
17 use crate::events::{self, PaymentFailureReason};
18 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::channelmanager::{ChannelDetails, EventCompletionAction, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
22 use crate::util::errors::APIError;
23 use crate::util::logger::Logger;
24 use crate::util::time::Time;
25 #[cfg(all(not(feature = "no-std"), test))]
26 use crate::util::time::tests::SinceEpoch;
27 use crate::util::ser::ReadableArgs;
29 use core::fmt::{self, Display, Formatter};
32 use crate::prelude::*;
33 use crate::sync::Mutex;
35 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
36 /// and later, also stores information for retrying the payment.
37 pub(crate) enum PendingOutboundPayment {
39 session_privs: HashSet<[u8; 32]>,
42 retry_strategy: Option<Retry>,
43 attempts: PaymentAttempts,
44 payment_params: Option<PaymentParameters>,
45 session_privs: HashSet<[u8; 32]>,
46 payment_hash: PaymentHash,
47 payment_secret: Option<PaymentSecret>,
48 payment_metadata: Option<Vec<u8>>,
49 keysend_preimage: Option<PaymentPreimage>,
50 pending_amt_msat: u64,
51 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
52 pending_fee_msat: Option<u64>,
53 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
55 /// Our best known block height at the time this payment was initiated.
56 starting_block_height: u32,
58 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
59 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
60 /// and add a pending payment that was already fulfilled.
62 session_privs: HashSet<[u8; 32]>,
63 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
64 payment_hash: Option<PaymentHash>,
65 timer_ticks_without_htlcs: u8,
67 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
68 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
70 session_privs: HashSet<[u8; 32]>,
71 payment_hash: PaymentHash,
72 /// Will be `None` if the payment was serialized before 0.0.115.
73 reason: Option<PaymentFailureReason>,
77 impl PendingOutboundPayment {
78 fn increment_attempts(&mut self) {
79 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
83 fn is_auto_retryable_now(&self) -> bool {
85 PendingOutboundPayment::Retryable {
86 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
88 strategy.is_retryable_now(&attempts)
93 fn is_retryable_now(&self) -> bool {
95 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
96 // We're handling retries manually, we can always retry.
99 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
100 strategy.is_retryable_now(&attempts)
105 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
106 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
107 params.previously_failed_channels.push(scid);
110 pub(super) fn is_fulfilled(&self) -> bool {
112 PendingOutboundPayment::Fulfilled { .. } => true,
116 pub(super) fn abandoned(&self) -> bool {
118 PendingOutboundPayment::Abandoned { .. } => true,
122 fn get_pending_fee_msat(&self) -> Option<u64> {
124 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
129 fn payment_hash(&self) -> Option<PaymentHash> {
131 PendingOutboundPayment::Legacy { .. } => None,
132 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
133 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
134 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
138 fn mark_fulfilled(&mut self) {
139 let mut session_privs = HashSet::new();
140 core::mem::swap(&mut session_privs, match self {
141 PendingOutboundPayment::Legacy { session_privs } |
142 PendingOutboundPayment::Retryable { session_privs, .. } |
143 PendingOutboundPayment::Fulfilled { session_privs, .. } |
144 PendingOutboundPayment::Abandoned { session_privs, .. }
147 let payment_hash = self.payment_hash();
148 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
151 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
152 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
153 let mut our_session_privs = HashSet::new();
154 core::mem::swap(&mut our_session_privs, session_privs);
155 *self = PendingOutboundPayment::Abandoned {
156 session_privs: our_session_privs,
157 payment_hash: *payment_hash,
163 /// panics if path is None and !self.is_fulfilled
164 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
165 let remove_res = match self {
166 PendingOutboundPayment::Legacy { session_privs } |
167 PendingOutboundPayment::Retryable { session_privs, .. } |
168 PendingOutboundPayment::Fulfilled { session_privs, .. } |
169 PendingOutboundPayment::Abandoned { session_privs, .. } => {
170 session_privs.remove(session_priv)
174 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
175 let path = path.expect("Fulfilling a payment should always come with a path");
176 *pending_amt_msat -= path.final_value_msat();
177 if let Some(fee_msat) = pending_fee_msat.as_mut() {
178 *fee_msat -= path.fee_msat();
185 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
186 let insert_res = match self {
187 PendingOutboundPayment::Legacy { session_privs } |
188 PendingOutboundPayment::Retryable { session_privs, .. } => {
189 session_privs.insert(session_priv)
191 PendingOutboundPayment::Fulfilled { .. } => false,
192 PendingOutboundPayment::Abandoned { .. } => false,
195 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
196 *pending_amt_msat += path.final_value_msat();
197 if let Some(fee_msat) = pending_fee_msat.as_mut() {
198 *fee_msat += path.fee_msat();
205 pub(super) fn remaining_parts(&self) -> usize {
207 PendingOutboundPayment::Legacy { session_privs } |
208 PendingOutboundPayment::Retryable { session_privs, .. } |
209 PendingOutboundPayment::Fulfilled { session_privs, .. } |
210 PendingOutboundPayment::Abandoned { session_privs, .. } => {
217 /// Strategies available to retry payment path failures.
218 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
220 /// Max number of attempts to retry payment.
222 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
223 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
224 /// were retried along a route from a single call to [`Router::find_route_with_id`].
226 #[cfg(not(feature = "no-std"))]
227 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
228 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
230 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
231 Timeout(core::time::Duration),
235 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
236 match (self, attempts) {
237 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
238 max_retry_count > count
240 #[cfg(all(not(feature = "no-std"), not(test)))]
241 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
242 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
243 #[cfg(all(not(feature = "no-std"), test))]
244 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
245 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
250 #[cfg(feature = "std")]
251 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
252 if let Some(expiry_time) = route_params.payment_params.expiry_time {
253 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
254 return elapsed > core::time::Duration::from_secs(expiry_time)
260 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
262 /// Storing minimal payment attempts information required for determining if a outbound payment can
264 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
265 /// This count will be incremented only after the result of the attempt is known. When it's 0,
266 /// it means the result of the first attempt is not known yet.
267 pub(crate) count: usize,
268 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
269 #[cfg(not(feature = "no-std"))]
270 first_attempted_at: T,
271 #[cfg(feature = "no-std")]
272 phantom: core::marker::PhantomData<T>,
276 #[cfg(not(any(feature = "no-std", test)))]
277 type ConfiguredTime = std::time::Instant;
278 #[cfg(feature = "no-std")]
279 type ConfiguredTime = crate::util::time::Eternity;
280 #[cfg(all(not(feature = "no-std"), test))]
281 type ConfiguredTime = SinceEpoch;
283 impl<T: Time> PaymentAttemptsUsingTime<T> {
284 pub(crate) fn new() -> Self {
285 PaymentAttemptsUsingTime {
287 #[cfg(not(feature = "no-std"))]
288 first_attempted_at: T::now(),
289 #[cfg(feature = "no-std")]
290 phantom: core::marker::PhantomData,
295 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
296 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
297 #[cfg(feature = "no-std")]
298 return write!(f, "attempts: {}", self.count);
299 #[cfg(not(feature = "no-std"))]
302 "attempts: {}, duration: {}s",
304 T::now().duration_since(self.first_attempted_at).as_secs()
309 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
310 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
312 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
313 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
314 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
315 #[derive(Clone, Debug, PartialEq, Eq)]
316 pub enum RetryableSendFailure {
317 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
318 /// that this error is *not* caused by [`Retry::Timeout`].
320 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
322 /// We were unable to find a route to the destination.
324 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
325 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
327 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
328 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
329 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
333 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
334 /// of several states. This enum is returned as the Err() type describing which state the payment
335 /// is in, see the description of individual enum states for more.
337 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
338 #[derive(Clone, Debug)]
339 pub enum PaymentSendFailure {
340 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
341 /// send the payment at all.
343 /// You can freely resend the payment in full (with the parameter error fixed).
345 /// Because the payment failed outright, no payment tracking is done and no
346 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
348 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
349 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
350 ParameterError(APIError),
351 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
352 /// from attempting to send the payment at all.
354 /// You can freely resend the payment in full (with the parameter error fixed).
356 /// Because the payment failed outright, no payment tracking is done and no
357 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
359 /// The results here are ordered the same as the paths in the route object which was passed to
362 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
363 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
364 PathParameterError(Vec<Result<(), APIError>>),
365 /// All paths which were attempted failed to send, with no channel state change taking place.
366 /// You can freely resend the payment in full (though you probably want to do so over different
367 /// paths than the ones selected).
369 /// Because the payment failed outright, no payment tracking is done and no
370 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
372 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
373 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
374 AllFailedResendSafe(Vec<APIError>),
375 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
376 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
378 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
379 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
380 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
382 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
383 /// some paths have irrevocably committed to the HTLC.
385 /// The results here are ordered the same as the paths in the route object that was passed to
388 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
389 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
391 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
393 /// The errors themselves, in the same order as the paths from the route.
394 results: Vec<Result<(), APIError>>,
395 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
396 /// contain a [`RouteParameters`] object for the failing paths.
397 failed_paths_retry: Option<RouteParameters>,
398 /// The payment id for the payment, which is now at least partially pending.
399 payment_id: PaymentId,
403 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
405 /// This should generally be constructed with data communicated to us from the recipient (via a
406 /// BOLT11 or BOLT12 invoice).
407 #[derive(Clone, Debug, PartialEq, Eq)]
408 pub struct RecipientOnionFields {
409 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
410 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
411 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
414 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
415 /// multi-path payments require a recipient-provided secret.
417 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
418 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
419 /// recipient will not reject it.
420 pub payment_secret: Option<PaymentSecret>,
421 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
422 /// arbitrary length. This gives recipients substantially more flexibility to receive
425 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
426 /// scheme to authenticate received payments against expected payments and invoices, this field
427 /// is not used in LDK for received payments, and can be used to store arbitrary data in
428 /// invoices which will be received with the payment.
430 /// Note that this field was added to the lightning specification more recently than
431 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
432 /// may not be supported as universally.
433 pub payment_metadata: Option<Vec<u8>>,
436 impl_writeable_tlv_based!(RecipientOnionFields, {
437 (0, payment_secret, option),
438 (2, payment_metadata, option),
441 impl RecipientOnionFields {
442 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
443 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
444 /// but do not require or provide any further data.
445 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
446 Self { payment_secret: Some(payment_secret), payment_metadata: None }
449 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
450 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
451 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
452 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
453 /// instead want to use [`RecipientOnionFields::secret_only`].
455 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
456 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
457 pub fn spontaneous_empty() -> Self {
458 Self { payment_secret: None, payment_metadata: None }
461 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
462 /// have to make sure that some fields match exactly across the parts. For those that aren't
463 /// required to match, if they don't match we should remove them so as to not expose data
464 /// that's dependent on the HTLC receive order to users.
466 /// Here we implement this, first checking compatibility then mutating two objects and then
467 /// dropping any remaining non-matching fields from both.
468 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
469 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
470 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
471 // For custom TLVs we should just drop non-matching ones, but not reject the payment.
476 pub(super) struct OutboundPayments {
477 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
478 pub(super) retry_lock: Mutex<()>,
481 impl OutboundPayments {
482 pub(super) fn new() -> Self {
484 pending_outbound_payments: Mutex::new(HashMap::new()),
485 retry_lock: Mutex::new(()),
489 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
490 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
491 retry_strategy: Retry, route_params: RouteParameters, router: &R,
492 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
493 node_signer: &NS, best_block_height: u32, logger: &L,
494 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
495 ) -> Result<(), RetryableSendFailure>
498 ES::Target: EntropySource,
499 NS::Target: NodeSigner,
501 IH: Fn() -> InFlightHtlcs,
502 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
503 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
505 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
506 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
507 best_block_height, logger, pending_events, &send_payment_along_path)
510 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
511 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
512 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
513 send_payment_along_path: F
514 ) -> Result<(), PaymentSendFailure>
516 ES::Target: EntropySource,
517 NS::Target: NodeSigner,
518 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
519 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
521 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(), payment_id, None, route, None, None, entropy_source, best_block_height)?;
522 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
523 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
524 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
527 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
528 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
529 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
530 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
531 node_signer: &NS, best_block_height: u32, logger: &L,
532 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
533 ) -> Result<PaymentHash, RetryableSendFailure>
536 ES::Target: EntropySource,
537 NS::Target: NodeSigner,
539 IH: Fn() -> InFlightHtlcs,
540 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
541 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
543 let preimage = payment_preimage
544 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
545 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
546 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
547 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
548 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
549 .map(|()| payment_hash)
552 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
553 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
554 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
555 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
556 ) -> Result<PaymentHash, PaymentSendFailure>
558 ES::Target: EntropySource,
559 NS::Target: NodeSigner,
560 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
561 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
563 let preimage = payment_preimage
564 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
565 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
566 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
567 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
569 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
570 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
572 Ok(()) => Ok(payment_hash),
574 self.remove_outbound_if_all_failed(payment_id, &e);
580 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
581 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
582 best_block_height: u32,
583 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
584 send_payment_along_path: SP,
588 ES::Target: EntropySource,
589 NS::Target: NodeSigner,
590 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
591 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
592 IH: Fn() -> InFlightHtlcs,
593 FH: Fn() -> Vec<ChannelDetails>,
596 let _single_thread = self.retry_lock.lock().unwrap();
598 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
599 let mut retry_id_route_params = None;
600 for (pmt_id, pmt) in outbounds.iter_mut() {
601 if pmt.is_auto_retryable_now() {
602 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
603 if pending_amt_msat < total_msat {
604 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
605 final_value_msat: *total_msat - *pending_amt_msat,
606 payment_params: params.clone(),
610 } else { debug_assert!(false); }
613 core::mem::drop(outbounds);
614 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
615 self.retry_payment_internal(payment_hash, payment_id, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
619 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
620 outbounds.retain(|pmt_id, pmt| {
621 let mut retain = true;
622 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
623 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
624 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
625 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
627 payment_hash: *payment_hash,
637 pub(super) fn needs_abandon(&self) -> bool {
638 let outbounds = self.pending_outbound_payments.lock().unwrap();
639 outbounds.iter().any(|(_, pmt)|
640 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
643 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
644 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
646 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
647 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
648 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
649 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
650 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
651 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
652 node_signer: &NS, best_block_height: u32, logger: &L,
653 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
654 ) -> Result<(), RetryableSendFailure>
657 ES::Target: EntropySource,
658 NS::Target: NodeSigner,
660 IH: Fn() -> InFlightHtlcs,
661 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
662 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
664 #[cfg(feature = "std")] {
665 if has_expired(&route_params) {
666 return Err(RetryableSendFailure::PaymentExpired)
670 let route = router.find_route_with_id(
671 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
672 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
673 payment_hash, payment_id,
674 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
676 let onion_session_privs = self.add_new_pending_payment(payment_hash,
677 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
678 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
679 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
681 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, None, payment_id, None,
682 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
683 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
684 if let Err(e) = res {
685 self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path);
690 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
691 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
692 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
693 node_signer: &NS, best_block_height: u32, logger: &L,
694 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
698 ES::Target: EntropySource,
699 NS::Target: NodeSigner,
701 IH: Fn() -> InFlightHtlcs,
702 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
703 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
705 #[cfg(feature = "std")] {
706 if has_expired(&route_params) {
707 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
708 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
713 let route = match router.find_route_with_id(
714 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
715 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
716 payment_hash, payment_id,
720 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
721 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
725 for path in route.paths.iter() {
726 if path.hops.len() == 0 {
727 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
728 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
733 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
734 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
735 for _ in 0..route.paths.len() {
736 onion_session_privs.push(entropy_source.get_secure_random_bytes());
739 macro_rules! abandon_with_entry {
740 ($payment: expr, $reason: expr) => {
741 $payment.get_mut().mark_abandoned($reason);
742 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
743 if $payment.get().remaining_parts() == 0 {
744 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
754 let (total_msat, recipient_onion, keysend_preimage) = {
755 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
756 match outbounds.entry(payment_id) {
757 hash_map::Entry::Occupied(mut payment) => {
758 let res = match payment.get() {
759 PendingOutboundPayment::Retryable {
760 total_msat, keysend_preimage, payment_secret, payment_metadata, pending_amt_msat, ..
762 let retry_amt_msat = route.get_total_amount();
763 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
764 log_error!(logger, "retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat);
765 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
768 (*total_msat, RecipientOnionFields {
769 payment_secret: *payment_secret,
770 payment_metadata: payment_metadata.clone(),
771 }, *keysend_preimage)
773 PendingOutboundPayment::Legacy { .. } => {
774 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
777 PendingOutboundPayment::Fulfilled { .. } => {
778 log_error!(logger, "Payment already completed");
781 PendingOutboundPayment::Abandoned { .. } => {
782 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
786 if !payment.get().is_retryable_now() {
787 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
788 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
791 payment.get_mut().increment_attempts();
792 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
793 assert!(payment.get_mut().insert(*session_priv_bytes, path));
797 hash_map::Entry::Vacant(_) => {
798 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
803 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
804 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
805 &send_payment_along_path);
806 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
807 if let Err(e) = res {
808 self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
812 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
813 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
814 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
815 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
816 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
820 ES::Target: EntropySource,
821 NS::Target: NodeSigner,
823 IH: Fn() -> InFlightHtlcs,
824 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
825 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
828 PaymentSendFailure::AllFailedResendSafe(errs) => {
829 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, errs.into_iter().map(|e| Err(e)), logger, pending_events);
830 self.retry_payment_internal(payment_hash, payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
832 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
833 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
834 // Some paths were sent, even if we failed to send the full MPP value our recipient may
835 // misbehave and claim the funds, at which point we have to consider the payment sent, so
836 // return `Ok()` here, ignoring any retry errors.
837 self.retry_payment_internal(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
839 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
840 // This may happen if we send a payment and some paths fail, but only due to a temporary
841 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
842 // initial HTLC-Add messages yet.
844 PaymentSendFailure::PathParameterError(results) => {
845 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
846 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
847 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
849 PaymentSendFailure::ParameterError(e) => {
850 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
851 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
853 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
857 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
858 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
859 paths: Vec<Path>, path_results: I, logger: &L,
860 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
861 ) where L::Target: Logger {
862 let mut events = pending_events.lock().unwrap();
863 debug_assert_eq!(paths.len(), path_results.len());
864 for (path, path_res) in paths.into_iter().zip(path_results) {
865 if let Err(e) = path_res {
866 if let APIError::MonitorUpdateInProgress = e { continue }
867 log_error!(logger, "Failed to send along path due to error: {:?}", e);
868 let mut failed_scid = None;
869 if let APIError::ChannelUnavailable { .. } = e {
870 let scid = path.hops[0].short_channel_id;
871 failed_scid = Some(scid);
872 route_params.payment_params.previously_failed_channels.push(scid);
874 events.push_back((events::Event::PaymentPathFailed {
875 payment_id: Some(payment_id),
877 payment_failed_permanently: false,
878 failure: events::PathFailure::InitialSend { err: e },
880 short_channel_id: failed_scid,
890 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
891 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
892 best_block_height: u32, send_payment_along_path: F
893 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
895 ES::Target: EntropySource,
896 NS::Target: NodeSigner,
897 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
898 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
900 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
902 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
904 if path.hops.len() < 2 && path.blinded_tail.is_none() {
905 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
906 err: "No need probing a path with less than two hops".to_string()
910 let route = Route { paths: vec![path], payment_params: None };
911 let onion_session_privs = self.add_new_pending_payment(payment_hash,
912 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
913 entropy_source, best_block_height)?;
915 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
916 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
918 Ok(()) => Ok((payment_hash, payment_id)),
920 self.remove_outbound_if_all_failed(payment_id, &e);
927 pub(super) fn test_set_payment_metadata(
928 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
930 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
931 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
932 *payment_metadata = new_payment_metadata;
934 _ => panic!("Need a retryable payment to update metadata on"),
939 pub(super) fn test_add_new_pending_payment<ES: Deref>(
940 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
941 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
942 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
943 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
946 pub(super) fn add_new_pending_payment<ES: Deref>(
947 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
948 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
949 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
950 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
951 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
952 for _ in 0..route.paths.len() {
953 onion_session_privs.push(entropy_source.get_secure_random_bytes());
956 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
957 match pending_outbounds.entry(payment_id) {
958 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
959 hash_map::Entry::Vacant(entry) => {
960 let payment = entry.insert(PendingOutboundPayment::Retryable {
962 attempts: PaymentAttempts::new(),
964 session_privs: HashSet::new(),
966 pending_fee_msat: Some(0),
968 payment_secret: recipient_onion.payment_secret,
969 payment_metadata: recipient_onion.payment_metadata,
971 starting_block_height: best_block_height,
972 total_msat: route.get_total_amount(),
975 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
976 assert!(payment.insert(*session_priv_bytes, path));
979 Ok(onion_session_privs)
984 fn pay_route_internal<NS: Deref, F>(
985 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
986 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
987 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
988 send_payment_along_path: &F
989 ) -> Result<(), PaymentSendFailure>
991 NS::Target: NodeSigner,
992 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
993 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
995 if route.paths.len() < 1 {
996 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
998 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
999 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1001 let mut total_value = 0;
1002 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1003 let mut path_errs = Vec::with_capacity(route.paths.len());
1004 'path_check: for path in route.paths.iter() {
1005 if path.hops.len() < 1 || path.hops.len() > 20 {
1006 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1007 continue 'path_check;
1009 if path.blinded_tail.is_some() {
1010 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1011 continue 'path_check;
1013 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1014 usize::max_value() } else { path.hops.len() - 1 };
1015 for (idx, hop) in path.hops.iter().enumerate() {
1016 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1017 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1018 continue 'path_check;
1021 total_value += path.final_value_msat();
1022 path_errs.push(Ok(()));
1024 if path_errs.iter().any(|e| e.is_err()) {
1025 return Err(PaymentSendFailure::PathParameterError(path_errs));
1027 if let Some(amt_msat) = recv_value_msat {
1028 total_value = amt_msat;
1031 let cur_height = best_block_height + 1;
1032 let mut results = Vec::new();
1033 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1034 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1035 let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
1036 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
1039 Err(APIError::MonitorUpdateInProgress) => {
1040 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1041 // considered "in flight" and we shouldn't remove it from the
1042 // PendingOutboundPayment set.
1045 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1046 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1047 let removed = payment.remove(&session_priv, Some(path));
1048 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1050 debug_assert!(false, "This can't happen as the payment was added by callers");
1051 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1055 results.push(path_res);
1057 let mut has_ok = false;
1058 let mut has_err = false;
1059 let mut pending_amt_unsent = 0;
1060 for (res, path) in results.iter().zip(route.paths.iter()) {
1061 if res.is_ok() { has_ok = true; }
1062 if res.is_err() { has_err = true; }
1063 if let &Err(APIError::MonitorUpdateInProgress) = res {
1064 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1068 } else if res.is_err() {
1069 pending_amt_unsent += path.final_value_msat();
1072 if has_err && has_ok {
1073 Err(PaymentSendFailure::PartialFailure {
1076 failed_paths_retry: if pending_amt_unsent != 0 {
1077 if let Some(payment_params) = &route.payment_params {
1078 Some(RouteParameters {
1079 payment_params: payment_params.clone(),
1080 final_value_msat: pending_amt_unsent,
1086 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1093 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1094 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1095 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1096 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1097 send_payment_along_path: F
1098 ) -> Result<(), PaymentSendFailure>
1100 NS::Target: NodeSigner,
1101 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1102 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1104 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1105 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1106 &send_payment_along_path)
1107 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1110 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1111 // map as the payment is free to be resent.
1112 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1113 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1114 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1115 debug_assert!(removed, "We should always have a pending payment to remove here");
1119 pub(super) fn claim_htlc<L: Deref>(
1120 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1121 path: Path, from_onchain: bool,
1122 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1124 ) where L::Target: Logger {
1125 let mut session_priv_bytes = [0; 32];
1126 session_priv_bytes.copy_from_slice(&session_priv[..]);
1127 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1128 let mut pending_events = pending_events.lock().unwrap();
1129 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1130 if !payment.get().is_fulfilled() {
1131 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1132 let fee_paid_msat = payment.get().get_pending_fee_msat();
1133 pending_events.push_back((events::Event::PaymentSent {
1134 payment_id: Some(payment_id),
1139 payment.get_mut().mark_fulfilled();
1143 // We currently immediately remove HTLCs which were fulfilled on-chain.
1144 // This could potentially lead to removing a pending payment too early,
1145 // with a reorg of one block causing us to re-add the fulfilled payment on
1147 // TODO: We should have a second monitor event that informs us of payments
1148 // irrevocably fulfilled.
1149 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1150 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1151 pending_events.push_back((events::Event::PaymentPathSuccessful {
1159 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1163 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1164 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1166 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1167 let mut pending_events = pending_events.lock().unwrap();
1168 for source in sources {
1169 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1170 let mut session_priv_bytes = [0; 32];
1171 session_priv_bytes.copy_from_slice(&session_priv[..]);
1172 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1173 assert!(payment.get().is_fulfilled());
1174 if payment.get_mut().remove(&session_priv_bytes, None) {
1175 let payment_hash = payment.get().payment_hash();
1176 debug_assert!(payment_hash.is_some());
1177 pending_events.push_back((events::Event::PaymentPathSuccessful {
1188 pub(super) fn remove_stale_resolved_payments(&self,
1189 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1191 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1192 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1193 // this could race the user making a duplicate send_payment call and our idempotency
1194 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1195 // removal. This should be more than sufficient to ensure the idempotency of any
1196 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1198 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1199 let pending_events = pending_events.lock().unwrap();
1200 pending_outbound_payments.retain(|payment_id, payment| {
1201 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1202 let mut no_remaining_entries = session_privs.is_empty();
1203 if no_remaining_entries {
1204 for (ev, _) in pending_events.iter() {
1206 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1207 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1208 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1209 if payment_id == ev_payment_id {
1210 no_remaining_entries = false;
1218 if no_remaining_entries {
1219 *timer_ticks_without_htlcs += 1;
1220 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1222 *timer_ticks_without_htlcs = 0;
1229 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1230 pub(super) fn fail_htlc<L: Deref>(
1231 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1232 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1233 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1234 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1235 ) -> bool where L::Target: Logger {
1237 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1239 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1241 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1242 let mut session_priv_bytes = [0; 32];
1243 session_priv_bytes.copy_from_slice(&session_priv[..]);
1244 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1246 // If any payments already need retry, there's no need to generate a redundant
1247 // `PendingHTLCsForwardable`.
1248 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1249 let mut awaiting_retry = false;
1250 if pmt.is_auto_retryable_now() {
1251 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1252 if pending_amt_msat < total_msat {
1253 awaiting_retry = true;
1260 let mut full_failure_ev = None;
1261 let mut pending_retry_ev = false;
1262 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1263 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1264 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1267 if payment.get().is_fulfilled() {
1268 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1271 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1272 if let Some(scid) = short_channel_id {
1273 // TODO: If we decided to blame ourselves (or one of our channels) in
1274 // process_onion_failure we should close that channel as it implies our
1275 // next-hop is needlessly blaming us!
1276 payment.get_mut().insert_previously_failed_scid(scid);
1279 if payment_is_probe || !is_retryable_now || !payment_retryable {
1280 let reason = if !payment_retryable {
1281 PaymentFailureReason::RecipientRejected
1283 PaymentFailureReason::RetriesExhausted
1285 payment.get_mut().mark_abandoned(reason);
1286 is_retryable_now = false;
1288 if payment.get().remaining_parts() == 0 {
1289 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1290 if !payment_is_probe {
1291 full_failure_ev = Some(events::Event::PaymentFailed {
1292 payment_id: *payment_id,
1293 payment_hash: *payment_hash,
1302 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1305 core::mem::drop(outbounds);
1306 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1308 let path_failure = {
1309 if payment_is_probe {
1310 if !payment_retryable {
1311 events::Event::ProbeSuccessful {
1312 payment_id: *payment_id,
1313 payment_hash: payment_hash.clone(),
1317 events::Event::ProbeFailed {
1318 payment_id: *payment_id,
1319 payment_hash: payment_hash.clone(),
1325 // If we miss abandoning the payment above, we *must* generate an event here or else the
1326 // payment will sit in our outbounds forever.
1327 if attempts_remaining && !already_awaiting_retry {
1328 debug_assert!(full_failure_ev.is_none());
1329 pending_retry_ev = true;
1331 events::Event::PaymentPathFailed {
1332 payment_id: Some(*payment_id),
1333 payment_hash: payment_hash.clone(),
1334 payment_failed_permanently: !payment_retryable,
1335 failure: events::PathFailure::OnPath { network_update },
1339 error_code: onion_error_code,
1341 error_data: onion_error_data
1345 let mut pending_events = pending_events.lock().unwrap();
1346 pending_events.push_back((path_failure, None));
1347 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1351 pub(super) fn abandon_payment(
1352 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1353 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1355 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1356 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1357 payment.get_mut().mark_abandoned(reason);
1358 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1359 if payment.get().remaining_parts() == 0 {
1360 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1362 payment_hash: *payment_hash,
1372 pub fn has_pending_payments(&self) -> bool {
1373 !self.pending_outbound_payments.lock().unwrap().is_empty()
1377 pub fn clear_pending_payments(&self) {
1378 self.pending_outbound_payments.lock().unwrap().clear()
1382 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1384 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1385 probing_cookie_secret: [u8; 32]) -> bool
1387 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1388 target_payment_hash == *payment_hash
1391 /// Returns the 'probing cookie' for the given [`PaymentId`].
1392 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1393 let mut preimage = [0u8; 64];
1394 preimage[..32].copy_from_slice(&probing_cookie_secret);
1395 preimage[32..].copy_from_slice(&payment_id.0);
1396 PaymentHash(Sha256::hash(&preimage).into_inner())
1399 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1401 (0, session_privs, required),
1404 (0, session_privs, required),
1405 (1, payment_hash, option),
1406 (3, timer_ticks_without_htlcs, (default_value, 0)),
1409 (0, session_privs, required),
1410 (1, pending_fee_msat, option),
1411 (2, payment_hash, required),
1412 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1413 // never see it - `payment_params` was added here after the field was added/required.
1414 (3, payment_params, (option: ReadableArgs, 0)),
1415 (4, payment_secret, option),
1416 (5, keysend_preimage, option),
1417 (6, total_msat, required),
1418 (7, payment_metadata, option),
1419 (8, pending_amt_msat, required),
1420 (10, starting_block_height, required),
1421 (not_written, retry_strategy, (static_value, None)),
1422 (not_written, attempts, (static_value, PaymentAttempts::new())),
1425 (0, session_privs, required),
1426 (1, reason, option),
1427 (2, payment_hash, required),
1433 use bitcoin::network::constants::Network;
1434 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1436 use crate::events::{Event, PathFailure, PaymentFailureReason};
1437 use crate::ln::PaymentHash;
1438 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1439 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1440 use crate::ln::msgs::{ErrorAction, LightningError};
1441 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1442 use crate::routing::gossip::NetworkGraph;
1443 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1444 use crate::sync::{Arc, Mutex};
1445 use crate::util::errors::APIError;
1446 use crate::util::test_utils;
1448 use alloc::collections::VecDeque;
1451 #[cfg(feature = "std")]
1452 fn fails_paying_after_expiration() {
1453 do_fails_paying_after_expiration(false);
1454 do_fails_paying_after_expiration(true);
1456 #[cfg(feature = "std")]
1457 fn do_fails_paying_after_expiration(on_retry: bool) {
1458 let outbound_payments = OutboundPayments::new();
1459 let logger = test_utils::TestLogger::new();
1460 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1461 let scorer = Mutex::new(test_utils::TestScorer::new());
1462 let router = test_utils::TestRouter::new(network_graph, &scorer);
1463 let secp_ctx = Secp256k1::new();
1464 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1466 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1467 let payment_params = PaymentParameters::from_node_id(
1468 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1470 ).with_expiry_time(past_expiry_time);
1471 let expired_route_params = RouteParameters {
1473 final_value_msat: 0,
1475 let pending_events = Mutex::new(VecDeque::new());
1477 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1478 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1479 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1480 &&keys_manager, 0).unwrap();
1481 outbound_payments.retry_payment_internal(
1482 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1483 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1484 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1485 let events = pending_events.lock().unwrap();
1486 assert_eq!(events.len(), 1);
1487 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1488 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1489 } else { panic!("Unexpected event"); }
1491 let err = outbound_payments.send_payment(
1492 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1493 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1494 &&keys_manager, &&keys_manager, 0, &&logger,
1495 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1496 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1501 fn find_route_error() {
1502 do_find_route_error(false);
1503 do_find_route_error(true);
1505 fn do_find_route_error(on_retry: bool) {
1506 let outbound_payments = OutboundPayments::new();
1507 let logger = test_utils::TestLogger::new();
1508 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1509 let scorer = Mutex::new(test_utils::TestScorer::new());
1510 let router = test_utils::TestRouter::new(network_graph, &scorer);
1511 let secp_ctx = Secp256k1::new();
1512 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1514 let payment_params = PaymentParameters::from_node_id(
1515 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1516 let route_params = RouteParameters {
1518 final_value_msat: 0,
1520 router.expect_find_route(route_params.clone(),
1521 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1523 let pending_events = Mutex::new(VecDeque::new());
1525 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1526 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1527 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1528 &&keys_manager, 0).unwrap();
1529 outbound_payments.retry_payment_internal(
1530 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1531 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1532 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1533 let events = pending_events.lock().unwrap();
1534 assert_eq!(events.len(), 1);
1535 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1537 let err = outbound_payments.send_payment(
1538 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1539 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1540 &&keys_manager, &&keys_manager, 0, &&logger,
1541 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1542 if let RetryableSendFailure::RouteNotFound = err {
1543 } else { panic!("Unexpected error"); }
1548 fn initial_send_payment_path_failed_evs() {
1549 let outbound_payments = OutboundPayments::new();
1550 let logger = test_utils::TestLogger::new();
1551 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1552 let scorer = Mutex::new(test_utils::TestScorer::new());
1553 let router = test_utils::TestRouter::new(network_graph, &scorer);
1554 let secp_ctx = Secp256k1::new();
1555 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1557 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1558 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1559 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1560 let route_params = RouteParameters {
1561 payment_params: payment_params.clone(),
1562 final_value_msat: 0,
1564 let failed_scid = 42;
1566 paths: vec![Path { hops: vec![RouteHop {
1567 pubkey: receiver_pk,
1568 node_features: NodeFeatures::empty(),
1569 short_channel_id: failed_scid,
1570 channel_features: ChannelFeatures::empty(),
1572 cltv_expiry_delta: 0,
1573 }], blinded_tail: None }],
1574 payment_params: Some(payment_params),
1576 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1577 let mut route_params_w_failed_scid = route_params.clone();
1578 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1579 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1580 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1581 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1583 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1584 // PaymentPathFailed event.
1585 let pending_events = Mutex::new(VecDeque::new());
1586 outbound_payments.send_payment(
1587 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1588 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1589 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1590 |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1592 let mut events = pending_events.lock().unwrap();
1593 assert_eq!(events.len(), 2);
1594 if let Event::PaymentPathFailed {
1596 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1598 assert_eq!(short_channel_id, Some(failed_scid));
1599 } else { panic!("Unexpected event"); }
1600 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1602 core::mem::drop(events);
1604 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1605 outbound_payments.send_payment(
1606 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1607 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1608 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1609 |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1610 assert_eq!(pending_events.lock().unwrap().len(), 0);
1612 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1613 outbound_payments.send_payment(
1614 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1615 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1616 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1617 |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1619 let events = pending_events.lock().unwrap();
1620 assert_eq!(events.len(), 2);
1621 if let Event::PaymentPathFailed {
1623 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1625 assert_eq!(short_channel_id, None);
1626 } else { panic!("Unexpected event"); }
1627 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }