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::blinded_path::{IntroductionNode, NodeIdLookUp};
17 use crate::blinded_path::payment::advance_path_by_one;
18 use crate::events::{self, PaymentFailureReason};
19 use crate::ln::types::{PaymentHash, PaymentPreimage, PaymentSecret};
20 use crate::ln::channel_state::ChannelDetails;
21 use crate::ln::channelmanager::{EventCompletionAction, HTLCSource, PaymentId};
22 use crate::ln::onion_utils;
23 use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
24 use crate::offers::invoice::Bolt12Invoice;
25 use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
26 use crate::sign::{EntropySource, NodeSigner, Recipient};
27 use crate::util::errors::APIError;
28 use crate::util::logger::Logger;
29 use crate::util::time::Time;
30 #[cfg(all(feature = "std", test))]
31 use crate::util::time::tests::SinceEpoch;
32 use crate::util::ser::ReadableArgs;
34 use core::fmt::{self, Display, Formatter};
36 use core::time::Duration;
38 use crate::prelude::*;
39 use crate::sync::Mutex;
41 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
42 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
44 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
45 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
47 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
48 /// and later, also stores information for retrying the payment.
49 pub(crate) enum PendingOutboundPayment {
51 session_privs: HashSet<[u8; 32]>,
54 expiration: StaleExpiration,
55 retry_strategy: Retry,
56 max_total_routing_fee_msat: Option<u64>,
59 payment_hash: PaymentHash,
60 retry_strategy: Retry,
61 // Note this field is currently just replicated from AwaitingInvoice but not actually
63 max_total_routing_fee_msat: Option<u64>,
66 retry_strategy: Option<Retry>,
67 attempts: PaymentAttempts,
68 payment_params: Option<PaymentParameters>,
69 session_privs: HashSet<[u8; 32]>,
70 payment_hash: PaymentHash,
71 payment_secret: Option<PaymentSecret>,
72 payment_metadata: Option<Vec<u8>>,
73 keysend_preimage: Option<PaymentPreimage>,
74 custom_tlvs: Vec<(u64, Vec<u8>)>,
75 pending_amt_msat: u64,
76 /// Used to track the fee paid. Present iff the payment was serialized on 0.0.103+.
77 pending_fee_msat: Option<u64>,
78 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
80 /// Our best known block height at the time this payment was initiated.
81 starting_block_height: u32,
82 remaining_max_total_routing_fee_msat: Option<u64>,
84 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
85 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
86 /// and add a pending payment that was already fulfilled.
88 session_privs: HashSet<[u8; 32]>,
89 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
90 payment_hash: Option<PaymentHash>,
91 timer_ticks_without_htlcs: u8,
93 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
94 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
96 session_privs: HashSet<[u8; 32]>,
97 payment_hash: PaymentHash,
98 /// Will be `None` if the payment was serialized before 0.0.115.
99 reason: Option<PaymentFailureReason>,
103 impl PendingOutboundPayment {
104 fn increment_attempts(&mut self) {
105 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
109 fn is_auto_retryable_now(&self) -> bool {
111 PendingOutboundPayment::Retryable {
112 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
114 strategy.is_retryable_now(&attempts)
119 fn is_retryable_now(&self) -> bool {
121 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
122 // We're handling retries manually, we can always retry.
125 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
126 strategy.is_retryable_now(&attempts)
131 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
132 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
133 params.previously_failed_channels.push(scid);
136 pub fn insert_previously_failed_blinded_path(&mut self, blinded_tail: &BlindedTail) {
137 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
138 params.insert_previously_failed_blinded_path(blinded_tail);
141 fn is_awaiting_invoice(&self) -> bool {
143 PendingOutboundPayment::AwaitingInvoice { .. } => true,
147 pub(super) fn is_fulfilled(&self) -> bool {
149 PendingOutboundPayment::Fulfilled { .. } => true,
153 pub(super) fn abandoned(&self) -> bool {
155 PendingOutboundPayment::Abandoned { .. } => true,
159 fn get_pending_fee_msat(&self) -> Option<u64> {
161 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
166 fn payment_hash(&self) -> Option<PaymentHash> {
168 PendingOutboundPayment::Legacy { .. } => None,
169 PendingOutboundPayment::AwaitingInvoice { .. } => None,
170 PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
171 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
172 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
173 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
177 fn mark_fulfilled(&mut self) {
178 let mut session_privs = new_hash_set();
179 core::mem::swap(&mut session_privs, match self {
180 PendingOutboundPayment::Legacy { session_privs } |
181 PendingOutboundPayment::Retryable { session_privs, .. } |
182 PendingOutboundPayment::Fulfilled { session_privs, .. } |
183 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
184 PendingOutboundPayment::AwaitingInvoice { .. } |
185 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
187 let payment_hash = self.payment_hash();
188 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
191 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
192 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
193 let mut our_session_privs = new_hash_set();
194 core::mem::swap(&mut our_session_privs, session_privs);
195 *self = PendingOutboundPayment::Abandoned {
196 session_privs: our_session_privs,
197 payment_hash: *payment_hash,
200 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash, .. } = self {
201 *self = PendingOutboundPayment::Abandoned {
202 session_privs: new_hash_set(),
203 payment_hash: *payment_hash,
209 /// panics if path is None and !self.is_fulfilled
210 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
211 let remove_res = match self {
212 PendingOutboundPayment::Legacy { session_privs } |
213 PendingOutboundPayment::Retryable { session_privs, .. } |
214 PendingOutboundPayment::Fulfilled { session_privs, .. } |
215 PendingOutboundPayment::Abandoned { session_privs, .. } => {
216 session_privs.remove(session_priv)
218 PendingOutboundPayment::AwaitingInvoice { .. } |
219 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
222 if let PendingOutboundPayment::Retryable {
223 ref mut pending_amt_msat, ref mut pending_fee_msat,
224 ref mut remaining_max_total_routing_fee_msat, ..
226 let path = path.expect("Removing a failed payment should always come with a path");
227 *pending_amt_msat -= path.final_value_msat();
228 let path_fee_msat = path.fee_msat();
229 if let Some(fee_msat) = pending_fee_msat.as_mut() {
230 *fee_msat -= path_fee_msat;
233 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
234 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
241 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
242 let insert_res = match self {
243 PendingOutboundPayment::Legacy { session_privs } |
244 PendingOutboundPayment::Retryable { session_privs, .. } => {
245 session_privs.insert(session_priv)
247 PendingOutboundPayment::AwaitingInvoice { .. } |
248 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
249 PendingOutboundPayment::Fulfilled { .. } => false,
250 PendingOutboundPayment::Abandoned { .. } => false,
253 if let PendingOutboundPayment::Retryable {
254 ref mut pending_amt_msat, ref mut pending_fee_msat,
255 ref mut remaining_max_total_routing_fee_msat, ..
257 *pending_amt_msat += path.final_value_msat();
258 let path_fee_msat = path.fee_msat();
259 if let Some(fee_msat) = pending_fee_msat.as_mut() {
260 *fee_msat += path_fee_msat;
263 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
264 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
271 pub(super) fn remaining_parts(&self) -> usize {
273 PendingOutboundPayment::Legacy { session_privs } |
274 PendingOutboundPayment::Retryable { session_privs, .. } |
275 PendingOutboundPayment::Fulfilled { session_privs, .. } |
276 PendingOutboundPayment::Abandoned { session_privs, .. } => {
279 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
280 PendingOutboundPayment::InvoiceReceived { .. } => 0,
285 /// Strategies available to retry payment path failures.
286 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
288 /// Max number of attempts to retry payment.
290 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
291 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
292 /// were retried along a route from a single call to [`Router::find_route_with_id`].
294 #[cfg(feature = "std")]
295 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
296 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
298 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
299 Timeout(core::time::Duration),
302 #[cfg(not(feature = "std"))]
303 impl_writeable_tlv_based_enum!(Retry,
308 #[cfg(feature = "std")]
309 impl_writeable_tlv_based_enum!(Retry,
316 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
317 match (self, attempts) {
318 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
319 max_retry_count > count
321 #[cfg(all(feature = "std", not(test)))]
322 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
323 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
324 #[cfg(all(feature = "std", test))]
325 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
326 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
331 #[cfg(feature = "std")]
332 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
333 if let Some(expiry_time) = route_params.payment_params.expiry_time {
334 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
335 return elapsed > core::time::Duration::from_secs(expiry_time)
341 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
343 /// Storing minimal payment attempts information required for determining if a outbound payment can
345 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
346 /// This count will be incremented only after the result of the attempt is known. When it's 0,
347 /// it means the result of the first attempt is not known yet.
348 pub(crate) count: u32,
349 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
350 #[cfg(feature = "std")]
351 first_attempted_at: T,
352 #[cfg(not(feature = "std"))]
353 phantom: core::marker::PhantomData<T>,
357 #[cfg(not(feature = "std"))]
358 type ConfiguredTime = crate::util::time::Eternity;
359 #[cfg(all(feature = "std", not(test)))]
360 type ConfiguredTime = crate::util::time::MonotonicTime;
361 #[cfg(all(feature = "std", test))]
362 type ConfiguredTime = SinceEpoch;
364 impl<T: Time> PaymentAttemptsUsingTime<T> {
365 pub(crate) fn new() -> Self {
366 PaymentAttemptsUsingTime {
368 #[cfg(feature = "std")]
369 first_attempted_at: T::now(),
370 #[cfg(not(feature = "std"))]
371 phantom: core::marker::PhantomData,
376 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
377 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
378 #[cfg(not(feature = "std"))]
379 return write!(f, "attempts: {}", self.count);
380 #[cfg(feature = "std")]
383 "attempts: {}, duration: {}s",
385 T::now().duration_since(self.first_attempted_at).as_secs()
390 /// How long before a [`PendingOutboundPayment::AwaitingInvoice`] should be considered stale and
391 /// candidate for removal in [`OutboundPayments::remove_stale_payments`].
392 #[derive(Clone, Copy)]
393 pub(crate) enum StaleExpiration {
394 /// Number of times [`OutboundPayments::remove_stale_payments`] is called.
396 /// Duration since the Unix epoch.
397 AbsoluteTimeout(core::time::Duration),
400 impl_writeable_tlv_based_enum!(StaleExpiration,
406 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
407 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
409 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
410 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
411 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
412 #[derive(Clone, Debug, PartialEq, Eq)]
413 pub enum RetryableSendFailure {
414 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
415 /// that this error is *not* caused by [`Retry::Timeout`].
417 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
419 /// We were unable to find a route to the destination.
421 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
422 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
424 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
425 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
426 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
428 /// The [`RecipientOnionFields::payment_metadata`], [`RecipientOnionFields::custom_tlvs`], or
429 /// [`BlindedPath`]s provided are too large and caused us to exceed the maximum onion packet size
432 /// [`BlindedPath`]: crate::blinded_path::BlindedPath
433 OnionPacketSizeExceeded,
436 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
437 /// of several states. This enum is returned as the Err() type describing which state the payment
438 /// is in, see the description of individual enum states for more.
440 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
441 #[derive(Clone, Debug, PartialEq, Eq)]
442 pub enum PaymentSendFailure {
443 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
444 /// send the payment at all.
446 /// You can freely resend the payment in full (with the parameter error fixed).
448 /// Because the payment failed outright, no payment tracking is done and no
449 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
451 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
452 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
453 ParameterError(APIError),
454 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
455 /// from attempting to send the payment at all.
457 /// You can freely resend the payment in full (with the parameter error fixed).
459 /// Because the payment failed outright, no payment tracking is done and no
460 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
462 /// The results here are ordered the same as the paths in the route object which was passed to
465 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
466 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
467 PathParameterError(Vec<Result<(), APIError>>),
468 /// All paths which were attempted failed to send, with no channel state change taking place.
469 /// You can freely resend the payment in full (though you probably want to do so over different
470 /// paths than the ones selected).
472 /// Because the payment failed outright, no payment tracking is done and no
473 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
475 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
476 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
477 AllFailedResendSafe(Vec<APIError>),
478 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
479 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
481 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
482 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
483 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
485 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
486 /// some paths have irrevocably committed to the HTLC.
488 /// The results here are ordered the same as the paths in the route object that was passed to
491 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
492 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
494 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
496 /// The errors themselves, in the same order as the paths from the route.
497 results: Vec<Result<(), APIError>>,
498 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
499 /// contain a [`RouteParameters`] object for the failing paths.
500 failed_paths_retry: Option<RouteParameters>,
501 /// The payment id for the payment, which is now at least partially pending.
502 payment_id: PaymentId,
506 /// An error when attempting to pay a [`Bolt12Invoice`].
507 #[derive(Clone, Debug, PartialEq, Eq)]
508 pub enum Bolt12PaymentError {
509 /// The invoice was not requested.
511 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
515 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
516 /// [`Event::ProbeFailed`].
518 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
519 #[derive(Clone, Debug, PartialEq, Eq)]
520 pub enum ProbeSendFailure {
521 /// We were unable to find a route to the destination.
523 /// We failed to send the payment probes.
524 SendingFailed(PaymentSendFailure),
527 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
529 /// This should generally be constructed with data communicated to us from the recipient (via a
530 /// BOLT11 or BOLT12 invoice).
531 #[derive(Clone, Debug, PartialEq, Eq)]
532 pub struct RecipientOnionFields {
533 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
534 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
535 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
538 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
539 /// multi-path payments require a recipient-provided secret.
541 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
542 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
543 /// recipient will not reject it.
544 pub payment_secret: Option<PaymentSecret>,
545 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
546 /// arbitrary length. This gives recipients substantially more flexibility to receive
549 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
550 /// scheme to authenticate received payments against expected payments and invoices, this field
551 /// is not used in LDK for received payments, and can be used to store arbitrary data in
552 /// invoices which will be received with the payment.
554 /// Note that this field was added to the lightning specification more recently than
555 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
556 /// may not be supported as universally.
557 pub payment_metadata: Option<Vec<u8>>,
558 /// See [`Self::custom_tlvs`] for more info.
559 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
562 impl_writeable_tlv_based!(RecipientOnionFields, {
563 (0, payment_secret, option),
564 (1, custom_tlvs, optional_vec),
565 (2, payment_metadata, option),
568 impl RecipientOnionFields {
569 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
570 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
571 /// but do not require or provide any further data.
572 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
573 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
576 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
577 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
578 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
579 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
580 /// instead want to use [`RecipientOnionFields::secret_only`].
582 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
583 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
584 pub fn spontaneous_empty() -> Self {
585 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
588 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
589 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
590 /// respectively. TLV type numbers must be unique and within the range
591 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
593 /// This method will also error for types in the experimental range which have been
594 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
596 /// See [`Self::custom_tlvs`] for more info.
597 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
598 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
599 let mut prev_type = None;
600 for (typ, _) in custom_tlvs.iter() {
601 if *typ < 1 << 16 { return Err(()); }
602 if *typ == 5482373484 { return Err(()); } // keysend
604 Some(prev) if prev >= *typ => return Err(()),
607 prev_type = Some(*typ);
609 self.custom_tlvs = custom_tlvs;
613 /// Gets the custom TLVs that will be sent or have been received.
615 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
616 /// additional flexibility on top of payment metadata, as while other implementations may
617 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
618 /// do not have this restriction.
620 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
621 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
622 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
623 #[cfg(not(c_bindings))]
624 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
628 /// Gets the custom TLVs that will be sent or have been received.
630 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
631 /// additional flexibility on top of payment metadata, as while other implementations may
632 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
633 /// do not have this restriction.
635 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
636 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
637 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
639 pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
640 self.custom_tlvs.clone()
643 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
644 /// have to make sure that some fields match exactly across the parts. For those that aren't
645 /// required to match, if they don't match we should remove them so as to not expose data
646 /// that's dependent on the HTLC receive order to users.
648 /// Here we implement this, first checking compatibility then mutating two objects and then
649 /// dropping any remaining non-matching fields from both.
650 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
651 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
652 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
654 let tlvs = &mut self.custom_tlvs;
655 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
657 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
658 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
659 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
661 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
662 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
668 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
669 pub(super) struct SendAlongPathArgs<'a> {
671 pub payment_hash: &'a PaymentHash,
672 pub recipient_onion: &'a RecipientOnionFields,
673 pub total_value: u64,
675 pub payment_id: PaymentId,
676 pub keysend_preimage: &'a Option<PaymentPreimage>,
677 pub session_priv_bytes: [u8; 32],
680 pub(super) struct OutboundPayments {
681 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
682 pub(super) retry_lock: Mutex<()>,
685 impl OutboundPayments {
686 pub(super) fn new() -> Self {
688 pending_outbound_payments: Mutex::new(new_hash_map()),
689 retry_lock: Mutex::new(()),
693 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
694 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
695 retry_strategy: Retry, route_params: RouteParameters, router: &R,
696 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
697 node_signer: &NS, best_block_height: u32, logger: &L,
698 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
699 ) -> Result<(), RetryableSendFailure>
702 ES::Target: EntropySource,
703 NS::Target: NodeSigner,
705 IH: Fn() -> InFlightHtlcs,
706 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
708 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
709 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
710 best_block_height, logger, pending_events, &send_payment_along_path)
713 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
714 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
715 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
716 send_payment_along_path: F
717 ) -> Result<(), PaymentSendFailure>
719 ES::Target: EntropySource,
720 NS::Target: NodeSigner,
721 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
723 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)?;
724 self.pay_route_internal(route, payment_hash, &recipient_onion, None, payment_id, None,
725 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
726 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
729 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
730 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
731 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
732 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
733 node_signer: &NS, best_block_height: u32, logger: &L,
734 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
735 ) -> Result<PaymentHash, RetryableSendFailure>
738 ES::Target: EntropySource,
739 NS::Target: NodeSigner,
741 IH: Fn() -> InFlightHtlcs,
742 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
744 let preimage = payment_preimage
745 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
746 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
747 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
748 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
749 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
750 .map(|()| payment_hash)
753 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
754 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
755 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
756 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
757 ) -> Result<PaymentHash, PaymentSendFailure>
759 ES::Target: EntropySource,
760 NS::Target: NodeSigner,
761 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
763 let preimage = payment_preimage
764 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
765 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
766 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
767 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
769 match self.pay_route_internal(route, payment_hash, &recipient_onion, Some(preimage),
770 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
772 Ok(()) => Ok(payment_hash),
774 self.remove_outbound_if_all_failed(payment_id, &e);
780 pub(super) fn send_payment_for_bolt12_invoice<
781 R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
783 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
784 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
785 node_id_lookup: &NL, secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32,
787 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
788 send_payment_along_path: SP,
789 ) -> Result<(), Bolt12PaymentError>
792 ES::Target: EntropySource,
793 NS::Target: NodeSigner,
794 NL::Target: NodeIdLookUp,
796 IH: Fn() -> InFlightHtlcs,
797 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
799 let payment_hash = invoice.payment_hash();
800 let max_total_routing_fee_msat;
801 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
802 hash_map::Entry::Occupied(entry) => match entry.get() {
803 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
804 max_total_routing_fee_msat = *max_total_fee;
805 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
807 retry_strategy: *retry_strategy,
808 max_total_routing_fee_msat,
811 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
813 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
816 let mut payment_params = PaymentParameters::from_bolt12_invoice(&invoice);
818 // Advance any blinded path where the introduction node is our node.
819 if let Ok(our_node_id) = node_signer.get_node_id(Recipient::Node) {
820 for (_, path) in payment_params.payee.blinded_route_hints_mut().iter_mut() {
821 let introduction_node_id = match path.introduction_node {
822 IntroductionNode::NodeId(pubkey) => pubkey,
823 IntroductionNode::DirectedShortChannelId(direction, scid) => {
824 match node_id_lookup.next_node_id(scid) {
825 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
830 if introduction_node_id == our_node_id {
831 let _ = advance_path_by_one(path, node_signer, node_id_lookup, secp_ctx);
836 let amount_msat = invoice.amount_msats();
837 let mut route_params = RouteParameters::from_payment_params_and_value(
838 payment_params, amount_msat
840 if let Some(max_fee_msat) = max_total_routing_fee_msat {
841 route_params.max_total_routing_fee_msat = Some(max_fee_msat);
844 self.find_route_and_send_payment(
845 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
846 entropy_source, node_signer, best_block_height, logger, pending_events,
847 &send_payment_along_path
853 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
854 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
855 best_block_height: u32,
856 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
857 send_payment_along_path: SP,
861 ES::Target: EntropySource,
862 NS::Target: NodeSigner,
863 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
864 IH: Fn() -> InFlightHtlcs,
865 FH: Fn() -> Vec<ChannelDetails>,
868 let _single_thread = self.retry_lock.lock().unwrap();
870 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
871 let mut retry_id_route_params = None;
872 for (pmt_id, pmt) in outbounds.iter_mut() {
873 if pmt.is_auto_retryable_now() {
874 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
875 if pending_amt_msat < total_msat {
876 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
877 final_value_msat: *total_msat - *pending_amt_msat,
878 payment_params: params.clone(),
879 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
883 } else { debug_assert!(false); }
886 core::mem::drop(outbounds);
887 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
888 self.find_route_and_send_payment(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)
892 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
893 outbounds.retain(|pmt_id, pmt| {
894 let mut retain = true;
895 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
896 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
897 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
898 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
900 payment_hash: *payment_hash,
910 pub(super) fn needs_abandon(&self) -> bool {
911 let outbounds = self.pending_outbound_payments.lock().unwrap();
912 outbounds.iter().any(|(_, pmt)|
913 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
914 !pmt.is_awaiting_invoice())
917 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
918 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
920 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
921 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
922 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
923 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
924 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, mut route_params: RouteParameters,
925 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
926 node_signer: &NS, best_block_height: u32, logger: &L,
927 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
928 ) -> Result<(), RetryableSendFailure>
931 ES::Target: EntropySource,
932 NS::Target: NodeSigner,
934 IH: Fn() -> InFlightHtlcs,
935 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
937 #[cfg(feature = "std")] {
938 if has_expired(&route_params) {
939 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
940 payment_id, payment_hash);
941 return Err(RetryableSendFailure::PaymentExpired)
945 onion_utils::set_max_path_length(
946 &mut route_params, &recipient_onion, keysend_preimage, best_block_height
949 log_error!(logger, "Can't construct an onion packet without exceeding 1300-byte onion \
950 hop_data length for payment with id {} and hash {}", payment_id, payment_hash);
951 RetryableSendFailure::OnionPacketSizeExceeded
954 let mut route = router.find_route_with_id(
955 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
956 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
957 payment_hash, payment_id,
959 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
960 payment_id, payment_hash);
961 RetryableSendFailure::RouteNotFound
964 if route.route_params.as_ref() != Some(&route_params) {
966 "Routers are expected to return a Route which includes the requested RouteParameters");
967 route.route_params = Some(route_params.clone());
970 let onion_session_privs = self.add_new_pending_payment(payment_hash,
971 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
972 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
974 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
975 payment_id, payment_hash);
976 RetryableSendFailure::DuplicatePayment
979 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion,
980 keysend_preimage, payment_id, None, onion_session_privs, node_signer,
981 best_block_height, &send_payment_along_path);
982 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
983 payment_id, payment_hash, res);
984 if let Err(e) = res {
985 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);
990 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
991 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
992 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
993 node_signer: &NS, best_block_height: u32, logger: &L,
994 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
998 ES::Target: EntropySource,
999 NS::Target: NodeSigner,
1001 IH: Fn() -> InFlightHtlcs,
1002 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1004 #[cfg(feature = "std")] {
1005 if has_expired(&route_params) {
1006 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
1007 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
1012 let mut route = match router.find_route_with_id(
1013 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
1014 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
1015 payment_hash, payment_id,
1019 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
1020 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
1025 if route.route_params.as_ref() != Some(&route_params) {
1026 debug_assert!(false,
1027 "Routers are expected to return a Route which includes the requested RouteParameters");
1028 route.route_params = Some(route_params.clone());
1031 for path in route.paths.iter() {
1032 if path.hops.len() == 0 {
1033 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
1034 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1039 macro_rules! abandon_with_entry {
1040 ($payment: expr, $reason: expr) => {
1041 $payment.get_mut().mark_abandoned($reason);
1042 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
1043 if $payment.get().remaining_parts() == 0 {
1044 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1054 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
1055 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1056 match outbounds.entry(payment_id) {
1057 hash_map::Entry::Occupied(mut payment) => {
1058 match payment.get() {
1059 PendingOutboundPayment::Retryable {
1060 total_msat, keysend_preimage, payment_secret, payment_metadata,
1061 custom_tlvs, pending_amt_msat, ..
1063 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1064 let retry_amt_msat = route.get_total_amount();
1065 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1066 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);
1067 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1071 if !payment.get().is_retryable_now() {
1072 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1073 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1077 let total_msat = *total_msat;
1078 let recipient_onion = RecipientOnionFields {
1079 payment_secret: *payment_secret,
1080 payment_metadata: payment_metadata.clone(),
1081 custom_tlvs: custom_tlvs.clone(),
1083 let keysend_preimage = *keysend_preimage;
1085 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1086 for _ in 0..route.paths.len() {
1087 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1090 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1091 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1094 payment.get_mut().increment_attempts();
1096 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1098 PendingOutboundPayment::Legacy { .. } => {
1099 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1102 PendingOutboundPayment::AwaitingInvoice { .. } => {
1103 log_error!(logger, "Payment not yet sent");
1106 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1107 let total_amount = route_params.final_value_msat;
1108 let recipient_onion = RecipientOnionFields {
1109 payment_secret: None,
1110 payment_metadata: None,
1111 custom_tlvs: vec![],
1113 let retry_strategy = Some(*retry_strategy);
1114 let payment_params = Some(route_params.payment_params.clone());
1115 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1116 *payment_hash, recipient_onion.clone(), None, &route,
1117 retry_strategy, payment_params, entropy_source, best_block_height
1119 *payment.into_mut() = retryable_payment;
1120 (total_amount, recipient_onion, None, onion_session_privs)
1122 PendingOutboundPayment::Fulfilled { .. } => {
1123 log_error!(logger, "Payment already completed");
1126 PendingOutboundPayment::Abandoned { .. } => {
1127 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1132 hash_map::Entry::Vacant(_) => {
1133 log_error!(logger, "Payment with ID {} not found", &payment_id);
1138 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion, keysend_preimage,
1139 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1140 &send_payment_along_path);
1141 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1142 if let Err(e) = res {
1143 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);
1147 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1148 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1149 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1150 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1151 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1155 ES::Target: EntropySource,
1156 NS::Target: NodeSigner,
1158 IH: Fn() -> InFlightHtlcs,
1159 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1162 PaymentSendFailure::AllFailedResendSafe(errs) => {
1163 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);
1164 self.find_route_and_send_payment(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);
1166 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1167 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1168 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1169 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1170 // return `Ok()` here, ignoring any retry errors.
1171 self.find_route_and_send_payment(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
1173 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1174 // This may happen if we send a payment and some paths fail, but only due to a temporary
1175 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1176 // initial HTLC-Add messages yet.
1178 PaymentSendFailure::PathParameterError(results) => {
1179 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1180 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1181 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1183 PaymentSendFailure::ParameterError(e) => {
1184 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1185 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1187 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1191 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1192 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1193 paths: Vec<Path>, path_results: I, logger: &L,
1194 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1195 ) where L::Target: Logger {
1196 let mut events = pending_events.lock().unwrap();
1197 debug_assert_eq!(paths.len(), path_results.len());
1198 for (path, path_res) in paths.into_iter().zip(path_results) {
1199 if let Err(e) = path_res {
1200 if let APIError::MonitorUpdateInProgress = e { continue }
1201 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1202 let mut failed_scid = None;
1203 if let APIError::ChannelUnavailable { .. } = e {
1204 let scid = path.hops[0].short_channel_id;
1205 failed_scid = Some(scid);
1206 route_params.payment_params.previously_failed_channels.push(scid);
1208 events.push_back((events::Event::PaymentPathFailed {
1209 payment_id: Some(payment_id),
1211 payment_failed_permanently: false,
1212 failure: events::PathFailure::InitialSend { err: e },
1214 short_channel_id: failed_scid,
1224 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1225 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1226 best_block_height: u32, send_payment_along_path: F
1227 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1229 ES::Target: EntropySource,
1230 NS::Target: NodeSigner,
1231 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1233 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1234 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1236 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1238 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1239 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1240 err: "No need probing a path with less than two hops".to_string()
1244 let route = Route { paths: vec![path], route_params: None };
1245 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1246 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1247 entropy_source, best_block_height)?;
1249 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1250 match self.pay_route_internal(&route, payment_hash, &recipient_onion_fields,
1251 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1253 Ok(()) => Ok((payment_hash, payment_id)),
1255 self.remove_outbound_if_all_failed(payment_id, &e);
1262 pub(super) fn test_set_payment_metadata(
1263 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1265 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1266 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1267 *payment_metadata = new_payment_metadata;
1269 _ => panic!("Need a retryable payment to update metadata on"),
1274 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1275 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1276 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1277 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1278 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1281 pub(super) fn add_new_pending_payment<ES: Deref>(
1282 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1283 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1284 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1285 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1286 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1287 match pending_outbounds.entry(payment_id) {
1288 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1289 hash_map::Entry::Vacant(entry) => {
1290 let (payment, onion_session_privs) = self.create_pending_payment(
1291 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1292 payment_params, entropy_source, best_block_height
1294 entry.insert(payment);
1295 Ok(onion_session_privs)
1300 fn create_pending_payment<ES: Deref>(
1301 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1302 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1303 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1304 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1306 ES::Target: EntropySource,
1308 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1309 for _ in 0..route.paths.len() {
1310 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1313 let mut payment = PendingOutboundPayment::Retryable {
1315 attempts: PaymentAttempts::new(),
1317 session_privs: new_hash_set(),
1318 pending_amt_msat: 0,
1319 pending_fee_msat: Some(0),
1321 payment_secret: recipient_onion.payment_secret,
1322 payment_metadata: recipient_onion.payment_metadata,
1324 custom_tlvs: recipient_onion.custom_tlvs,
1325 starting_block_height: best_block_height,
1326 total_msat: route.get_total_amount(),
1327 remaining_max_total_routing_fee_msat:
1328 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1331 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1332 assert!(payment.insert(*session_priv_bytes, path));
1335 (payment, onion_session_privs)
1338 pub(super) fn add_new_awaiting_invoice(
1339 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1340 max_total_routing_fee_msat: Option<u64>
1341 ) -> Result<(), ()> {
1342 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1343 match pending_outbounds.entry(payment_id) {
1344 hash_map::Entry::Occupied(_) => Err(()),
1345 hash_map::Entry::Vacant(entry) => {
1346 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1349 max_total_routing_fee_msat,
1357 fn pay_route_internal<NS: Deref, F>(
1358 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
1359 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1360 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1361 send_payment_along_path: &F
1362 ) -> Result<(), PaymentSendFailure>
1364 NS::Target: NodeSigner,
1365 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1367 if route.paths.len() < 1 {
1368 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1370 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1371 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1373 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1375 let mut total_value = 0;
1376 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1377 let mut path_errs = Vec::with_capacity(route.paths.len());
1378 'path_check: for path in route.paths.iter() {
1379 if path.hops.len() < 1 || path.hops.len() > 20 {
1380 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1381 continue 'path_check;
1383 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1384 usize::max_value() } else { path.hops.len() - 1 };
1385 for (idx, hop) in path.hops.iter().enumerate() {
1386 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1387 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1388 continue 'path_check;
1391 for (i, hop) in path.hops.iter().enumerate() {
1392 // Check for duplicate channel_id in the remaining hops of the path
1393 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1394 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1395 continue 'path_check;
1398 total_value += path.final_value_msat();
1399 path_errs.push(Ok(()));
1401 if path_errs.iter().any(|e| e.is_err()) {
1402 return Err(PaymentSendFailure::PathParameterError(path_errs));
1404 if let Some(amt_msat) = recv_value_msat {
1405 total_value = amt_msat;
1408 let cur_height = best_block_height + 1;
1409 let mut results = Vec::new();
1410 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1411 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1412 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1413 path: &path, payment_hash: &payment_hash, recipient_onion, total_value,
1414 cur_height, payment_id, keysend_preimage: &keysend_preimage,
1419 Err(APIError::MonitorUpdateInProgress) => {
1420 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1421 // considered "in flight" and we shouldn't remove it from the
1422 // PendingOutboundPayment set.
1425 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1426 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1427 let removed = payment.remove(&session_priv_bytes, Some(path));
1428 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1430 debug_assert!(false, "This can't happen as the payment was added by callers");
1431 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1435 results.push(path_res);
1437 let mut has_ok = false;
1438 let mut has_err = false;
1439 let mut has_unsent = false;
1440 let mut total_ok_fees_msat = 0;
1441 let mut total_ok_amt_sent_msat = 0;
1442 for (res, path) in results.iter().zip(route.paths.iter()) {
1445 total_ok_fees_msat += path.fee_msat();
1446 total_ok_amt_sent_msat += path.final_value_msat();
1448 if res.is_err() { has_err = true; }
1449 if let &Err(APIError::MonitorUpdateInProgress) = res {
1450 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1454 total_ok_fees_msat += path.fee_msat();
1455 total_ok_amt_sent_msat += path.final_value_msat();
1456 } else if res.is_err() {
1460 if has_err && has_ok {
1461 Err(PaymentSendFailure::PartialFailure {
1464 failed_paths_retry: if has_unsent {
1465 if let Some(route_params) = &route.route_params {
1466 let mut route_params = route_params.clone();
1467 // We calculate the leftover fee budget we're allowed to spend by
1468 // subtracting the used fee from the total fee budget.
1469 route_params.max_total_routing_fee_msat = route_params
1470 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1472 // We calculate the remaining target amount by subtracting the succeded
1474 route_params.final_value_msat = route_params.final_value_msat
1475 .saturating_sub(total_ok_amt_sent_msat);
1481 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1488 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1489 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1490 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1491 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1492 send_payment_along_path: F
1493 ) -> Result<(), PaymentSendFailure>
1495 NS::Target: NodeSigner,
1496 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1498 self.pay_route_internal(route, payment_hash, &recipient_onion,
1499 keysend_preimage, payment_id, recv_value_msat, onion_session_privs,
1500 node_signer, best_block_height, &send_payment_along_path)
1501 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1504 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1505 // map as the payment is free to be resent.
1506 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1507 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1508 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1509 debug_assert!(removed, "We should always have a pending payment to remove here");
1513 pub(super) fn claim_htlc<L: Deref>(
1514 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1515 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1516 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1518 ) where L::Target: Logger {
1519 let mut session_priv_bytes = [0; 32];
1520 session_priv_bytes.copy_from_slice(&session_priv[..]);
1521 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1522 let mut pending_events = pending_events.lock().unwrap();
1523 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1524 if !payment.get().is_fulfilled() {
1525 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1526 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1527 let fee_paid_msat = payment.get().get_pending_fee_msat();
1528 pending_events.push_back((events::Event::PaymentSent {
1529 payment_id: Some(payment_id),
1533 }, Some(ev_completion_action.clone())));
1534 payment.get_mut().mark_fulfilled();
1538 // We currently immediately remove HTLCs which were fulfilled on-chain.
1539 // This could potentially lead to removing a pending payment too early,
1540 // with a reorg of one block causing us to re-add the fulfilled payment on
1542 // TODO: We should have a second monitor event that informs us of payments
1543 // irrevocably fulfilled.
1544 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1545 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1546 pending_events.push_back((events::Event::PaymentPathSuccessful {
1550 }, Some(ev_completion_action)));
1554 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1558 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1559 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1561 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1562 let mut pending_events = pending_events.lock().unwrap();
1563 for source in sources {
1564 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1565 let mut session_priv_bytes = [0; 32];
1566 session_priv_bytes.copy_from_slice(&session_priv[..]);
1567 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1568 assert!(payment.get().is_fulfilled());
1569 if payment.get_mut().remove(&session_priv_bytes, None) {
1570 let payment_hash = payment.get().payment_hash();
1571 debug_assert!(payment_hash.is_some());
1572 pending_events.push_back((events::Event::PaymentPathSuccessful {
1583 pub(super) fn remove_stale_payments(
1584 &self, duration_since_epoch: Duration,
1585 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1587 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1588 let mut pending_events = pending_events.lock().unwrap();
1589 pending_outbound_payments.retain(|payment_id, payment| match payment {
1590 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1591 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1592 // this could race the user making a duplicate send_payment call and our idempotency
1593 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1594 // removal. This should be more than sufficient to ensure the idempotency of any
1595 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1597 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1598 let mut no_remaining_entries = session_privs.is_empty();
1599 if no_remaining_entries {
1600 for (ev, _) in pending_events.iter() {
1602 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1603 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1604 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1605 if payment_id == ev_payment_id {
1606 no_remaining_entries = false;
1614 if no_remaining_entries {
1615 *timer_ticks_without_htlcs += 1;
1616 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1618 *timer_ticks_without_htlcs = 0;
1622 PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1623 let is_stale = match expiration {
1624 StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1625 *absolute_expiry <= duration_since_epoch
1627 StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1628 if *timer_ticks_remaining > 0 {
1629 *timer_ticks_remaining -= 1;
1637 pending_events.push_back(
1638 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1649 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1650 pub(super) fn fail_htlc<L: Deref>(
1651 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1652 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1653 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1654 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1655 ) -> bool where L::Target: Logger {
1657 let DecodedOnionFailure {
1658 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1659 onion_error_data, failed_within_blinded_path
1660 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1662 let DecodedOnionFailure {
1663 network_update, short_channel_id, payment_failed_permanently, failed_within_blinded_path
1664 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1666 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1667 let mut session_priv_bytes = [0; 32];
1668 session_priv_bytes.copy_from_slice(&session_priv[..]);
1669 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1671 // If any payments already need retry, there's no need to generate a redundant
1672 // `PendingHTLCsForwardable`.
1673 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1674 let mut awaiting_retry = false;
1675 if pmt.is_auto_retryable_now() {
1676 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1677 if pending_amt_msat < total_msat {
1678 awaiting_retry = true;
1685 let mut full_failure_ev = None;
1686 let mut pending_retry_ev = false;
1687 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1688 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1689 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1692 if payment.get().is_fulfilled() {
1693 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1696 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1697 if let Some(scid) = short_channel_id {
1698 // TODO: If we decided to blame ourselves (or one of our channels) in
1699 // process_onion_failure we should close that channel as it implies our
1700 // next-hop is needlessly blaming us!
1701 payment.get_mut().insert_previously_failed_scid(scid);
1703 if failed_within_blinded_path {
1704 debug_assert!(short_channel_id.is_none());
1705 if let Some(bt) = &path.blinded_tail {
1706 payment.get_mut().insert_previously_failed_blinded_path(&bt);
1707 } else { debug_assert!(false); }
1710 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1711 let reason = if payment_failed_permanently {
1712 PaymentFailureReason::RecipientRejected
1714 PaymentFailureReason::RetriesExhausted
1716 payment.get_mut().mark_abandoned(reason);
1717 is_retryable_now = false;
1719 if payment.get().remaining_parts() == 0 {
1720 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1721 if !payment_is_probe {
1722 full_failure_ev = Some(events::Event::PaymentFailed {
1723 payment_id: *payment_id,
1724 payment_hash: *payment_hash,
1733 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1736 core::mem::drop(outbounds);
1737 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1739 let path_failure = {
1740 if payment_is_probe {
1741 if payment_failed_permanently {
1742 events::Event::ProbeSuccessful {
1743 payment_id: *payment_id,
1744 payment_hash: payment_hash.clone(),
1748 events::Event::ProbeFailed {
1749 payment_id: *payment_id,
1750 payment_hash: payment_hash.clone(),
1756 // If we miss abandoning the payment above, we *must* generate an event here or else the
1757 // payment will sit in our outbounds forever.
1758 if attempts_remaining && !already_awaiting_retry {
1759 debug_assert!(full_failure_ev.is_none());
1760 pending_retry_ev = true;
1762 events::Event::PaymentPathFailed {
1763 payment_id: Some(*payment_id),
1764 payment_hash: payment_hash.clone(),
1765 payment_failed_permanently,
1766 failure: events::PathFailure::OnPath { network_update },
1770 error_code: onion_error_code,
1772 error_data: onion_error_data
1776 let mut pending_events = pending_events.lock().unwrap();
1777 pending_events.push_back((path_failure, None));
1778 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1782 pub(super) fn abandon_payment(
1783 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1784 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1786 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1787 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1788 payment.get_mut().mark_abandoned(reason);
1789 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1790 if payment.get().remaining_parts() == 0 {
1791 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1793 payment_hash: *payment_hash,
1798 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1799 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1808 pub fn has_pending_payments(&self) -> bool {
1809 !self.pending_outbound_payments.lock().unwrap().is_empty()
1813 pub fn clear_pending_payments(&self) {
1814 self.pending_outbound_payments.lock().unwrap().clear()
1818 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1820 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1821 probing_cookie_secret: [u8; 32]) -> bool
1823 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1824 target_payment_hash == *payment_hash
1827 /// Returns the 'probing cookie' for the given [`PaymentId`].
1828 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1829 let mut preimage = [0u8; 64];
1830 preimage[..32].copy_from_slice(&probing_cookie_secret);
1831 preimage[32..].copy_from_slice(&payment_id.0);
1832 PaymentHash(Sha256::hash(&preimage).to_byte_array())
1835 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1837 (0, session_privs, required),
1840 (0, session_privs, required),
1841 (1, payment_hash, option),
1842 (3, timer_ticks_without_htlcs, (default_value, 0)),
1845 (0, session_privs, required),
1846 (1, pending_fee_msat, option),
1847 (2, payment_hash, required),
1848 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1849 // never see it - `payment_params` was added here after the field was added/required.
1850 (3, payment_params, (option: ReadableArgs, 0)),
1851 (4, payment_secret, option),
1852 (5, keysend_preimage, option),
1853 (6, total_msat, required),
1854 (7, payment_metadata, option),
1855 (8, pending_amt_msat, required),
1856 (9, custom_tlvs, optional_vec),
1857 (10, starting_block_height, required),
1858 (11, remaining_max_total_routing_fee_msat, option),
1859 (not_written, retry_strategy, (static_value, None)),
1860 (not_written, attempts, (static_value, PaymentAttempts::new())),
1863 (0, session_privs, required),
1864 (1, reason, option),
1865 (2, payment_hash, required),
1867 (5, AwaitingInvoice) => {
1868 (0, expiration, required),
1869 (2, retry_strategy, required),
1870 (4, max_total_routing_fee_msat, option),
1872 (7, InvoiceReceived) => {
1873 (0, payment_hash, required),
1874 (2, retry_strategy, required),
1875 (4, max_total_routing_fee_msat, option),
1881 use bitcoin::network::Network;
1882 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1884 use core::time::Duration;
1886 use crate::blinded_path::EmptyNodeIdLookUp;
1887 use crate::events::{Event, PathFailure, PaymentFailureReason};
1888 use crate::ln::types::PaymentHash;
1889 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1890 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1891 use crate::ln::msgs::{ErrorAction, LightningError};
1892 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1893 #[cfg(feature = "std")]
1894 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1895 use crate::offers::offer::OfferBuilder;
1896 use crate::offers::test_utils::*;
1897 use crate::routing::gossip::NetworkGraph;
1898 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1899 use crate::sync::{Arc, Mutex, RwLock};
1900 use crate::util::errors::APIError;
1901 use crate::util::test_utils;
1903 use alloc::collections::VecDeque;
1906 fn test_recipient_onion_fields_with_custom_tlvs() {
1907 let onion_fields = RecipientOnionFields::spontaneous_empty();
1909 let bad_type_range_tlvs = vec![
1913 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1915 let keysend_tlv = vec![
1916 (5482373484, vec![42; 32]),
1918 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1920 let good_tlvs = vec![
1921 ((1 << 16) + 1, vec![42]),
1922 ((1 << 16) + 3, vec![42; 32]),
1924 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1928 #[cfg(feature = "std")]
1929 fn fails_paying_after_expiration() {
1930 do_fails_paying_after_expiration(false);
1931 do_fails_paying_after_expiration(true);
1933 #[cfg(feature = "std")]
1934 fn do_fails_paying_after_expiration(on_retry: bool) {
1935 let outbound_payments = OutboundPayments::new();
1936 let logger = test_utils::TestLogger::new();
1937 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1938 let scorer = RwLock::new(test_utils::TestScorer::new());
1939 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1940 let secp_ctx = Secp256k1::new();
1941 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1943 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1944 let payment_params = PaymentParameters::from_node_id(
1945 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1947 ).with_expiry_time(past_expiry_time);
1948 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1949 let pending_events = Mutex::new(VecDeque::new());
1951 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1952 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1953 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1954 &&keys_manager, 0).unwrap();
1955 outbound_payments.find_route_and_send_payment(
1956 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1957 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1959 let events = pending_events.lock().unwrap();
1960 assert_eq!(events.len(), 1);
1961 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1962 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1963 } else { panic!("Unexpected event"); }
1965 let err = outbound_payments.send_payment(
1966 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1967 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1968 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1969 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1974 fn find_route_error() {
1975 do_find_route_error(false);
1976 do_find_route_error(true);
1978 fn do_find_route_error(on_retry: bool) {
1979 let outbound_payments = OutboundPayments::new();
1980 let logger = test_utils::TestLogger::new();
1981 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1982 let scorer = RwLock::new(test_utils::TestScorer::new());
1983 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1984 let secp_ctx = Secp256k1::new();
1985 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1987 let payment_params = PaymentParameters::from_node_id(
1988 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1989 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1990 router.expect_find_route(route_params.clone(),
1991 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1993 let pending_events = Mutex::new(VecDeque::new());
1995 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1996 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1997 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1998 &&keys_manager, 0).unwrap();
1999 outbound_payments.find_route_and_send_payment(
2000 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
2001 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2003 let events = pending_events.lock().unwrap();
2004 assert_eq!(events.len(), 1);
2005 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
2007 let err = outbound_payments.send_payment(
2008 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2009 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
2010 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
2011 if let RetryableSendFailure::RouteNotFound = err {
2012 } else { panic!("Unexpected error"); }
2017 fn initial_send_payment_path_failed_evs() {
2018 let outbound_payments = OutboundPayments::new();
2019 let logger = test_utils::TestLogger::new();
2020 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2021 let scorer = RwLock::new(test_utils::TestScorer::new());
2022 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2023 let secp_ctx = Secp256k1::new();
2024 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2026 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2027 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
2028 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
2029 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
2030 let failed_scid = 42;
2032 paths: vec![Path { hops: vec![RouteHop {
2033 pubkey: receiver_pk,
2034 node_features: NodeFeatures::empty(),
2035 short_channel_id: failed_scid,
2036 channel_features: ChannelFeatures::empty(),
2038 cltv_expiry_delta: 0,
2039 maybe_announced_channel: true,
2040 }], blinded_tail: None }],
2041 route_params: Some(route_params.clone()),
2043 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2044 let mut route_params_w_failed_scid = route_params.clone();
2045 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
2046 let mut route_w_failed_scid = route.clone();
2047 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
2048 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
2049 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2050 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2052 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
2053 // PaymentPathFailed event.
2054 let pending_events = Mutex::new(VecDeque::new());
2055 outbound_payments.send_payment(
2056 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2057 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2058 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2059 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2060 let mut events = pending_events.lock().unwrap();
2061 assert_eq!(events.len(), 2);
2062 if let Event::PaymentPathFailed {
2064 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2066 assert_eq!(short_channel_id, Some(failed_scid));
2067 } else { panic!("Unexpected event"); }
2068 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2070 core::mem::drop(events);
2072 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2073 outbound_payments.send_payment(
2074 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2075 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2076 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2077 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2078 assert_eq!(pending_events.lock().unwrap().len(), 0);
2080 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2081 outbound_payments.send_payment(
2082 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2083 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2084 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2085 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2086 let events = pending_events.lock().unwrap();
2087 assert_eq!(events.len(), 2);
2088 if let Event::PaymentPathFailed {
2090 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2092 assert_eq!(short_channel_id, None);
2093 } else { panic!("Unexpected event"); }
2094 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2098 fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2099 let pending_events = Mutex::new(VecDeque::new());
2100 let outbound_payments = OutboundPayments::new();
2101 let payment_id = PaymentId([0; 32]);
2102 let absolute_expiry = 100;
2103 let tick_interval = 10;
2104 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2106 assert!(!outbound_payments.has_pending_payments());
2108 outbound_payments.add_new_awaiting_invoice(
2109 payment_id, expiration, Retry::Attempts(0), None
2112 assert!(outbound_payments.has_pending_payments());
2114 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2115 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2116 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2118 assert!(outbound_payments.has_pending_payments());
2119 assert!(pending_events.lock().unwrap().is_empty());
2122 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2123 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2125 assert!(!outbound_payments.has_pending_payments());
2126 assert!(!pending_events.lock().unwrap().is_empty());
2128 pending_events.lock().unwrap().pop_front(),
2129 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2131 assert!(pending_events.lock().unwrap().is_empty());
2134 outbound_payments.add_new_awaiting_invoice(
2135 payment_id, expiration, Retry::Attempts(0), None
2138 assert!(outbound_payments.has_pending_payments());
2141 outbound_payments.add_new_awaiting_invoice(
2142 payment_id, expiration, Retry::Attempts(0), None
2148 fn removes_stale_awaiting_invoice_using_timer_ticks() {
2149 let pending_events = Mutex::new(VecDeque::new());
2150 let outbound_payments = OutboundPayments::new();
2151 let payment_id = PaymentId([0; 32]);
2152 let timer_ticks = 3;
2153 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2155 assert!(!outbound_payments.has_pending_payments());
2157 outbound_payments.add_new_awaiting_invoice(
2158 payment_id, expiration, Retry::Attempts(0), None
2161 assert!(outbound_payments.has_pending_payments());
2163 for i in 0..timer_ticks {
2164 let duration_since_epoch = Duration::from_secs(i * 60);
2165 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2167 assert!(outbound_payments.has_pending_payments());
2168 assert!(pending_events.lock().unwrap().is_empty());
2171 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2172 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2174 assert!(!outbound_payments.has_pending_payments());
2175 assert!(!pending_events.lock().unwrap().is_empty());
2177 pending_events.lock().unwrap().pop_front(),
2178 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2180 assert!(pending_events.lock().unwrap().is_empty());
2183 outbound_payments.add_new_awaiting_invoice(
2184 payment_id, expiration, Retry::Attempts(0), None
2187 assert!(outbound_payments.has_pending_payments());
2190 outbound_payments.add_new_awaiting_invoice(
2191 payment_id, expiration, Retry::Attempts(0), None
2197 fn removes_abandoned_awaiting_invoice() {
2198 let pending_events = Mutex::new(VecDeque::new());
2199 let outbound_payments = OutboundPayments::new();
2200 let payment_id = PaymentId([0; 32]);
2201 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2203 assert!(!outbound_payments.has_pending_payments());
2205 outbound_payments.add_new_awaiting_invoice(
2206 payment_id, expiration, Retry::Attempts(0), None
2209 assert!(outbound_payments.has_pending_payments());
2211 outbound_payments.abandon_payment(
2212 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2214 assert!(!outbound_payments.has_pending_payments());
2215 assert!(!pending_events.lock().unwrap().is_empty());
2217 pending_events.lock().unwrap().pop_front(),
2218 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2220 assert!(pending_events.lock().unwrap().is_empty());
2223 #[cfg(feature = "std")]
2225 fn fails_sending_payment_for_expired_bolt12_invoice() {
2226 let logger = test_utils::TestLogger::new();
2227 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2228 let scorer = RwLock::new(test_utils::TestScorer::new());
2229 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2230 let secp_ctx = Secp256k1::new();
2231 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2233 let pending_events = Mutex::new(VecDeque::new());
2234 let outbound_payments = OutboundPayments::new();
2235 let payment_id = PaymentId([0; 32]);
2236 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2239 outbound_payments.add_new_awaiting_invoice(
2240 payment_id, expiration, Retry::Attempts(0), None
2243 assert!(outbound_payments.has_pending_payments());
2245 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2246 let invoice = OfferBuilder::new(recipient_pubkey())
2249 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2251 .sign(payer_sign).unwrap()
2252 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2254 .sign(recipient_sign).unwrap();
2257 outbound_payments.send_payment_for_bolt12_invoice(
2258 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2259 &&keys_manager, &EmptyNodeIdLookUp {}, &secp_ctx, 0, &&logger, &pending_events,
2264 assert!(!outbound_payments.has_pending_payments());
2266 let payment_hash = invoice.payment_hash();
2267 let reason = Some(PaymentFailureReason::PaymentExpired);
2269 assert!(!pending_events.lock().unwrap().is_empty());
2271 pending_events.lock().unwrap().pop_front(),
2272 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2274 assert!(pending_events.lock().unwrap().is_empty());
2278 fn fails_finding_route_for_bolt12_invoice() {
2279 let logger = test_utils::TestLogger::new();
2280 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2281 let scorer = RwLock::new(test_utils::TestScorer::new());
2282 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2283 let secp_ctx = Secp256k1::new();
2284 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2286 let pending_events = Mutex::new(VecDeque::new());
2287 let outbound_payments = OutboundPayments::new();
2288 let payment_id = PaymentId([0; 32]);
2289 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2291 let invoice = OfferBuilder::new(recipient_pubkey())
2294 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2296 .sign(payer_sign).unwrap()
2297 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2299 .sign(recipient_sign).unwrap();
2302 outbound_payments.add_new_awaiting_invoice(
2303 payment_id, expiration, Retry::Attempts(0),
2304 Some(invoice.amount_msats() / 100 + 50_000)
2307 assert!(outbound_payments.has_pending_payments());
2309 router.expect_find_route(
2310 RouteParameters::from_payment_params_and_value(
2311 PaymentParameters::from_bolt12_invoice(&invoice),
2312 invoice.amount_msats(),
2314 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2318 outbound_payments.send_payment_for_bolt12_invoice(
2319 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2320 &&keys_manager, &EmptyNodeIdLookUp {}, &secp_ctx, 0, &&logger, &pending_events,
2325 assert!(!outbound_payments.has_pending_payments());
2327 let payment_hash = invoice.payment_hash();
2328 let reason = Some(PaymentFailureReason::RouteNotFound);
2330 assert!(!pending_events.lock().unwrap().is_empty());
2332 pending_events.lock().unwrap().pop_front(),
2333 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2335 assert!(pending_events.lock().unwrap().is_empty());
2339 fn sends_payment_for_bolt12_invoice() {
2340 let logger = test_utils::TestLogger::new();
2341 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2342 let scorer = RwLock::new(test_utils::TestScorer::new());
2343 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2344 let secp_ctx = Secp256k1::new();
2345 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2347 let pending_events = Mutex::new(VecDeque::new());
2348 let outbound_payments = OutboundPayments::new();
2349 let payment_id = PaymentId([0; 32]);
2350 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2352 let invoice = OfferBuilder::new(recipient_pubkey())
2355 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2357 .sign(payer_sign).unwrap()
2358 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2360 .sign(recipient_sign).unwrap();
2362 let route_params = RouteParameters {
2363 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2364 final_value_msat: invoice.amount_msats(),
2365 max_total_routing_fee_msat: Some(1234),
2367 router.expect_find_route(
2368 route_params.clone(),
2374 pubkey: recipient_pubkey(),
2375 node_features: NodeFeatures::empty(),
2376 short_channel_id: 42,
2377 channel_features: ChannelFeatures::empty(),
2378 fee_msat: invoice.amount_msats(),
2379 cltv_expiry_delta: 0,
2380 maybe_announced_channel: true,
2386 route_params: Some(route_params),
2390 assert!(!outbound_payments.has_pending_payments());
2392 outbound_payments.send_payment_for_bolt12_invoice(
2393 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2394 &&keys_manager, &EmptyNodeIdLookUp {}, &secp_ctx, 0, &&logger, &pending_events,
2397 Err(Bolt12PaymentError::UnexpectedInvoice),
2399 assert!(!outbound_payments.has_pending_payments());
2400 assert!(pending_events.lock().unwrap().is_empty());
2403 outbound_payments.add_new_awaiting_invoice(
2404 payment_id, expiration, Retry::Attempts(0), Some(1234)
2407 assert!(outbound_payments.has_pending_payments());
2410 outbound_payments.send_payment_for_bolt12_invoice(
2411 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2412 &&keys_manager, &EmptyNodeIdLookUp {}, &secp_ctx, 0, &&logger, &pending_events,
2417 assert!(outbound_payments.has_pending_payments());
2418 assert!(pending_events.lock().unwrap().is_empty());
2421 outbound_payments.send_payment_for_bolt12_invoice(
2422 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2423 &&keys_manager, &EmptyNodeIdLookUp {}, &secp_ctx, 0, &&logger, &pending_events,
2426 Err(Bolt12PaymentError::DuplicateInvoice),
2428 assert!(outbound_payments.has_pending_payments());
2429 assert!(pending_events.lock().unwrap().is_empty());