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 payment_hash: Option<PaymentHash>,
64 timer_ticks_without_htlcs: u8,
66 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
67 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
69 session_privs: HashSet<[u8; 32]>,
70 payment_hash: PaymentHash,
71 /// Will be `None` if the payment was serialized before 0.0.115.
72 reason: Option<PaymentFailureReason>,
76 impl PendingOutboundPayment {
77 fn increment_attempts(&mut self) {
78 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
82 fn is_auto_retryable_now(&self) -> bool {
84 PendingOutboundPayment::Retryable {
85 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
87 strategy.is_retryable_now(&attempts)
92 fn is_retryable_now(&self) -> bool {
94 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
95 // We're handling retries manually, we can always retry.
98 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
99 strategy.is_retryable_now(&attempts)
104 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
105 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
106 params.previously_failed_channels.push(scid);
109 pub(super) fn is_fulfilled(&self) -> bool {
111 PendingOutboundPayment::Fulfilled { .. } => true,
115 pub(super) fn abandoned(&self) -> bool {
117 PendingOutboundPayment::Abandoned { .. } => true,
121 fn get_pending_fee_msat(&self) -> Option<u64> {
123 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
128 fn payment_hash(&self) -> Option<PaymentHash> {
130 PendingOutboundPayment::Legacy { .. } => None,
131 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
132 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
133 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
137 fn mark_fulfilled(&mut self) {
138 let mut session_privs = HashSet::new();
139 core::mem::swap(&mut session_privs, match self {
140 PendingOutboundPayment::Legacy { session_privs } |
141 PendingOutboundPayment::Retryable { session_privs, .. } |
142 PendingOutboundPayment::Fulfilled { session_privs, .. } |
143 PendingOutboundPayment::Abandoned { session_privs, .. }
146 let payment_hash = self.payment_hash();
147 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
150 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
151 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
152 let mut our_session_privs = HashSet::new();
153 core::mem::swap(&mut our_session_privs, session_privs);
154 *self = PendingOutboundPayment::Abandoned {
155 session_privs: our_session_privs,
156 payment_hash: *payment_hash,
162 /// panics if path is None and !self.is_fulfilled
163 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
164 let remove_res = match self {
165 PendingOutboundPayment::Legacy { session_privs } |
166 PendingOutboundPayment::Retryable { session_privs, .. } |
167 PendingOutboundPayment::Fulfilled { session_privs, .. } |
168 PendingOutboundPayment::Abandoned { session_privs, .. } => {
169 session_privs.remove(session_priv)
173 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
174 let path = path.expect("Fulfilling a payment should always come with a path");
175 *pending_amt_msat -= path.final_value_msat();
176 if let Some(fee_msat) = pending_fee_msat.as_mut() {
177 *fee_msat -= path.fee_msat();
184 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
185 let insert_res = match self {
186 PendingOutboundPayment::Legacy { session_privs } |
187 PendingOutboundPayment::Retryable { session_privs, .. } => {
188 session_privs.insert(session_priv)
190 PendingOutboundPayment::Fulfilled { .. } => false,
191 PendingOutboundPayment::Abandoned { .. } => false,
194 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
195 *pending_amt_msat += path.final_value_msat();
196 if let Some(fee_msat) = pending_fee_msat.as_mut() {
197 *fee_msat += path.fee_msat();
204 pub(super) fn remaining_parts(&self) -> usize {
206 PendingOutboundPayment::Legacy { session_privs } |
207 PendingOutboundPayment::Retryable { session_privs, .. } |
208 PendingOutboundPayment::Fulfilled { session_privs, .. } |
209 PendingOutboundPayment::Abandoned { session_privs, .. } => {
216 /// Strategies available to retry payment path failures.
217 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
219 /// Max number of attempts to retry payment.
221 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
222 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
223 /// were retried along a route from a single call to [`Router::find_route_with_id`].
225 #[cfg(not(feature = "no-std"))]
226 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
227 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
229 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
230 Timeout(core::time::Duration),
234 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
235 match (self, attempts) {
236 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
237 max_retry_count > count
239 #[cfg(all(not(feature = "no-std"), not(test)))]
240 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
241 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
242 #[cfg(all(not(feature = "no-std"), test))]
243 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
244 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
249 #[cfg(feature = "std")]
250 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
251 if let Some(expiry_time) = route_params.payment_params.expiry_time {
252 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
253 return elapsed > core::time::Duration::from_secs(expiry_time)
259 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
261 /// Storing minimal payment attempts information required for determining if a outbound payment can
263 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
264 /// This count will be incremented only after the result of the attempt is known. When it's 0,
265 /// it means the result of the first attempt is not known yet.
266 pub(crate) count: usize,
267 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
268 #[cfg(not(feature = "no-std"))]
269 first_attempted_at: T,
270 #[cfg(feature = "no-std")]
271 phantom: core::marker::PhantomData<T>,
275 #[cfg(not(any(feature = "no-std", test)))]
276 type ConfiguredTime = std::time::Instant;
277 #[cfg(feature = "no-std")]
278 type ConfiguredTime = crate::util::time::Eternity;
279 #[cfg(all(not(feature = "no-std"), test))]
280 type ConfiguredTime = SinceEpoch;
282 impl<T: Time> PaymentAttemptsUsingTime<T> {
283 pub(crate) fn new() -> Self {
284 PaymentAttemptsUsingTime {
286 #[cfg(not(feature = "no-std"))]
287 first_attempted_at: T::now(),
288 #[cfg(feature = "no-std")]
289 phantom: core::marker::PhantomData,
294 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
295 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
296 #[cfg(feature = "no-std")]
297 return write!(f, "attempts: {}", self.count);
298 #[cfg(not(feature = "no-std"))]
301 "attempts: {}, duration: {}s",
303 T::now().duration_since(self.first_attempted_at).as_secs()
308 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
309 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
311 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
312 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
313 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
314 #[derive(Clone, Debug)]
315 pub enum RetryableSendFailure {
316 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
317 /// that this error is *not* caused by [`Retry::Timeout`].
319 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
321 /// We were unable to find a route to the destination.
323 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
324 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
326 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
327 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
328 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
332 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
333 /// of several states. This enum is returned as the Err() type describing which state the payment
334 /// is in, see the description of individual enum states for more.
336 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
337 #[derive(Clone, Debug)]
338 pub enum PaymentSendFailure {
339 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
340 /// send the payment at all.
342 /// You can freely resend the payment in full (with the parameter error fixed).
344 /// Because the payment failed outright, no payment tracking is done and no
345 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
347 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
348 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
349 ParameterError(APIError),
350 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
351 /// from attempting to send the payment at all.
353 /// You can freely resend the payment in full (with the parameter error fixed).
355 /// Because the payment failed outright, no payment tracking is done and no
356 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
358 /// The results here are ordered the same as the paths in the route object which was passed to
361 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
362 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
363 PathParameterError(Vec<Result<(), APIError>>),
364 /// All paths which were attempted failed to send, with no channel state change taking place.
365 /// You can freely resend the payment in full (though you probably want to do so over different
366 /// paths than the ones selected).
368 /// Because the payment failed outright, no payment tracking is done and no
369 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
371 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
372 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
373 AllFailedResendSafe(Vec<APIError>),
374 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
375 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
377 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
378 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
379 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
381 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
382 /// some paths have irrevocably committed to the HTLC.
384 /// The results here are ordered the same as the paths in the route object that was passed to
387 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
388 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
390 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
392 /// The errors themselves, in the same order as the paths from the route.
393 results: Vec<Result<(), APIError>>,
394 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
395 /// contain a [`RouteParameters`] object for the failing paths.
396 failed_paths_retry: Option<RouteParameters>,
397 /// The payment id for the payment, which is now at least partially pending.
398 payment_id: PaymentId,
402 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
404 /// This should generally be constructed with data communicated to us from the recipient (via a
405 /// BOLT11 or BOLT12 invoice).
406 #[derive(Clone, Debug, PartialEq, Eq)]
407 pub struct RecipientOnionFields {
408 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
409 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
410 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
413 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
414 /// multi-path payments require a recipient-provided secret.
416 /// Note that for spontaneous payments most lightning nodes do not currently support MPP
417 /// receives, thus you should generally never be providing a secret here for spontaneous
419 pub payment_secret: Option<PaymentSecret>,
420 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
421 /// arbitrary length. This gives recipients substantially more flexibility to receive
424 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
425 /// scheme to authenticate received payments against expected payments and invoices, this field
426 /// is not used in LDK for received payments, and can be used to store arbitrary data in
427 /// invoices which will be received with the payment.
429 /// Note that this field was added to the lightning specification more recently than
430 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
431 /// may not be supported as universally.
432 pub payment_metadata: Option<Vec<u8>>,
435 impl_writeable_tlv_based!(RecipientOnionFields, {
436 (0, payment_secret, option),
437 (2, payment_metadata, option),
440 impl RecipientOnionFields {
441 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
442 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
443 /// but do not require or provide any further data.
444 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
445 Self { payment_secret: Some(payment_secret), payment_metadata: None }
448 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
449 /// payable HTLCs except for spontaneous payments, i.e. this should generally only be used for
450 /// calls to [`ChannelManager::send_spontaneous_payment`].
452 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
453 pub fn spontaneous_empty() -> Self {
454 Self { payment_secret: None, payment_metadata: None }
457 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
458 /// have to make sure that some fields match exactly across the parts. For those that aren't
459 /// required to match, if they don't match we should remove them so as to not expose data
460 /// that's dependent on the HTLC receive order to users.
462 /// Here we implement this, first checking compatibility then mutating two objects and then
463 /// dropping any remaining non-matching fields from both.
464 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
465 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
466 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
467 // For custom TLVs we should just drop non-matching ones, but not reject the payment.
472 pub(super) struct OutboundPayments {
473 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
474 pub(super) retry_lock: Mutex<()>,
477 impl OutboundPayments {
478 pub(super) fn new() -> Self {
480 pending_outbound_payments: Mutex::new(HashMap::new()),
481 retry_lock: Mutex::new(()),
485 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
486 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
487 retry_strategy: Retry, route_params: RouteParameters, router: &R,
488 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
489 node_signer: &NS, best_block_height: u32, logger: &L,
490 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
491 ) -> Result<(), RetryableSendFailure>
494 ES::Target: EntropySource,
495 NS::Target: NodeSigner,
497 IH: Fn() -> InFlightHtlcs,
498 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
499 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
501 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
502 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
503 best_block_height, logger, pending_events, &send_payment_along_path)
506 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
507 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
508 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
509 send_payment_along_path: F
510 ) -> Result<(), PaymentSendFailure>
512 ES::Target: EntropySource,
513 NS::Target: NodeSigner,
514 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
515 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
517 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)?;
518 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
519 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
520 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
523 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
524 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
525 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
526 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
527 node_signer: &NS, best_block_height: u32, logger: &L,
528 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
529 ) -> Result<PaymentHash, RetryableSendFailure>
532 ES::Target: EntropySource,
533 NS::Target: NodeSigner,
535 IH: Fn() -> InFlightHtlcs,
536 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
537 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
539 let preimage = payment_preimage
540 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
541 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
542 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
543 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
544 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
545 .map(|()| payment_hash)
548 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
549 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
550 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
551 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
552 ) -> Result<PaymentHash, PaymentSendFailure>
554 ES::Target: EntropySource,
555 NS::Target: NodeSigner,
556 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
557 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
559 let preimage = payment_preimage
560 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
561 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
562 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
563 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
565 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
566 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
568 Ok(()) => Ok(payment_hash),
570 self.remove_outbound_if_all_failed(payment_id, &e);
576 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
577 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
578 best_block_height: u32,
579 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
580 send_payment_along_path: SP,
584 ES::Target: EntropySource,
585 NS::Target: NodeSigner,
586 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
587 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
588 IH: Fn() -> InFlightHtlcs,
589 FH: Fn() -> Vec<ChannelDetails>,
592 let _single_thread = self.retry_lock.lock().unwrap();
594 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
595 let mut retry_id_route_params = None;
596 for (pmt_id, pmt) in outbounds.iter_mut() {
597 if pmt.is_auto_retryable_now() {
598 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
599 if pending_amt_msat < total_msat {
600 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
601 final_value_msat: *total_msat - *pending_amt_msat,
602 payment_params: params.clone(),
606 } else { debug_assert!(false); }
609 core::mem::drop(outbounds);
610 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
611 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)
615 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
616 outbounds.retain(|pmt_id, pmt| {
617 let mut retain = true;
618 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
619 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
620 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
621 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
623 payment_hash: *payment_hash,
633 pub(super) fn needs_abandon(&self) -> bool {
634 let outbounds = self.pending_outbound_payments.lock().unwrap();
635 outbounds.iter().any(|(_, pmt)|
636 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
639 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
640 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
642 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
643 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
644 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
645 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
646 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
647 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
648 node_signer: &NS, best_block_height: u32, logger: &L,
649 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
650 ) -> Result<(), RetryableSendFailure>
653 ES::Target: EntropySource,
654 NS::Target: NodeSigner,
656 IH: Fn() -> InFlightHtlcs,
657 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
658 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
660 #[cfg(feature = "std")] {
661 if has_expired(&route_params) {
662 return Err(RetryableSendFailure::PaymentExpired)
666 let route = router.find_route_with_id(
667 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
668 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
669 payment_hash, payment_id,
670 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
672 let onion_session_privs = self.add_new_pending_payment(payment_hash,
673 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
674 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
675 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
677 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, None, payment_id, None,
678 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
679 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
680 if let Err(e) = res {
681 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);
686 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
687 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
688 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
689 node_signer: &NS, best_block_height: u32, logger: &L,
690 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
694 ES::Target: EntropySource,
695 NS::Target: NodeSigner,
697 IH: Fn() -> InFlightHtlcs,
698 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
699 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
701 #[cfg(feature = "std")] {
702 if has_expired(&route_params) {
703 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
704 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
709 let route = match router.find_route_with_id(
710 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
711 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
712 payment_hash, payment_id,
716 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
717 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
721 for path in route.paths.iter() {
722 if path.hops.len() == 0 {
723 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
724 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
729 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
730 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
731 for _ in 0..route.paths.len() {
732 onion_session_privs.push(entropy_source.get_secure_random_bytes());
735 macro_rules! abandon_with_entry {
736 ($payment: expr, $reason: expr) => {
737 $payment.get_mut().mark_abandoned($reason);
738 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
739 if $payment.get().remaining_parts() == 0 {
740 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
750 let (total_msat, recipient_onion, keysend_preimage) = {
751 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
752 match outbounds.entry(payment_id) {
753 hash_map::Entry::Occupied(mut payment) => {
754 let res = match payment.get() {
755 PendingOutboundPayment::Retryable {
756 total_msat, keysend_preimage, payment_secret, payment_metadata, pending_amt_msat, ..
758 let retry_amt_msat = route.get_total_amount();
759 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
760 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);
761 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
764 (*total_msat, RecipientOnionFields {
765 payment_secret: *payment_secret,
766 payment_metadata: payment_metadata.clone(),
767 }, *keysend_preimage)
769 PendingOutboundPayment::Legacy { .. } => {
770 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
773 PendingOutboundPayment::Fulfilled { .. } => {
774 log_error!(logger, "Payment already completed");
777 PendingOutboundPayment::Abandoned { .. } => {
778 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
782 if !payment.get().is_retryable_now() {
783 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
784 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
787 payment.get_mut().increment_attempts();
788 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
789 assert!(payment.get_mut().insert(*session_priv_bytes, path));
793 hash_map::Entry::Vacant(_) => {
794 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
799 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
800 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
801 &send_payment_along_path);
802 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
803 if let Err(e) = res {
804 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);
808 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
809 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
810 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
811 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
812 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
816 ES::Target: EntropySource,
817 NS::Target: NodeSigner,
819 IH: Fn() -> InFlightHtlcs,
820 SP: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
821 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
824 PaymentSendFailure::AllFailedResendSafe(errs) => {
825 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);
826 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);
828 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
829 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
830 // Some paths were sent, even if we failed to send the full MPP value our recipient may
831 // misbehave and claim the funds, at which point we have to consider the payment sent, so
832 // return `Ok()` here, ignoring any retry errors.
833 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);
835 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
836 // This may happen if we send a payment and some paths fail, but only due to a temporary
837 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
838 // initial HTLC-Add messages yet.
840 PaymentSendFailure::PathParameterError(results) => {
841 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
842 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
843 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
845 PaymentSendFailure::ParameterError(e) => {
846 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
847 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
849 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
853 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
854 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
855 paths: Vec<Path>, path_results: I, logger: &L,
856 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
857 ) where L::Target: Logger {
858 let mut events = pending_events.lock().unwrap();
859 debug_assert_eq!(paths.len(), path_results.len());
860 for (path, path_res) in paths.into_iter().zip(path_results) {
861 if let Err(e) = path_res {
862 if let APIError::MonitorUpdateInProgress = e { continue }
863 log_error!(logger, "Failed to send along path due to error: {:?}", e);
864 let mut failed_scid = None;
865 if let APIError::ChannelUnavailable { .. } = e {
866 let scid = path.hops[0].short_channel_id;
867 failed_scid = Some(scid);
868 route_params.payment_params.previously_failed_channels.push(scid);
870 events.push_back((events::Event::PaymentPathFailed {
871 payment_id: Some(payment_id),
873 payment_failed_permanently: false,
874 failure: events::PathFailure::InitialSend { err: e },
876 short_channel_id: failed_scid,
886 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
887 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
888 best_block_height: u32, send_payment_along_path: F
889 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
891 ES::Target: EntropySource,
892 NS::Target: NodeSigner,
893 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
894 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
896 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
898 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
900 if path.hops.len() < 2 && path.blinded_tail.is_none() {
901 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
902 err: "No need probing a path with less than two hops".to_string()
906 let route = Route { paths: vec![path], payment_params: None };
907 let onion_session_privs = self.add_new_pending_payment(payment_hash,
908 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
909 entropy_source, best_block_height)?;
911 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
912 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
914 Ok(()) => Ok((payment_hash, payment_id)),
916 self.remove_outbound_if_all_failed(payment_id, &e);
923 pub(super) fn test_set_payment_metadata(
924 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
926 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
927 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
928 *payment_metadata = new_payment_metadata;
930 _ => panic!("Need a retryable payment to update metadata on"),
935 pub(super) fn test_add_new_pending_payment<ES: Deref>(
936 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
937 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
938 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
939 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
942 pub(super) fn add_new_pending_payment<ES: Deref>(
943 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
944 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
945 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
946 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
947 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
948 for _ in 0..route.paths.len() {
949 onion_session_privs.push(entropy_source.get_secure_random_bytes());
952 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
953 match pending_outbounds.entry(payment_id) {
954 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
955 hash_map::Entry::Vacant(entry) => {
956 let payment = entry.insert(PendingOutboundPayment::Retryable {
958 attempts: PaymentAttempts::new(),
960 session_privs: HashSet::new(),
962 pending_fee_msat: Some(0),
964 payment_secret: recipient_onion.payment_secret,
965 payment_metadata: recipient_onion.payment_metadata,
967 starting_block_height: best_block_height,
968 total_msat: route.get_total_amount(),
971 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
972 assert!(payment.insert(*session_priv_bytes, path));
975 Ok(onion_session_privs)
980 fn pay_route_internal<NS: Deref, F>(
981 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
982 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
983 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
984 send_payment_along_path: &F
985 ) -> Result<(), PaymentSendFailure>
987 NS::Target: NodeSigner,
988 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
989 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
991 if route.paths.len() < 1 {
992 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
994 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
995 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
997 let mut total_value = 0;
998 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
999 let mut path_errs = Vec::with_capacity(route.paths.len());
1000 'path_check: for path in route.paths.iter() {
1001 if path.hops.len() < 1 || path.hops.len() > 20 {
1002 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1003 continue 'path_check;
1005 if path.blinded_tail.is_some() {
1006 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1007 continue 'path_check;
1009 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1010 usize::max_value() } else { path.hops.len() - 1 };
1011 for (idx, hop) in path.hops.iter().enumerate() {
1012 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1013 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1014 continue 'path_check;
1017 total_value += path.final_value_msat();
1018 path_errs.push(Ok(()));
1020 if path_errs.iter().any(|e| e.is_err()) {
1021 return Err(PaymentSendFailure::PathParameterError(path_errs));
1023 if let Some(amt_msat) = recv_value_msat {
1024 total_value = amt_msat;
1027 let cur_height = best_block_height + 1;
1028 let mut results = Vec::new();
1029 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1030 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1031 let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
1032 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
1035 Err(APIError::MonitorUpdateInProgress) => {
1036 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1037 // considered "in flight" and we shouldn't remove it from the
1038 // PendingOutboundPayment set.
1041 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1042 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1043 let removed = payment.remove(&session_priv, Some(path));
1044 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1046 debug_assert!(false, "This can't happen as the payment was added by callers");
1047 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1051 results.push(path_res);
1053 let mut has_ok = false;
1054 let mut has_err = false;
1055 let mut pending_amt_unsent = 0;
1056 for (res, path) in results.iter().zip(route.paths.iter()) {
1057 if res.is_ok() { has_ok = true; }
1058 if res.is_err() { has_err = true; }
1059 if let &Err(APIError::MonitorUpdateInProgress) = res {
1060 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1064 } else if res.is_err() {
1065 pending_amt_unsent += path.final_value_msat();
1068 if has_err && has_ok {
1069 Err(PaymentSendFailure::PartialFailure {
1072 failed_paths_retry: if pending_amt_unsent != 0 {
1073 if let Some(payment_params) = &route.payment_params {
1074 Some(RouteParameters {
1075 payment_params: payment_params.clone(),
1076 final_value_msat: pending_amt_unsent,
1082 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1089 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1090 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1091 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1092 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1093 send_payment_along_path: F
1094 ) -> Result<(), PaymentSendFailure>
1096 NS::Target: NodeSigner,
1097 F: Fn(&Path, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1098 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1100 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1101 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1102 &send_payment_along_path)
1103 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1106 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1107 // map as the payment is free to be resent.
1108 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1109 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1110 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1111 debug_assert!(removed, "We should always have a pending payment to remove here");
1115 pub(super) fn claim_htlc<L: Deref>(
1116 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1117 path: Path, from_onchain: bool,
1118 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1120 ) where L::Target: Logger {
1121 let mut session_priv_bytes = [0; 32];
1122 session_priv_bytes.copy_from_slice(&session_priv[..]);
1123 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1124 let mut pending_events = pending_events.lock().unwrap();
1125 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1126 if !payment.get().is_fulfilled() {
1127 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1128 let fee_paid_msat = payment.get().get_pending_fee_msat();
1129 pending_events.push_back((events::Event::PaymentSent {
1130 payment_id: Some(payment_id),
1135 payment.get_mut().mark_fulfilled();
1139 // We currently immediately remove HTLCs which were fulfilled on-chain.
1140 // This could potentially lead to removing a pending payment too early,
1141 // with a reorg of one block causing us to re-add the fulfilled payment on
1143 // TODO: We should have a second monitor event that informs us of payments
1144 // irrevocably fulfilled.
1145 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1146 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1147 pending_events.push_back((events::Event::PaymentPathSuccessful {
1155 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1159 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1160 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1162 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1163 let mut pending_events = pending_events.lock().unwrap();
1164 for source in sources {
1165 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1166 let mut session_priv_bytes = [0; 32];
1167 session_priv_bytes.copy_from_slice(&session_priv[..]);
1168 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1169 assert!(payment.get().is_fulfilled());
1170 if payment.get_mut().remove(&session_priv_bytes, None) {
1171 pending_events.push_back((events::Event::PaymentPathSuccessful {
1173 payment_hash: payment.get().payment_hash(),
1182 pub(super) fn remove_stale_resolved_payments(&self,
1183 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1185 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1186 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1187 // this could race the user making a duplicate send_payment call and our idempotency
1188 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1189 // removal. This should be more than sufficient to ensure the idempotency of any
1190 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1192 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1193 let pending_events = pending_events.lock().unwrap();
1194 pending_outbound_payments.retain(|payment_id, payment| {
1195 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1196 let mut no_remaining_entries = session_privs.is_empty();
1197 if no_remaining_entries {
1198 for (ev, _) in pending_events.iter() {
1200 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1201 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1202 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1203 if payment_id == ev_payment_id {
1204 no_remaining_entries = false;
1212 if no_remaining_entries {
1213 *timer_ticks_without_htlcs += 1;
1214 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1216 *timer_ticks_without_htlcs = 0;
1223 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1224 pub(super) fn fail_htlc<L: Deref>(
1225 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1226 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1227 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1228 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1229 ) -> bool where L::Target: Logger {
1231 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1233 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1235 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1236 let mut session_priv_bytes = [0; 32];
1237 session_priv_bytes.copy_from_slice(&session_priv[..]);
1238 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1240 // If any payments already need retry, there's no need to generate a redundant
1241 // `PendingHTLCsForwardable`.
1242 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1243 let mut awaiting_retry = false;
1244 if pmt.is_auto_retryable_now() {
1245 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1246 if pending_amt_msat < total_msat {
1247 awaiting_retry = true;
1254 let mut full_failure_ev = None;
1255 let mut pending_retry_ev = false;
1256 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1257 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1258 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1261 if payment.get().is_fulfilled() {
1262 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1265 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1266 if let Some(scid) = short_channel_id {
1267 // TODO: If we decided to blame ourselves (or one of our channels) in
1268 // process_onion_failure we should close that channel as it implies our
1269 // next-hop is needlessly blaming us!
1270 payment.get_mut().insert_previously_failed_scid(scid);
1273 if payment_is_probe || !is_retryable_now || !payment_retryable {
1274 let reason = if !payment_retryable {
1275 PaymentFailureReason::RecipientRejected
1277 PaymentFailureReason::RetriesExhausted
1279 payment.get_mut().mark_abandoned(reason);
1280 is_retryable_now = false;
1282 if payment.get().remaining_parts() == 0 {
1283 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1284 if !payment_is_probe {
1285 full_failure_ev = Some(events::Event::PaymentFailed {
1286 payment_id: *payment_id,
1287 payment_hash: *payment_hash,
1296 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1299 core::mem::drop(outbounds);
1300 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1302 let path_failure = {
1303 if payment_is_probe {
1304 if !payment_retryable {
1305 events::Event::ProbeSuccessful {
1306 payment_id: *payment_id,
1307 payment_hash: payment_hash.clone(),
1311 events::Event::ProbeFailed {
1312 payment_id: *payment_id,
1313 payment_hash: payment_hash.clone(),
1319 // If we miss abandoning the payment above, we *must* generate an event here or else the
1320 // payment will sit in our outbounds forever.
1321 if attempts_remaining && !already_awaiting_retry {
1322 debug_assert!(full_failure_ev.is_none());
1323 pending_retry_ev = true;
1325 events::Event::PaymentPathFailed {
1326 payment_id: Some(*payment_id),
1327 payment_hash: payment_hash.clone(),
1328 payment_failed_permanently: !payment_retryable,
1329 failure: events::PathFailure::OnPath { network_update },
1333 error_code: onion_error_code,
1335 error_data: onion_error_data
1339 let mut pending_events = pending_events.lock().unwrap();
1340 pending_events.push_back((path_failure, None));
1341 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1345 pub(super) fn abandon_payment(
1346 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1347 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1349 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1350 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1351 payment.get_mut().mark_abandoned(reason);
1352 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1353 if payment.get().remaining_parts() == 0 {
1354 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1356 payment_hash: *payment_hash,
1366 pub fn has_pending_payments(&self) -> bool {
1367 !self.pending_outbound_payments.lock().unwrap().is_empty()
1371 pub fn clear_pending_payments(&self) {
1372 self.pending_outbound_payments.lock().unwrap().clear()
1376 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1378 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1379 probing_cookie_secret: [u8; 32]) -> bool
1381 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1382 target_payment_hash == *payment_hash
1385 /// Returns the 'probing cookie' for the given [`PaymentId`].
1386 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1387 let mut preimage = [0u8; 64];
1388 preimage[..32].copy_from_slice(&probing_cookie_secret);
1389 preimage[32..].copy_from_slice(&payment_id.0);
1390 PaymentHash(Sha256::hash(&preimage).into_inner())
1393 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1395 (0, session_privs, required),
1398 (0, session_privs, required),
1399 (1, payment_hash, option),
1400 (3, timer_ticks_without_htlcs, (default_value, 0)),
1403 (0, session_privs, required),
1404 (1, pending_fee_msat, option),
1405 (2, payment_hash, required),
1406 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1407 // never see it - `payment_params` was added here after the field was added/required.
1408 (3, payment_params, (option: ReadableArgs, 0)),
1409 (4, payment_secret, option),
1410 (5, keysend_preimage, option),
1411 (6, total_msat, required),
1412 (7, payment_metadata, option),
1413 (8, pending_amt_msat, required),
1414 (10, starting_block_height, required),
1415 (not_written, retry_strategy, (static_value, None)),
1416 (not_written, attempts, (static_value, PaymentAttempts::new())),
1419 (0, session_privs, required),
1420 (1, reason, option),
1421 (2, payment_hash, required),
1427 use bitcoin::network::constants::Network;
1428 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1430 use crate::events::{Event, PathFailure, PaymentFailureReason};
1431 use crate::ln::PaymentHash;
1432 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1433 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1434 use crate::ln::msgs::{ErrorAction, LightningError};
1435 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1436 use crate::routing::gossip::NetworkGraph;
1437 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1438 use crate::sync::{Arc, Mutex};
1439 use crate::util::errors::APIError;
1440 use crate::util::test_utils;
1442 use alloc::collections::VecDeque;
1445 #[cfg(feature = "std")]
1446 fn fails_paying_after_expiration() {
1447 do_fails_paying_after_expiration(false);
1448 do_fails_paying_after_expiration(true);
1450 #[cfg(feature = "std")]
1451 fn do_fails_paying_after_expiration(on_retry: bool) {
1452 let outbound_payments = OutboundPayments::new();
1453 let logger = test_utils::TestLogger::new();
1454 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1455 let scorer = Mutex::new(test_utils::TestScorer::new());
1456 let router = test_utils::TestRouter::new(network_graph, &scorer);
1457 let secp_ctx = Secp256k1::new();
1458 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1460 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1461 let payment_params = PaymentParameters::from_node_id(
1462 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1464 ).with_expiry_time(past_expiry_time);
1465 let expired_route_params = RouteParameters {
1467 final_value_msat: 0,
1469 let pending_events = Mutex::new(VecDeque::new());
1471 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1472 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1473 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1474 &&keys_manager, 0).unwrap();
1475 outbound_payments.retry_payment_internal(
1476 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1477 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1478 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1479 let events = pending_events.lock().unwrap();
1480 assert_eq!(events.len(), 1);
1481 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1482 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1483 } else { panic!("Unexpected event"); }
1485 let err = outbound_payments.send_payment(
1486 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1487 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1488 &&keys_manager, &&keys_manager, 0, &&logger,
1489 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1490 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1495 fn find_route_error() {
1496 do_find_route_error(false);
1497 do_find_route_error(true);
1499 fn do_find_route_error(on_retry: bool) {
1500 let outbound_payments = OutboundPayments::new();
1501 let logger = test_utils::TestLogger::new();
1502 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1503 let scorer = Mutex::new(test_utils::TestScorer::new());
1504 let router = test_utils::TestRouter::new(network_graph, &scorer);
1505 let secp_ctx = Secp256k1::new();
1506 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1508 let payment_params = PaymentParameters::from_node_id(
1509 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1510 let route_params = RouteParameters {
1512 final_value_msat: 0,
1514 router.expect_find_route(route_params.clone(),
1515 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1517 let pending_events = Mutex::new(VecDeque::new());
1519 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1520 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1521 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1522 &&keys_manager, 0).unwrap();
1523 outbound_payments.retry_payment_internal(
1524 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1525 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1526 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1527 let events = pending_events.lock().unwrap();
1528 assert_eq!(events.len(), 1);
1529 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1531 let err = outbound_payments.send_payment(
1532 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1533 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1534 &&keys_manager, &&keys_manager, 0, &&logger,
1535 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1536 if let RetryableSendFailure::RouteNotFound = err {
1537 } else { panic!("Unexpected error"); }
1542 fn initial_send_payment_path_failed_evs() {
1543 let outbound_payments = OutboundPayments::new();
1544 let logger = test_utils::TestLogger::new();
1545 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1546 let scorer = Mutex::new(test_utils::TestScorer::new());
1547 let router = test_utils::TestRouter::new(network_graph, &scorer);
1548 let secp_ctx = Secp256k1::new();
1549 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1551 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1552 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1553 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1554 let route_params = RouteParameters {
1555 payment_params: payment_params.clone(),
1556 final_value_msat: 0,
1558 let failed_scid = 42;
1560 paths: vec![Path { hops: vec![RouteHop {
1561 pubkey: receiver_pk,
1562 node_features: NodeFeatures::empty(),
1563 short_channel_id: failed_scid,
1564 channel_features: ChannelFeatures::empty(),
1566 cltv_expiry_delta: 0,
1567 }], blinded_tail: None }],
1568 payment_params: Some(payment_params),
1570 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1571 let mut route_params_w_failed_scid = route_params.clone();
1572 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1573 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1574 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1575 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1577 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1578 // PaymentPathFailed event.
1579 let pending_events = Mutex::new(VecDeque::new());
1580 outbound_payments.send_payment(
1581 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1582 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1583 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1584 |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1586 let mut events = pending_events.lock().unwrap();
1587 assert_eq!(events.len(), 2);
1588 if let Event::PaymentPathFailed {
1590 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1592 assert_eq!(short_channel_id, Some(failed_scid));
1593 } else { panic!("Unexpected event"); }
1594 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1596 core::mem::drop(events);
1598 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1599 outbound_payments.send_payment(
1600 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1601 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1602 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1603 |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1604 assert_eq!(pending_events.lock().unwrap().len(), 0);
1606 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1607 outbound_payments.send_payment(
1608 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1609 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1610 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1611 |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1613 let events = pending_events.lock().unwrap();
1614 assert_eq!(events.len(), 2);
1615 if let Event::PaymentPathFailed {
1617 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1619 assert_eq!(short_channel_id, None);
1620 } else { panic!("Unexpected event"); }
1621 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }