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)]
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 /// Note that for spontaneous payments most lightning nodes do not currently support MPP
418 /// receives, thus you should generally never be providing a secret here for spontaneous
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 spontaneous payments, i.e. this should generally only be used for
451 /// calls to [`ChannelManager::send_spontaneous_payment`].
453 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
454 pub fn spontaneous_empty() -> Self {
455 Self { payment_secret: None, payment_metadata: None }
458 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
459 /// have to make sure that some fields match exactly across the parts. For those that aren't
460 /// required to match, if they don't match we should remove them so as to not expose data
461 /// that's dependent on the HTLC receive order to users.
463 /// Here we implement this, first checking compatibility then mutating two objects and then
464 /// dropping any remaining non-matching fields from both.
465 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
466 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
467 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
468 // For custom TLVs we should just drop non-matching ones, but not reject the payment.
473 pub(super) struct OutboundPayments {
474 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
475 pub(super) retry_lock: Mutex<()>,
478 impl OutboundPayments {
479 pub(super) fn new() -> Self {
481 pending_outbound_payments: Mutex::new(HashMap::new()),
482 retry_lock: Mutex::new(()),
486 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
487 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
488 retry_strategy: Retry, route_params: RouteParameters, router: &R,
489 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
490 node_signer: &NS, best_block_height: u32, logger: &L,
491 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
492 ) -> Result<(), RetryableSendFailure>
495 ES::Target: EntropySource,
496 NS::Target: NodeSigner,
498 IH: Fn() -> InFlightHtlcs,
499 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
500 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
502 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
503 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
504 best_block_height, logger, pending_events, &send_payment_along_path)
507 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
508 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
509 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
510 send_payment_along_path: F
511 ) -> Result<(), PaymentSendFailure>
513 ES::Target: EntropySource,
514 NS::Target: NodeSigner,
515 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
516 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
518 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)?;
519 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
520 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
521 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
524 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
525 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
526 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
527 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
528 node_signer: &NS, best_block_height: u32, logger: &L,
529 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
530 ) -> Result<PaymentHash, RetryableSendFailure>
533 ES::Target: EntropySource,
534 NS::Target: NodeSigner,
536 IH: Fn() -> InFlightHtlcs,
537 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
538 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
540 let preimage = payment_preimage
541 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
542 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
543 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
544 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
545 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
546 .map(|()| payment_hash)
549 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
550 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
551 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
552 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
553 ) -> Result<PaymentHash, PaymentSendFailure>
555 ES::Target: EntropySource,
556 NS::Target: NodeSigner,
557 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
558 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
560 let preimage = payment_preimage
561 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
562 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
563 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
564 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
566 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
567 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
569 Ok(()) => Ok(payment_hash),
571 self.remove_outbound_if_all_failed(payment_id, &e);
577 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
578 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
579 best_block_height: u32,
580 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
581 send_payment_along_path: SP,
585 ES::Target: EntropySource,
586 NS::Target: NodeSigner,
587 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
588 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
589 IH: Fn() -> InFlightHtlcs,
590 FH: Fn() -> Vec<ChannelDetails>,
593 let _single_thread = self.retry_lock.lock().unwrap();
595 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
596 let mut retry_id_route_params = None;
597 for (pmt_id, pmt) in outbounds.iter_mut() {
598 if pmt.is_auto_retryable_now() {
599 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
600 if pending_amt_msat < total_msat {
601 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
602 final_value_msat: *total_msat - *pending_amt_msat,
603 payment_params: params.clone(),
607 } else { debug_assert!(false); }
610 core::mem::drop(outbounds);
611 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
612 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)
616 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
617 outbounds.retain(|pmt_id, pmt| {
618 let mut retain = true;
619 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
620 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
621 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
622 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
624 payment_hash: *payment_hash,
634 pub(super) fn needs_abandon(&self) -> bool {
635 let outbounds = self.pending_outbound_payments.lock().unwrap();
636 outbounds.iter().any(|(_, pmt)|
637 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
640 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
641 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
643 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
644 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
645 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
646 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
647 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
648 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
649 node_signer: &NS, best_block_height: u32, logger: &L,
650 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
651 ) -> Result<(), RetryableSendFailure>
654 ES::Target: EntropySource,
655 NS::Target: NodeSigner,
657 IH: Fn() -> InFlightHtlcs,
658 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
659 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
661 #[cfg(feature = "std")] {
662 if has_expired(&route_params) {
663 return Err(RetryableSendFailure::PaymentExpired)
667 let route = router.find_route_with_id(
668 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
669 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
670 payment_hash, payment_id,
671 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
673 let onion_session_privs = self.add_new_pending_payment(payment_hash,
674 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
675 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
676 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
678 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, None, payment_id, None,
679 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
680 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
681 if let Err(e) = res {
682 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);
687 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
688 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
689 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
690 node_signer: &NS, best_block_height: u32, logger: &L,
691 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
695 ES::Target: EntropySource,
696 NS::Target: NodeSigner,
698 IH: Fn() -> InFlightHtlcs,
699 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
700 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
702 #[cfg(feature = "std")] {
703 if has_expired(&route_params) {
704 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
705 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
710 let route = match router.find_route_with_id(
711 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
712 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
713 payment_hash, payment_id,
717 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
718 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
722 for path in route.paths.iter() {
723 if path.hops.len() == 0 {
724 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
725 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
730 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
731 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
732 for _ in 0..route.paths.len() {
733 onion_session_privs.push(entropy_source.get_secure_random_bytes());
736 macro_rules! abandon_with_entry {
737 ($payment: expr, $reason: expr) => {
738 $payment.get_mut().mark_abandoned($reason);
739 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
740 if $payment.get().remaining_parts() == 0 {
741 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
751 let (total_msat, recipient_onion, keysend_preimage) = {
752 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
753 match outbounds.entry(payment_id) {
754 hash_map::Entry::Occupied(mut payment) => {
755 let res = match payment.get() {
756 PendingOutboundPayment::Retryable {
757 total_msat, keysend_preimage, payment_secret, payment_metadata, pending_amt_msat, ..
759 let retry_amt_msat = route.get_total_amount();
760 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
761 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);
762 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
765 (*total_msat, RecipientOnionFields {
766 payment_secret: *payment_secret,
767 payment_metadata: payment_metadata.clone(),
768 }, *keysend_preimage)
770 PendingOutboundPayment::Legacy { .. } => {
771 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
774 PendingOutboundPayment::Fulfilled { .. } => {
775 log_error!(logger, "Payment already completed");
778 PendingOutboundPayment::Abandoned { .. } => {
779 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
783 if !payment.get().is_retryable_now() {
784 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
785 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
788 payment.get_mut().increment_attempts();
789 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
790 assert!(payment.get_mut().insert(*session_priv_bytes, path));
794 hash_map::Entry::Vacant(_) => {
795 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
800 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
801 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
802 &send_payment_along_path);
803 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
804 if let Err(e) = res {
805 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);
809 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
810 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
811 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
812 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
813 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
817 ES::Target: EntropySource,
818 NS::Target: NodeSigner,
820 IH: Fn() -> InFlightHtlcs,
821 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
822 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
825 PaymentSendFailure::AllFailedResendSafe(errs) => {
826 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);
827 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);
829 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
830 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
831 // Some paths were sent, even if we failed to send the full MPP value our recipient may
832 // misbehave and claim the funds, at which point we have to consider the payment sent, so
833 // return `Ok()` here, ignoring any retry errors.
834 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);
836 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
837 // This may happen if we send a payment and some paths fail, but only due to a temporary
838 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
839 // initial HTLC-Add messages yet.
841 PaymentSendFailure::PathParameterError(results) => {
842 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
843 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
844 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
846 PaymentSendFailure::ParameterError(e) => {
847 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
848 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
850 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
854 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
855 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
856 paths: Vec<Path>, path_results: I, logger: &L,
857 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
858 ) where L::Target: Logger {
859 let mut events = pending_events.lock().unwrap();
860 debug_assert_eq!(paths.len(), path_results.len());
861 for (path, path_res) in paths.into_iter().zip(path_results) {
862 if let Err(e) = path_res {
863 if let APIError::MonitorUpdateInProgress = e { continue }
864 log_error!(logger, "Failed to send along path due to error: {:?}", e);
865 let mut failed_scid = None;
866 if let APIError::ChannelUnavailable { .. } = e {
867 let scid = path.hops[0].short_channel_id;
868 failed_scid = Some(scid);
869 route_params.payment_params.previously_failed_channels.push(scid);
871 events.push_back((events::Event::PaymentPathFailed {
872 payment_id: Some(payment_id),
874 payment_failed_permanently: false,
875 failure: events::PathFailure::InitialSend { err: e },
877 short_channel_id: failed_scid,
887 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
888 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
889 best_block_height: u32, send_payment_along_path: F
890 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
892 ES::Target: EntropySource,
893 NS::Target: NodeSigner,
894 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
895 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
897 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
899 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
901 if path.hops.len() < 2 && path.blinded_tail.is_none() {
902 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
903 err: "No need probing a path with less than two hops".to_string()
907 let route = Route { paths: vec![path], payment_params: None };
908 let onion_session_privs = self.add_new_pending_payment(payment_hash,
909 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
910 entropy_source, best_block_height)?;
912 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
913 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
915 Ok(()) => Ok((payment_hash, payment_id)),
917 self.remove_outbound_if_all_failed(payment_id, &e);
924 pub(super) fn test_set_payment_metadata(
925 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
927 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
928 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
929 *payment_metadata = new_payment_metadata;
931 _ => panic!("Need a retryable payment to update metadata on"),
936 pub(super) fn test_add_new_pending_payment<ES: Deref>(
937 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
938 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
939 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
940 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
943 pub(super) fn add_new_pending_payment<ES: Deref>(
944 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
945 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
946 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
947 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
948 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
949 for _ in 0..route.paths.len() {
950 onion_session_privs.push(entropy_source.get_secure_random_bytes());
953 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
954 match pending_outbounds.entry(payment_id) {
955 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
956 hash_map::Entry::Vacant(entry) => {
957 let payment = entry.insert(PendingOutboundPayment::Retryable {
959 attempts: PaymentAttempts::new(),
961 session_privs: HashSet::new(),
963 pending_fee_msat: Some(0),
965 payment_secret: recipient_onion.payment_secret,
966 payment_metadata: recipient_onion.payment_metadata,
968 starting_block_height: best_block_height,
969 total_msat: route.get_total_amount(),
972 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
973 assert!(payment.insert(*session_priv_bytes, path));
976 Ok(onion_session_privs)
981 fn pay_route_internal<NS: Deref, F>(
982 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
983 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
984 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
985 send_payment_along_path: &F
986 ) -> Result<(), PaymentSendFailure>
988 NS::Target: NodeSigner,
989 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
990 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
992 if route.paths.len() < 1 {
993 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
995 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
996 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
998 let mut total_value = 0;
999 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1000 let mut path_errs = Vec::with_capacity(route.paths.len());
1001 'path_check: for path in route.paths.iter() {
1002 if path.hops.len() < 1 || path.hops.len() > 20 {
1003 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1004 continue 'path_check;
1006 if path.blinded_tail.is_some() {
1007 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1008 continue 'path_check;
1010 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1011 usize::max_value() } else { path.hops.len() - 1 };
1012 for (idx, hop) in path.hops.iter().enumerate() {
1013 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1014 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1015 continue 'path_check;
1018 total_value += path.final_value_msat();
1019 path_errs.push(Ok(()));
1021 if path_errs.iter().any(|e| e.is_err()) {
1022 return Err(PaymentSendFailure::PathParameterError(path_errs));
1024 if let Some(amt_msat) = recv_value_msat {
1025 total_value = amt_msat;
1028 let cur_height = best_block_height + 1;
1029 let mut results = Vec::new();
1030 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1031 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1032 let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
1033 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
1036 Err(APIError::MonitorUpdateInProgress) => {
1037 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1038 // considered "in flight" and we shouldn't remove it from the
1039 // PendingOutboundPayment set.
1042 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1043 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1044 let removed = payment.remove(&session_priv, Some(path));
1045 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1047 debug_assert!(false, "This can't happen as the payment was added by callers");
1048 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1052 results.push(path_res);
1054 let mut has_ok = false;
1055 let mut has_err = false;
1056 let mut pending_amt_unsent = 0;
1057 for (res, path) in results.iter().zip(route.paths.iter()) {
1058 if res.is_ok() { has_ok = true; }
1059 if res.is_err() { has_err = true; }
1060 if let &Err(APIError::MonitorUpdateInProgress) = res {
1061 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1065 } else if res.is_err() {
1066 pending_amt_unsent += path.final_value_msat();
1069 if has_err && has_ok {
1070 Err(PaymentSendFailure::PartialFailure {
1073 failed_paths_retry: if pending_amt_unsent != 0 {
1074 if let Some(payment_params) = &route.payment_params {
1075 Some(RouteParameters {
1076 payment_params: payment_params.clone(),
1077 final_value_msat: pending_amt_unsent,
1083 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1090 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1091 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1092 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1093 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1094 send_payment_along_path: F
1095 ) -> Result<(), PaymentSendFailure>
1097 NS::Target: NodeSigner,
1098 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1099 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1101 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1102 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1103 &send_payment_along_path)
1104 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1107 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1108 // map as the payment is free to be resent.
1109 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1110 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1111 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1112 debug_assert!(removed, "We should always have a pending payment to remove here");
1116 pub(super) fn claim_htlc<L: Deref>(
1117 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1118 path: Path, from_onchain: bool,
1119 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1121 ) where L::Target: Logger {
1122 let mut session_priv_bytes = [0; 32];
1123 session_priv_bytes.copy_from_slice(&session_priv[..]);
1124 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1125 let mut pending_events = pending_events.lock().unwrap();
1126 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1127 if !payment.get().is_fulfilled() {
1128 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1129 let fee_paid_msat = payment.get().get_pending_fee_msat();
1130 pending_events.push_back((events::Event::PaymentSent {
1131 payment_id: Some(payment_id),
1136 payment.get_mut().mark_fulfilled();
1140 // We currently immediately remove HTLCs which were fulfilled on-chain.
1141 // This could potentially lead to removing a pending payment too early,
1142 // with a reorg of one block causing us to re-add the fulfilled payment on
1144 // TODO: We should have a second monitor event that informs us of payments
1145 // irrevocably fulfilled.
1146 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1147 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1148 pending_events.push_back((events::Event::PaymentPathSuccessful {
1156 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1160 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1161 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1163 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1164 let mut pending_events = pending_events.lock().unwrap();
1165 for source in sources {
1166 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1167 let mut session_priv_bytes = [0; 32];
1168 session_priv_bytes.copy_from_slice(&session_priv[..]);
1169 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1170 assert!(payment.get().is_fulfilled());
1171 if payment.get_mut().remove(&session_priv_bytes, None) {
1172 let payment_hash = payment.get().payment_hash();
1173 debug_assert!(payment_hash.is_some());
1174 pending_events.push_back((events::Event::PaymentPathSuccessful {
1185 pub(super) fn remove_stale_resolved_payments(&self,
1186 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1188 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1189 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1190 // this could race the user making a duplicate send_payment call and our idempotency
1191 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1192 // removal. This should be more than sufficient to ensure the idempotency of any
1193 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1195 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1196 let pending_events = pending_events.lock().unwrap();
1197 pending_outbound_payments.retain(|payment_id, payment| {
1198 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1199 let mut no_remaining_entries = session_privs.is_empty();
1200 if no_remaining_entries {
1201 for (ev, _) in pending_events.iter() {
1203 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1204 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1205 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1206 if payment_id == ev_payment_id {
1207 no_remaining_entries = false;
1215 if no_remaining_entries {
1216 *timer_ticks_without_htlcs += 1;
1217 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1219 *timer_ticks_without_htlcs = 0;
1226 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1227 pub(super) fn fail_htlc<L: Deref>(
1228 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1229 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1230 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1231 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1232 ) -> bool where L::Target: Logger {
1234 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1236 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1238 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1239 let mut session_priv_bytes = [0; 32];
1240 session_priv_bytes.copy_from_slice(&session_priv[..]);
1241 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1243 // If any payments already need retry, there's no need to generate a redundant
1244 // `PendingHTLCsForwardable`.
1245 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1246 let mut awaiting_retry = false;
1247 if pmt.is_auto_retryable_now() {
1248 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1249 if pending_amt_msat < total_msat {
1250 awaiting_retry = true;
1257 let mut full_failure_ev = None;
1258 let mut pending_retry_ev = false;
1259 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1260 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1261 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1264 if payment.get().is_fulfilled() {
1265 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1268 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1269 if let Some(scid) = short_channel_id {
1270 // TODO: If we decided to blame ourselves (or one of our channels) in
1271 // process_onion_failure we should close that channel as it implies our
1272 // next-hop is needlessly blaming us!
1273 payment.get_mut().insert_previously_failed_scid(scid);
1276 if payment_is_probe || !is_retryable_now || !payment_retryable {
1277 let reason = if !payment_retryable {
1278 PaymentFailureReason::RecipientRejected
1280 PaymentFailureReason::RetriesExhausted
1282 payment.get_mut().mark_abandoned(reason);
1283 is_retryable_now = false;
1285 if payment.get().remaining_parts() == 0 {
1286 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1287 if !payment_is_probe {
1288 full_failure_ev = Some(events::Event::PaymentFailed {
1289 payment_id: *payment_id,
1290 payment_hash: *payment_hash,
1299 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1302 core::mem::drop(outbounds);
1303 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1305 let path_failure = {
1306 if payment_is_probe {
1307 if !payment_retryable {
1308 events::Event::ProbeSuccessful {
1309 payment_id: *payment_id,
1310 payment_hash: payment_hash.clone(),
1314 events::Event::ProbeFailed {
1315 payment_id: *payment_id,
1316 payment_hash: payment_hash.clone(),
1322 // If we miss abandoning the payment above, we *must* generate an event here or else the
1323 // payment will sit in our outbounds forever.
1324 if attempts_remaining && !already_awaiting_retry {
1325 debug_assert!(full_failure_ev.is_none());
1326 pending_retry_ev = true;
1328 events::Event::PaymentPathFailed {
1329 payment_id: Some(*payment_id),
1330 payment_hash: payment_hash.clone(),
1331 payment_failed_permanently: !payment_retryable,
1332 failure: events::PathFailure::OnPath { network_update },
1336 error_code: onion_error_code,
1338 error_data: onion_error_data
1342 let mut pending_events = pending_events.lock().unwrap();
1343 pending_events.push_back((path_failure, None));
1344 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1348 pub(super) fn abandon_payment(
1349 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1350 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1352 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1353 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1354 payment.get_mut().mark_abandoned(reason);
1355 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1356 if payment.get().remaining_parts() == 0 {
1357 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1359 payment_hash: *payment_hash,
1369 pub fn has_pending_payments(&self) -> bool {
1370 !self.pending_outbound_payments.lock().unwrap().is_empty()
1374 pub fn clear_pending_payments(&self) {
1375 self.pending_outbound_payments.lock().unwrap().clear()
1379 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1381 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1382 probing_cookie_secret: [u8; 32]) -> bool
1384 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1385 target_payment_hash == *payment_hash
1388 /// Returns the 'probing cookie' for the given [`PaymentId`].
1389 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1390 let mut preimage = [0u8; 64];
1391 preimage[..32].copy_from_slice(&probing_cookie_secret);
1392 preimage[32..].copy_from_slice(&payment_id.0);
1393 PaymentHash(Sha256::hash(&preimage).into_inner())
1396 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1398 (0, session_privs, required),
1401 (0, session_privs, required),
1402 (1, payment_hash, option),
1403 (3, timer_ticks_without_htlcs, (default_value, 0)),
1406 (0, session_privs, required),
1407 (1, pending_fee_msat, option),
1408 (2, payment_hash, required),
1409 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1410 // never see it - `payment_params` was added here after the field was added/required.
1411 (3, payment_params, (option: ReadableArgs, 0)),
1412 (4, payment_secret, option),
1413 (5, keysend_preimage, option),
1414 (6, total_msat, required),
1415 (7, payment_metadata, option),
1416 (8, pending_amt_msat, required),
1417 (10, starting_block_height, required),
1418 (not_written, retry_strategy, (static_value, None)),
1419 (not_written, attempts, (static_value, PaymentAttempts::new())),
1422 (0, session_privs, required),
1423 (1, reason, option),
1424 (2, payment_hash, required),
1430 use bitcoin::network::constants::Network;
1431 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1433 use crate::events::{Event, PathFailure, PaymentFailureReason};
1434 use crate::ln::PaymentHash;
1435 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1436 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1437 use crate::ln::msgs::{ErrorAction, LightningError};
1438 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1439 use crate::routing::gossip::NetworkGraph;
1440 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1441 use crate::sync::{Arc, Mutex};
1442 use crate::util::errors::APIError;
1443 use crate::util::test_utils;
1445 use alloc::collections::VecDeque;
1448 #[cfg(feature = "std")]
1449 fn fails_paying_after_expiration() {
1450 do_fails_paying_after_expiration(false);
1451 do_fails_paying_after_expiration(true);
1453 #[cfg(feature = "std")]
1454 fn do_fails_paying_after_expiration(on_retry: bool) {
1455 let outbound_payments = OutboundPayments::new();
1456 let logger = test_utils::TestLogger::new();
1457 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1458 let scorer = Mutex::new(test_utils::TestScorer::new());
1459 let router = test_utils::TestRouter::new(network_graph, &scorer);
1460 let secp_ctx = Secp256k1::new();
1461 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1463 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1464 let payment_params = PaymentParameters::from_node_id(
1465 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1467 ).with_expiry_time(past_expiry_time);
1468 let expired_route_params = RouteParameters {
1470 final_value_msat: 0,
1472 let pending_events = Mutex::new(VecDeque::new());
1474 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1475 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1476 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1477 &&keys_manager, 0).unwrap();
1478 outbound_payments.retry_payment_internal(
1479 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1480 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1481 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1482 let events = pending_events.lock().unwrap();
1483 assert_eq!(events.len(), 1);
1484 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1485 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1486 } else { panic!("Unexpected event"); }
1488 let err = outbound_payments.send_payment(
1489 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1490 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1491 &&keys_manager, &&keys_manager, 0, &&logger,
1492 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1493 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1498 fn find_route_error() {
1499 do_find_route_error(false);
1500 do_find_route_error(true);
1502 fn do_find_route_error(on_retry: bool) {
1503 let outbound_payments = OutboundPayments::new();
1504 let logger = test_utils::TestLogger::new();
1505 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1506 let scorer = Mutex::new(test_utils::TestScorer::new());
1507 let router = test_utils::TestRouter::new(network_graph, &scorer);
1508 let secp_ctx = Secp256k1::new();
1509 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1511 let payment_params = PaymentParameters::from_node_id(
1512 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1513 let route_params = RouteParameters {
1515 final_value_msat: 0,
1517 router.expect_find_route(route_params.clone(),
1518 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1520 let pending_events = Mutex::new(VecDeque::new());
1522 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1523 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1524 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1525 &&keys_manager, 0).unwrap();
1526 outbound_payments.retry_payment_internal(
1527 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1528 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1529 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1530 let events = pending_events.lock().unwrap();
1531 assert_eq!(events.len(), 1);
1532 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1534 let err = outbound_payments.send_payment(
1535 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1536 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1537 &&keys_manager, &&keys_manager, 0, &&logger,
1538 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1539 if let RetryableSendFailure::RouteNotFound = err {
1540 } else { panic!("Unexpected error"); }
1545 fn initial_send_payment_path_failed_evs() {
1546 let outbound_payments = OutboundPayments::new();
1547 let logger = test_utils::TestLogger::new();
1548 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1549 let scorer = Mutex::new(test_utils::TestScorer::new());
1550 let router = test_utils::TestRouter::new(network_graph, &scorer);
1551 let secp_ctx = Secp256k1::new();
1552 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1554 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1555 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1556 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1557 let route_params = RouteParameters {
1558 payment_params: payment_params.clone(),
1559 final_value_msat: 0,
1561 let failed_scid = 42;
1563 paths: vec![Path { hops: vec![RouteHop {
1564 pubkey: receiver_pk,
1565 node_features: NodeFeatures::empty(),
1566 short_channel_id: failed_scid,
1567 channel_features: ChannelFeatures::empty(),
1569 cltv_expiry_delta: 0,
1570 }], blinded_tail: None }],
1571 payment_params: Some(payment_params),
1573 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1574 let mut route_params_w_failed_scid = route_params.clone();
1575 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1576 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1577 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1578 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1580 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1581 // PaymentPathFailed event.
1582 let pending_events = Mutex::new(VecDeque::new());
1583 outbound_payments.send_payment(
1584 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1585 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1586 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1587 |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1589 let mut events = pending_events.lock().unwrap();
1590 assert_eq!(events.len(), 2);
1591 if let Event::PaymentPathFailed {
1593 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1595 assert_eq!(short_channel_id, Some(failed_scid));
1596 } else { panic!("Unexpected event"); }
1597 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1599 core::mem::drop(events);
1601 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1602 outbound_payments.send_payment(
1603 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1604 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1605 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1606 |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1607 assert_eq!(pending_events.lock().unwrap().len(), 0);
1609 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1610 outbound_payments.send_payment(
1611 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1612 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1613 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1614 |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1616 let events = pending_events.lock().unwrap();
1617 assert_eq!(events.len(), 2);
1618 if let Event::PaymentPathFailed {
1620 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1622 assert_eq!(short_channel_id, None);
1623 } else { panic!("Unexpected event"); }
1624 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }