1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Utilities to send payments and manage outbound payment information.
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
16 use crate::sign::{EntropySource, NodeSigner, Recipient};
17 use crate::events::{self, PaymentFailureReason};
18 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::channelmanager::{ChannelDetails, EventCompletionAction, HTLCSource, PaymentId};
20 use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
21 use crate::offers::invoice::Bolt12Invoice;
22 use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
23 use crate::util::errors::APIError;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(feature = "std", test))]
27 use crate::util::time::tests::SinceEpoch;
28 use crate::util::ser::ReadableArgs;
30 use core::fmt::{self, Display, Formatter};
32 use core::time::Duration;
34 use crate::prelude::*;
35 use crate::sync::Mutex;
37 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
38 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
40 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
41 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
43 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
44 /// and later, also stores information for retrying the payment.
45 pub(crate) enum PendingOutboundPayment {
47 session_privs: HashSet<[u8; 32]>,
50 expiration: StaleExpiration,
51 retry_strategy: Retry,
52 max_total_routing_fee_msat: Option<u64>,
55 payment_hash: PaymentHash,
56 retry_strategy: Retry,
57 // Note this field is currently just replicated from AwaitingInvoice but not actually
59 max_total_routing_fee_msat: Option<u64>,
62 retry_strategy: Option<Retry>,
63 attempts: PaymentAttempts,
64 payment_params: Option<PaymentParameters>,
65 session_privs: HashSet<[u8; 32]>,
66 payment_hash: PaymentHash,
67 payment_secret: Option<PaymentSecret>,
68 payment_metadata: Option<Vec<u8>>,
69 keysend_preimage: Option<PaymentPreimage>,
70 custom_tlvs: Vec<(u64, Vec<u8>)>,
71 pending_amt_msat: u64,
72 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
73 pending_fee_msat: Option<u64>,
74 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
76 /// Our best known block height at the time this payment was initiated.
77 starting_block_height: u32,
78 remaining_max_total_routing_fee_msat: Option<u64>,
80 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
81 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
82 /// and add a pending payment that was already fulfilled.
84 session_privs: HashSet<[u8; 32]>,
85 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
86 payment_hash: Option<PaymentHash>,
87 timer_ticks_without_htlcs: u8,
89 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
90 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
92 session_privs: HashSet<[u8; 32]>,
93 payment_hash: PaymentHash,
94 /// Will be `None` if the payment was serialized before 0.0.115.
95 reason: Option<PaymentFailureReason>,
99 impl PendingOutboundPayment {
100 fn increment_attempts(&mut self) {
101 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
105 fn is_auto_retryable_now(&self) -> bool {
107 PendingOutboundPayment::Retryable {
108 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
110 strategy.is_retryable_now(&attempts)
115 fn is_retryable_now(&self) -> bool {
117 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
118 // We're handling retries manually, we can always retry.
121 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
122 strategy.is_retryable_now(&attempts)
127 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
128 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
129 params.previously_failed_channels.push(scid);
132 pub fn insert_previously_failed_blinded_path(&mut self, blinded_tail: &BlindedTail) {
133 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
134 params.insert_previously_failed_blinded_path(blinded_tail);
137 fn is_awaiting_invoice(&self) -> bool {
139 PendingOutboundPayment::AwaitingInvoice { .. } => true,
143 pub(super) fn is_fulfilled(&self) -> bool {
145 PendingOutboundPayment::Fulfilled { .. } => true,
149 pub(super) fn abandoned(&self) -> bool {
151 PendingOutboundPayment::Abandoned { .. } => true,
155 fn get_pending_fee_msat(&self) -> Option<u64> {
157 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
162 fn payment_hash(&self) -> Option<PaymentHash> {
164 PendingOutboundPayment::Legacy { .. } => None,
165 PendingOutboundPayment::AwaitingInvoice { .. } => None,
166 PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
167 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
168 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
169 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
173 fn mark_fulfilled(&mut self) {
174 let mut session_privs = new_hash_set();
175 core::mem::swap(&mut session_privs, match self {
176 PendingOutboundPayment::Legacy { session_privs } |
177 PendingOutboundPayment::Retryable { session_privs, .. } |
178 PendingOutboundPayment::Fulfilled { session_privs, .. } |
179 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
180 PendingOutboundPayment::AwaitingInvoice { .. } |
181 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
183 let payment_hash = self.payment_hash();
184 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
187 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
188 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
189 let mut our_session_privs = new_hash_set();
190 core::mem::swap(&mut our_session_privs, session_privs);
191 *self = PendingOutboundPayment::Abandoned {
192 session_privs: our_session_privs,
193 payment_hash: *payment_hash,
196 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash, .. } = self {
197 *self = PendingOutboundPayment::Abandoned {
198 session_privs: new_hash_set(),
199 payment_hash: *payment_hash,
205 /// panics if path is None and !self.is_fulfilled
206 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
207 let remove_res = match self {
208 PendingOutboundPayment::Legacy { session_privs } |
209 PendingOutboundPayment::Retryable { session_privs, .. } |
210 PendingOutboundPayment::Fulfilled { session_privs, .. } |
211 PendingOutboundPayment::Abandoned { session_privs, .. } => {
212 session_privs.remove(session_priv)
214 PendingOutboundPayment::AwaitingInvoice { .. } |
215 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
218 if let PendingOutboundPayment::Retryable {
219 ref mut pending_amt_msat, ref mut pending_fee_msat,
220 ref mut remaining_max_total_routing_fee_msat, ..
222 let path = path.expect("Removing a failed payment should always come with a path");
223 *pending_amt_msat -= path.final_value_msat();
224 let path_fee_msat = path.fee_msat();
225 if let Some(fee_msat) = pending_fee_msat.as_mut() {
226 *fee_msat -= path_fee_msat;
229 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
230 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
237 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
238 let insert_res = match self {
239 PendingOutboundPayment::Legacy { session_privs } |
240 PendingOutboundPayment::Retryable { session_privs, .. } => {
241 session_privs.insert(session_priv)
243 PendingOutboundPayment::AwaitingInvoice { .. } |
244 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
245 PendingOutboundPayment::Fulfilled { .. } => false,
246 PendingOutboundPayment::Abandoned { .. } => false,
249 if let PendingOutboundPayment::Retryable {
250 ref mut pending_amt_msat, ref mut pending_fee_msat,
251 ref mut remaining_max_total_routing_fee_msat, ..
253 *pending_amt_msat += path.final_value_msat();
254 let path_fee_msat = path.fee_msat();
255 if let Some(fee_msat) = pending_fee_msat.as_mut() {
256 *fee_msat += path_fee_msat;
259 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
260 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
267 pub(super) fn remaining_parts(&self) -> usize {
269 PendingOutboundPayment::Legacy { session_privs } |
270 PendingOutboundPayment::Retryable { session_privs, .. } |
271 PendingOutboundPayment::Fulfilled { session_privs, .. } |
272 PendingOutboundPayment::Abandoned { session_privs, .. } => {
275 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
276 PendingOutboundPayment::InvoiceReceived { .. } => 0,
281 /// Strategies available to retry payment path failures.
282 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
284 /// Max number of attempts to retry payment.
286 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
287 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
288 /// were retried along a route from a single call to [`Router::find_route_with_id`].
290 #[cfg(feature = "std")]
291 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
292 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
294 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
295 Timeout(core::time::Duration),
298 #[cfg(not(feature = "std"))]
299 impl_writeable_tlv_based_enum!(Retry,
304 #[cfg(feature = "std")]
305 impl_writeable_tlv_based_enum!(Retry,
312 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
313 match (self, attempts) {
314 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
315 max_retry_count > count
317 #[cfg(all(feature = "std", not(test)))]
318 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
319 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
320 #[cfg(all(feature = "std", test))]
321 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
322 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
327 #[cfg(feature = "std")]
328 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
329 if let Some(expiry_time) = route_params.payment_params.expiry_time {
330 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
331 return elapsed > core::time::Duration::from_secs(expiry_time)
337 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
339 /// Storing minimal payment attempts information required for determining if a outbound payment can
341 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
342 /// This count will be incremented only after the result of the attempt is known. When it's 0,
343 /// it means the result of the first attempt is not known yet.
344 pub(crate) count: u32,
345 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
346 #[cfg(feature = "std")]
347 first_attempted_at: T,
348 #[cfg(not(feature = "std"))]
349 phantom: core::marker::PhantomData<T>,
353 #[cfg(not(feature = "std"))]
354 type ConfiguredTime = crate::util::time::Eternity;
355 #[cfg(all(feature = "std", not(test)))]
356 type ConfiguredTime = crate::util::time::MonotonicTime;
357 #[cfg(all(feature = "std", test))]
358 type ConfiguredTime = SinceEpoch;
360 impl<T: Time> PaymentAttemptsUsingTime<T> {
361 pub(crate) fn new() -> Self {
362 PaymentAttemptsUsingTime {
364 #[cfg(feature = "std")]
365 first_attempted_at: T::now(),
366 #[cfg(not(feature = "std"))]
367 phantom: core::marker::PhantomData,
372 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
373 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
374 #[cfg(not(feature = "std"))]
375 return write!(f, "attempts: {}", self.count);
376 #[cfg(feature = "std")]
379 "attempts: {}, duration: {}s",
381 T::now().duration_since(self.first_attempted_at).as_secs()
386 /// How long before a [`PendingOutboundPayment::AwaitingInvoice`] should be considered stale and
387 /// candidate for removal in [`OutboundPayments::remove_stale_payments`].
388 #[derive(Clone, Copy)]
389 pub(crate) enum StaleExpiration {
390 /// Number of times [`OutboundPayments::remove_stale_payments`] is called.
392 /// Duration since the Unix epoch.
393 AbsoluteTimeout(core::time::Duration),
396 impl_writeable_tlv_based_enum!(StaleExpiration,
402 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
403 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
405 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
406 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
407 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
408 #[derive(Clone, Debug, PartialEq, Eq)]
409 pub enum RetryableSendFailure {
410 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
411 /// that this error is *not* caused by [`Retry::Timeout`].
413 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
415 /// We were unable to find a route to the destination.
417 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
418 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
420 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
421 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
422 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
426 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
427 /// of several states. This enum is returned as the Err() type describing which state the payment
428 /// is in, see the description of individual enum states for more.
430 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
431 #[derive(Clone, Debug, PartialEq, Eq)]
432 pub enum PaymentSendFailure {
433 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
434 /// send the payment at all.
436 /// You can freely resend the payment in full (with the parameter error fixed).
438 /// Because the payment failed outright, no payment tracking is done and no
439 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
441 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
442 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
443 ParameterError(APIError),
444 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
445 /// from attempting to send the payment at all.
447 /// You can freely resend the payment in full (with the parameter error fixed).
449 /// Because the payment failed outright, no payment tracking is done and no
450 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
452 /// The results here are ordered the same as the paths in the route object which was passed to
455 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
456 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
457 PathParameterError(Vec<Result<(), APIError>>),
458 /// All paths which were attempted failed to send, with no channel state change taking place.
459 /// You can freely resend the payment in full (though you probably want to do so over different
460 /// paths than the ones selected).
462 /// Because the payment failed outright, no payment tracking is done and no
463 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
465 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
466 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
467 AllFailedResendSafe(Vec<APIError>),
468 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
469 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
471 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
472 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
473 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
475 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
476 /// some paths have irrevocably committed to the HTLC.
478 /// The results here are ordered the same as the paths in the route object that was passed to
481 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
482 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
484 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
486 /// The errors themselves, in the same order as the paths from the route.
487 results: Vec<Result<(), APIError>>,
488 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
489 /// contain a [`RouteParameters`] object for the failing paths.
490 failed_paths_retry: Option<RouteParameters>,
491 /// The payment id for the payment, which is now at least partially pending.
492 payment_id: PaymentId,
496 /// An error when attempting to pay a BOLT 12 invoice.
497 #[derive(Clone, Debug, PartialEq, Eq)]
498 pub(super) enum Bolt12PaymentError {
499 /// The invoice was not requested.
501 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
505 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
506 /// [`Event::ProbeFailed`].
508 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
509 #[derive(Clone, Debug, PartialEq, Eq)]
510 pub enum ProbeSendFailure {
511 /// We were unable to find a route to the destination.
513 /// We failed to send the payment probes.
514 SendingFailed(PaymentSendFailure),
517 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
519 /// This should generally be constructed with data communicated to us from the recipient (via a
520 /// BOLT11 or BOLT12 invoice).
521 #[derive(Clone, Debug, PartialEq, Eq)]
522 pub struct RecipientOnionFields {
523 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
524 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
525 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
528 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
529 /// multi-path payments require a recipient-provided secret.
531 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
532 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
533 /// recipient will not reject it.
534 pub payment_secret: Option<PaymentSecret>,
535 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
536 /// arbitrary length. This gives recipients substantially more flexibility to receive
539 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
540 /// scheme to authenticate received payments against expected payments and invoices, this field
541 /// is not used in LDK for received payments, and can be used to store arbitrary data in
542 /// invoices which will be received with the payment.
544 /// Note that this field was added to the lightning specification more recently than
545 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
546 /// may not be supported as universally.
547 pub payment_metadata: Option<Vec<u8>>,
548 /// See [`Self::custom_tlvs`] for more info.
549 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
552 impl_writeable_tlv_based!(RecipientOnionFields, {
553 (0, payment_secret, option),
554 (1, custom_tlvs, optional_vec),
555 (2, payment_metadata, option),
558 impl RecipientOnionFields {
559 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
560 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
561 /// but do not require or provide any further data.
562 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
563 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
566 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
567 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
568 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
569 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
570 /// instead want to use [`RecipientOnionFields::secret_only`].
572 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
573 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
574 pub fn spontaneous_empty() -> Self {
575 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
578 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
579 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
580 /// respectively. TLV type numbers must be unique and within the range
581 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
583 /// This method will also error for types in the experimental range which have been
584 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
586 /// See [`Self::custom_tlvs`] for more info.
587 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
588 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
589 let mut prev_type = None;
590 for (typ, _) in custom_tlvs.iter() {
591 if *typ < 1 << 16 { return Err(()); }
592 if *typ == 5482373484 { return Err(()); } // keysend
594 Some(prev) if prev >= *typ => return Err(()),
597 prev_type = Some(*typ);
599 self.custom_tlvs = custom_tlvs;
603 /// Gets the custom TLVs that will be sent or have been received.
605 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
606 /// additional flexibility on top of payment metadata, as while other implementations may
607 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
608 /// do not have this restriction.
610 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
611 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
612 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
613 #[cfg(not(c_bindings))]
614 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
618 /// Gets the custom TLVs that will be sent or have been received.
620 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
621 /// additional flexibility on top of payment metadata, as while other implementations may
622 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
623 /// do not have this restriction.
625 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
626 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
627 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
629 pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
630 self.custom_tlvs.clone()
633 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
634 /// have to make sure that some fields match exactly across the parts. For those that aren't
635 /// required to match, if they don't match we should remove them so as to not expose data
636 /// that's dependent on the HTLC receive order to users.
638 /// Here we implement this, first checking compatibility then mutating two objects and then
639 /// dropping any remaining non-matching fields from both.
640 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
641 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
642 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
644 let tlvs = &mut self.custom_tlvs;
645 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
647 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
648 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
649 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
651 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
652 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
658 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
659 pub(super) struct SendAlongPathArgs<'a> {
661 pub payment_hash: &'a PaymentHash,
662 pub recipient_onion: RecipientOnionFields,
663 pub total_value: u64,
665 pub payment_id: PaymentId,
666 pub keysend_preimage: &'a Option<PaymentPreimage>,
667 pub session_priv_bytes: [u8; 32],
670 pub(super) struct OutboundPayments {
671 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
672 pub(super) retry_lock: Mutex<()>,
675 impl OutboundPayments {
676 pub(super) fn new() -> Self {
678 pending_outbound_payments: Mutex::new(new_hash_map()),
679 retry_lock: Mutex::new(()),
683 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
684 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
685 retry_strategy: Retry, route_params: RouteParameters, router: &R,
686 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
687 node_signer: &NS, best_block_height: u32, logger: &L,
688 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
689 ) -> Result<(), RetryableSendFailure>
692 ES::Target: EntropySource,
693 NS::Target: NodeSigner,
695 IH: Fn() -> InFlightHtlcs,
696 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
698 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
699 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
700 best_block_height, logger, pending_events, &send_payment_along_path)
703 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
704 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
705 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
706 send_payment_along_path: F
707 ) -> Result<(), PaymentSendFailure>
709 ES::Target: EntropySource,
710 NS::Target: NodeSigner,
711 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
713 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)?;
714 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
715 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
716 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
719 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
720 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
721 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
722 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
723 node_signer: &NS, best_block_height: u32, logger: &L,
724 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
725 ) -> Result<PaymentHash, RetryableSendFailure>
728 ES::Target: EntropySource,
729 NS::Target: NodeSigner,
731 IH: Fn() -> InFlightHtlcs,
732 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
734 let preimage = payment_preimage
735 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
736 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
737 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
738 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
739 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
740 .map(|()| payment_hash)
743 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
744 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
745 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
746 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
747 ) -> Result<PaymentHash, PaymentSendFailure>
749 ES::Target: EntropySource,
750 NS::Target: NodeSigner,
751 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
753 let preimage = payment_preimage
754 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
755 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
756 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
757 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
759 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
760 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
762 Ok(()) => Ok(payment_hash),
764 self.remove_outbound_if_all_failed(payment_id, &e);
770 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
771 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
772 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
773 best_block_height: u32, logger: &L,
774 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
775 send_payment_along_path: SP,
776 ) -> Result<(), Bolt12PaymentError>
779 ES::Target: EntropySource,
780 NS::Target: NodeSigner,
782 IH: Fn() -> InFlightHtlcs,
783 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
785 let payment_hash = invoice.payment_hash();
786 let max_total_routing_fee_msat;
787 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
788 hash_map::Entry::Occupied(entry) => match entry.get() {
789 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
790 max_total_routing_fee_msat = *max_total_fee;
791 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
793 retry_strategy: *retry_strategy,
794 max_total_routing_fee_msat,
797 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
799 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
802 let pay_params = PaymentParameters::from_bolt12_invoice(&invoice);
803 let amount_msat = invoice.amount_msats();
804 let mut route_params = RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
805 if let Some(max_fee_msat) = max_total_routing_fee_msat {
806 route_params.max_total_routing_fee_msat = Some(max_fee_msat);
809 self.find_route_and_send_payment(
810 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
811 entropy_source, node_signer, best_block_height, logger, pending_events,
812 &send_payment_along_path
818 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
819 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
820 best_block_height: u32,
821 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
822 send_payment_along_path: SP,
826 ES::Target: EntropySource,
827 NS::Target: NodeSigner,
828 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
829 IH: Fn() -> InFlightHtlcs,
830 FH: Fn() -> Vec<ChannelDetails>,
833 let _single_thread = self.retry_lock.lock().unwrap();
835 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
836 let mut retry_id_route_params = None;
837 for (pmt_id, pmt) in outbounds.iter_mut() {
838 if pmt.is_auto_retryable_now() {
839 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
840 if pending_amt_msat < total_msat {
841 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
842 final_value_msat: *total_msat - *pending_amt_msat,
843 payment_params: params.clone(),
844 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
848 } else { debug_assert!(false); }
851 core::mem::drop(outbounds);
852 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
853 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)
857 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
858 outbounds.retain(|pmt_id, pmt| {
859 let mut retain = true;
860 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
861 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
862 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
863 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
865 payment_hash: *payment_hash,
875 pub(super) fn needs_abandon(&self) -> bool {
876 let outbounds = self.pending_outbound_payments.lock().unwrap();
877 outbounds.iter().any(|(_, pmt)|
878 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
879 !pmt.is_awaiting_invoice())
882 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
883 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
885 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
886 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
887 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
888 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
889 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
890 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
891 node_signer: &NS, best_block_height: u32, logger: &L,
892 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
893 ) -> Result<(), RetryableSendFailure>
896 ES::Target: EntropySource,
897 NS::Target: NodeSigner,
899 IH: Fn() -> InFlightHtlcs,
900 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
902 #[cfg(feature = "std")] {
903 if has_expired(&route_params) {
904 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
905 payment_id, payment_hash);
906 return Err(RetryableSendFailure::PaymentExpired)
910 let mut route = router.find_route_with_id(
911 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
912 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
913 payment_hash, payment_id,
915 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
916 payment_id, payment_hash);
917 RetryableSendFailure::RouteNotFound
920 if route.route_params.as_ref() != Some(&route_params) {
922 "Routers are expected to return a Route which includes the requested RouteParameters");
923 route.route_params = Some(route_params.clone());
926 let onion_session_privs = self.add_new_pending_payment(payment_hash,
927 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
928 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
930 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
931 payment_id, payment_hash);
932 RetryableSendFailure::DuplicatePayment
935 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
936 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
937 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
938 payment_id, payment_hash, res);
939 if let Err(e) = res {
940 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);
945 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
946 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
947 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
948 node_signer: &NS, best_block_height: u32, logger: &L,
949 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
953 ES::Target: EntropySource,
954 NS::Target: NodeSigner,
956 IH: Fn() -> InFlightHtlcs,
957 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
959 #[cfg(feature = "std")] {
960 if has_expired(&route_params) {
961 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
962 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
967 let mut route = match router.find_route_with_id(
968 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
969 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
970 payment_hash, payment_id,
974 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
975 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
980 if route.route_params.as_ref() != Some(&route_params) {
982 "Routers are expected to return a Route which includes the requested RouteParameters");
983 route.route_params = Some(route_params.clone());
986 for path in route.paths.iter() {
987 if path.hops.len() == 0 {
988 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
989 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
994 macro_rules! abandon_with_entry {
995 ($payment: expr, $reason: expr) => {
996 $payment.get_mut().mark_abandoned($reason);
997 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
998 if $payment.get().remaining_parts() == 0 {
999 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1009 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
1010 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1011 match outbounds.entry(payment_id) {
1012 hash_map::Entry::Occupied(mut payment) => {
1013 match payment.get() {
1014 PendingOutboundPayment::Retryable {
1015 total_msat, keysend_preimage, payment_secret, payment_metadata,
1016 custom_tlvs, pending_amt_msat, ..
1018 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1019 let retry_amt_msat = route.get_total_amount();
1020 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1021 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);
1022 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1026 if !payment.get().is_retryable_now() {
1027 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1028 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1032 let total_msat = *total_msat;
1033 let recipient_onion = RecipientOnionFields {
1034 payment_secret: *payment_secret,
1035 payment_metadata: payment_metadata.clone(),
1036 custom_tlvs: custom_tlvs.clone(),
1038 let keysend_preimage = *keysend_preimage;
1040 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1041 for _ in 0..route.paths.len() {
1042 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1045 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1046 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1049 payment.get_mut().increment_attempts();
1051 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1053 PendingOutboundPayment::Legacy { .. } => {
1054 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1057 PendingOutboundPayment::AwaitingInvoice { .. } => {
1058 log_error!(logger, "Payment not yet sent");
1061 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1062 let total_amount = route_params.final_value_msat;
1063 let recipient_onion = RecipientOnionFields {
1064 payment_secret: None,
1065 payment_metadata: None,
1066 custom_tlvs: vec![],
1068 let retry_strategy = Some(*retry_strategy);
1069 let payment_params = Some(route_params.payment_params.clone());
1070 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1071 *payment_hash, recipient_onion.clone(), None, &route,
1072 retry_strategy, payment_params, entropy_source, best_block_height
1074 *payment.into_mut() = retryable_payment;
1075 (total_amount, recipient_onion, None, onion_session_privs)
1077 PendingOutboundPayment::Fulfilled { .. } => {
1078 log_error!(logger, "Payment already completed");
1081 PendingOutboundPayment::Abandoned { .. } => {
1082 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1087 hash_map::Entry::Vacant(_) => {
1088 log_error!(logger, "Payment with ID {} not found", &payment_id);
1093 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1094 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1095 &send_payment_along_path);
1096 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1097 if let Err(e) = res {
1098 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);
1102 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1103 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1104 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1105 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1106 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1110 ES::Target: EntropySource,
1111 NS::Target: NodeSigner,
1113 IH: Fn() -> InFlightHtlcs,
1114 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1117 PaymentSendFailure::AllFailedResendSafe(errs) => {
1118 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);
1119 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);
1121 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1122 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1123 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1124 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1125 // return `Ok()` here, ignoring any retry errors.
1126 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);
1128 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1129 // This may happen if we send a payment and some paths fail, but only due to a temporary
1130 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1131 // initial HTLC-Add messages yet.
1133 PaymentSendFailure::PathParameterError(results) => {
1134 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1135 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1136 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1138 PaymentSendFailure::ParameterError(e) => {
1139 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1140 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1142 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1146 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1147 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1148 paths: Vec<Path>, path_results: I, logger: &L,
1149 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1150 ) where L::Target: Logger {
1151 let mut events = pending_events.lock().unwrap();
1152 debug_assert_eq!(paths.len(), path_results.len());
1153 for (path, path_res) in paths.into_iter().zip(path_results) {
1154 if let Err(e) = path_res {
1155 if let APIError::MonitorUpdateInProgress = e { continue }
1156 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1157 let mut failed_scid = None;
1158 if let APIError::ChannelUnavailable { .. } = e {
1159 let scid = path.hops[0].short_channel_id;
1160 failed_scid = Some(scid);
1161 route_params.payment_params.previously_failed_channels.push(scid);
1163 events.push_back((events::Event::PaymentPathFailed {
1164 payment_id: Some(payment_id),
1166 payment_failed_permanently: false,
1167 failure: events::PathFailure::InitialSend { err: e },
1169 short_channel_id: failed_scid,
1179 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1180 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1181 best_block_height: u32, send_payment_along_path: F
1182 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1184 ES::Target: EntropySource,
1185 NS::Target: NodeSigner,
1186 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1188 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1189 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1191 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1193 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1194 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1195 err: "No need probing a path with less than two hops".to_string()
1199 let route = Route { paths: vec![path], route_params: None };
1200 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1201 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1202 entropy_source, best_block_height)?;
1204 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1205 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1207 Ok(()) => Ok((payment_hash, payment_id)),
1209 self.remove_outbound_if_all_failed(payment_id, &e);
1216 pub(super) fn test_set_payment_metadata(
1217 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1219 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1220 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1221 *payment_metadata = new_payment_metadata;
1223 _ => panic!("Need a retryable payment to update metadata on"),
1228 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1229 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1230 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1231 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1232 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1235 pub(super) fn add_new_pending_payment<ES: Deref>(
1236 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1237 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1238 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1239 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1240 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1241 match pending_outbounds.entry(payment_id) {
1242 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1243 hash_map::Entry::Vacant(entry) => {
1244 let (payment, onion_session_privs) = self.create_pending_payment(
1245 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1246 payment_params, entropy_source, best_block_height
1248 entry.insert(payment);
1249 Ok(onion_session_privs)
1254 fn create_pending_payment<ES: Deref>(
1255 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1256 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1257 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1258 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1260 ES::Target: EntropySource,
1262 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1263 for _ in 0..route.paths.len() {
1264 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1267 let mut payment = PendingOutboundPayment::Retryable {
1269 attempts: PaymentAttempts::new(),
1271 session_privs: new_hash_set(),
1272 pending_amt_msat: 0,
1273 pending_fee_msat: Some(0),
1275 payment_secret: recipient_onion.payment_secret,
1276 payment_metadata: recipient_onion.payment_metadata,
1278 custom_tlvs: recipient_onion.custom_tlvs,
1279 starting_block_height: best_block_height,
1280 total_msat: route.get_total_amount(),
1281 remaining_max_total_routing_fee_msat:
1282 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1285 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1286 assert!(payment.insert(*session_priv_bytes, path));
1289 (payment, onion_session_privs)
1292 pub(super) fn add_new_awaiting_invoice(
1293 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1294 max_total_routing_fee_msat: Option<u64>
1295 ) -> Result<(), ()> {
1296 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1297 match pending_outbounds.entry(payment_id) {
1298 hash_map::Entry::Occupied(_) => Err(()),
1299 hash_map::Entry::Vacant(entry) => {
1300 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1303 max_total_routing_fee_msat,
1311 fn pay_route_internal<NS: Deref, F>(
1312 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1313 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1314 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1315 send_payment_along_path: &F
1316 ) -> Result<(), PaymentSendFailure>
1318 NS::Target: NodeSigner,
1319 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1321 if route.paths.len() < 1 {
1322 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1324 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1325 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1327 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1329 let mut total_value = 0;
1330 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1331 let mut path_errs = Vec::with_capacity(route.paths.len());
1332 'path_check: for path in route.paths.iter() {
1333 if path.hops.len() < 1 || path.hops.len() > 20 {
1334 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1335 continue 'path_check;
1337 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1338 usize::max_value() } else { path.hops.len() - 1 };
1339 for (idx, hop) in path.hops.iter().enumerate() {
1340 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1341 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1342 continue 'path_check;
1345 for (i, hop) in path.hops.iter().enumerate() {
1346 // Check for duplicate channel_id in the remaining hops of the path
1347 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1348 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1349 continue 'path_check;
1352 total_value += path.final_value_msat();
1353 path_errs.push(Ok(()));
1355 if path_errs.iter().any(|e| e.is_err()) {
1356 return Err(PaymentSendFailure::PathParameterError(path_errs));
1358 if let Some(amt_msat) = recv_value_msat {
1359 total_value = amt_msat;
1362 let cur_height = best_block_height + 1;
1363 let mut results = Vec::new();
1364 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1365 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1366 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1367 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1368 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1372 Err(APIError::MonitorUpdateInProgress) => {
1373 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1374 // considered "in flight" and we shouldn't remove it from the
1375 // PendingOutboundPayment set.
1378 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1379 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1380 let removed = payment.remove(&session_priv_bytes, Some(path));
1381 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1383 debug_assert!(false, "This can't happen as the payment was added by callers");
1384 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1388 results.push(path_res);
1390 let mut has_ok = false;
1391 let mut has_err = false;
1392 let mut has_unsent = false;
1393 let mut total_ok_fees_msat = 0;
1394 let mut total_ok_amt_sent_msat = 0;
1395 for (res, path) in results.iter().zip(route.paths.iter()) {
1398 total_ok_fees_msat += path.fee_msat();
1399 total_ok_amt_sent_msat += path.final_value_msat();
1401 if res.is_err() { has_err = true; }
1402 if let &Err(APIError::MonitorUpdateInProgress) = res {
1403 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1407 total_ok_fees_msat += path.fee_msat();
1408 total_ok_amt_sent_msat += path.final_value_msat();
1409 } else if res.is_err() {
1413 if has_err && has_ok {
1414 Err(PaymentSendFailure::PartialFailure {
1417 failed_paths_retry: if has_unsent {
1418 if let Some(route_params) = &route.route_params {
1419 let mut route_params = route_params.clone();
1420 // We calculate the leftover fee budget we're allowed to spend by
1421 // subtracting the used fee from the total fee budget.
1422 route_params.max_total_routing_fee_msat = route_params
1423 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1425 // We calculate the remaining target amount by subtracting the succeded
1427 route_params.final_value_msat = route_params.final_value_msat
1428 .saturating_sub(total_ok_amt_sent_msat);
1434 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1441 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1442 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1443 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1444 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1445 send_payment_along_path: F
1446 ) -> Result<(), PaymentSendFailure>
1448 NS::Target: NodeSigner,
1449 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1451 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1452 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1453 &send_payment_along_path)
1454 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1457 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1458 // map as the payment is free to be resent.
1459 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1460 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1461 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1462 debug_assert!(removed, "We should always have a pending payment to remove here");
1466 pub(super) fn claim_htlc<L: Deref>(
1467 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1468 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1469 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1471 ) where L::Target: Logger {
1472 let mut session_priv_bytes = [0; 32];
1473 session_priv_bytes.copy_from_slice(&session_priv[..]);
1474 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1475 let mut pending_events = pending_events.lock().unwrap();
1476 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1477 if !payment.get().is_fulfilled() {
1478 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1479 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1480 let fee_paid_msat = payment.get().get_pending_fee_msat();
1481 pending_events.push_back((events::Event::PaymentSent {
1482 payment_id: Some(payment_id),
1486 }, Some(ev_completion_action.clone())));
1487 payment.get_mut().mark_fulfilled();
1491 // We currently immediately remove HTLCs which were fulfilled on-chain.
1492 // This could potentially lead to removing a pending payment too early,
1493 // with a reorg of one block causing us to re-add the fulfilled payment on
1495 // TODO: We should have a second monitor event that informs us of payments
1496 // irrevocably fulfilled.
1497 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1498 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1499 pending_events.push_back((events::Event::PaymentPathSuccessful {
1503 }, Some(ev_completion_action)));
1507 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1511 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1512 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1514 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1515 let mut pending_events = pending_events.lock().unwrap();
1516 for source in sources {
1517 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1518 let mut session_priv_bytes = [0; 32];
1519 session_priv_bytes.copy_from_slice(&session_priv[..]);
1520 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1521 assert!(payment.get().is_fulfilled());
1522 if payment.get_mut().remove(&session_priv_bytes, None) {
1523 let payment_hash = payment.get().payment_hash();
1524 debug_assert!(payment_hash.is_some());
1525 pending_events.push_back((events::Event::PaymentPathSuccessful {
1536 pub(super) fn remove_stale_payments(
1537 &self, duration_since_epoch: Duration,
1538 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1540 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1541 let mut pending_events = pending_events.lock().unwrap();
1542 pending_outbound_payments.retain(|payment_id, payment| match payment {
1543 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1544 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1545 // this could race the user making a duplicate send_payment call and our idempotency
1546 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1547 // removal. This should be more than sufficient to ensure the idempotency of any
1548 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1550 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1551 let mut no_remaining_entries = session_privs.is_empty();
1552 if no_remaining_entries {
1553 for (ev, _) in pending_events.iter() {
1555 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1556 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1557 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1558 if payment_id == ev_payment_id {
1559 no_remaining_entries = false;
1567 if no_remaining_entries {
1568 *timer_ticks_without_htlcs += 1;
1569 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1571 *timer_ticks_without_htlcs = 0;
1575 PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1576 let is_stale = match expiration {
1577 StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1578 *absolute_expiry <= duration_since_epoch
1580 StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1581 if *timer_ticks_remaining > 0 {
1582 *timer_ticks_remaining -= 1;
1590 pending_events.push_back(
1591 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1602 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1603 pub(super) fn fail_htlc<L: Deref>(
1604 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1605 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1606 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1607 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1608 ) -> bool where L::Target: Logger {
1610 let DecodedOnionFailure {
1611 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1612 onion_error_data, failed_within_blinded_path
1613 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1615 let DecodedOnionFailure {
1616 network_update, short_channel_id, payment_failed_permanently, failed_within_blinded_path
1617 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1619 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1620 let mut session_priv_bytes = [0; 32];
1621 session_priv_bytes.copy_from_slice(&session_priv[..]);
1622 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1624 // If any payments already need retry, there's no need to generate a redundant
1625 // `PendingHTLCsForwardable`.
1626 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1627 let mut awaiting_retry = false;
1628 if pmt.is_auto_retryable_now() {
1629 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1630 if pending_amt_msat < total_msat {
1631 awaiting_retry = true;
1638 let mut full_failure_ev = None;
1639 let mut pending_retry_ev = false;
1640 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1641 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1642 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1645 if payment.get().is_fulfilled() {
1646 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1649 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1650 if let Some(scid) = short_channel_id {
1651 // TODO: If we decided to blame ourselves (or one of our channels) in
1652 // process_onion_failure we should close that channel as it implies our
1653 // next-hop is needlessly blaming us!
1654 payment.get_mut().insert_previously_failed_scid(scid);
1656 if failed_within_blinded_path {
1657 debug_assert!(short_channel_id.is_none());
1658 if let Some(bt) = &path.blinded_tail {
1659 payment.get_mut().insert_previously_failed_blinded_path(&bt);
1660 } else { debug_assert!(false); }
1663 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1664 let reason = if payment_failed_permanently {
1665 PaymentFailureReason::RecipientRejected
1667 PaymentFailureReason::RetriesExhausted
1669 payment.get_mut().mark_abandoned(reason);
1670 is_retryable_now = false;
1672 if payment.get().remaining_parts() == 0 {
1673 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1674 if !payment_is_probe {
1675 full_failure_ev = Some(events::Event::PaymentFailed {
1676 payment_id: *payment_id,
1677 payment_hash: *payment_hash,
1686 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1689 core::mem::drop(outbounds);
1690 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1692 let path_failure = {
1693 if payment_is_probe {
1694 if payment_failed_permanently {
1695 events::Event::ProbeSuccessful {
1696 payment_id: *payment_id,
1697 payment_hash: payment_hash.clone(),
1701 events::Event::ProbeFailed {
1702 payment_id: *payment_id,
1703 payment_hash: payment_hash.clone(),
1709 // If we miss abandoning the payment above, we *must* generate an event here or else the
1710 // payment will sit in our outbounds forever.
1711 if attempts_remaining && !already_awaiting_retry {
1712 debug_assert!(full_failure_ev.is_none());
1713 pending_retry_ev = true;
1715 events::Event::PaymentPathFailed {
1716 payment_id: Some(*payment_id),
1717 payment_hash: payment_hash.clone(),
1718 payment_failed_permanently,
1719 failure: events::PathFailure::OnPath { network_update },
1723 error_code: onion_error_code,
1725 error_data: onion_error_data
1729 let mut pending_events = pending_events.lock().unwrap();
1730 pending_events.push_back((path_failure, None));
1731 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1735 pub(super) fn abandon_payment(
1736 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1737 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1739 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1740 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1741 payment.get_mut().mark_abandoned(reason);
1742 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1743 if payment.get().remaining_parts() == 0 {
1744 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1746 payment_hash: *payment_hash,
1751 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1752 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1761 pub fn has_pending_payments(&self) -> bool {
1762 !self.pending_outbound_payments.lock().unwrap().is_empty()
1766 pub fn clear_pending_payments(&self) {
1767 self.pending_outbound_payments.lock().unwrap().clear()
1771 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1773 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1774 probing_cookie_secret: [u8; 32]) -> bool
1776 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1777 target_payment_hash == *payment_hash
1780 /// Returns the 'probing cookie' for the given [`PaymentId`].
1781 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1782 let mut preimage = [0u8; 64];
1783 preimage[..32].copy_from_slice(&probing_cookie_secret);
1784 preimage[32..].copy_from_slice(&payment_id.0);
1785 PaymentHash(Sha256::hash(&preimage).to_byte_array())
1788 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1790 (0, session_privs, required),
1793 (0, session_privs, required),
1794 (1, payment_hash, option),
1795 (3, timer_ticks_without_htlcs, (default_value, 0)),
1798 (0, session_privs, required),
1799 (1, pending_fee_msat, option),
1800 (2, payment_hash, required),
1801 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1802 // never see it - `payment_params` was added here after the field was added/required.
1803 (3, payment_params, (option: ReadableArgs, 0)),
1804 (4, payment_secret, option),
1805 (5, keysend_preimage, option),
1806 (6, total_msat, required),
1807 (7, payment_metadata, option),
1808 (8, pending_amt_msat, required),
1809 (9, custom_tlvs, optional_vec),
1810 (10, starting_block_height, required),
1811 (11, remaining_max_total_routing_fee_msat, option),
1812 (not_written, retry_strategy, (static_value, None)),
1813 (not_written, attempts, (static_value, PaymentAttempts::new())),
1816 (0, session_privs, required),
1817 (1, reason, option),
1818 (2, payment_hash, required),
1820 (5, AwaitingInvoice) => {
1821 (0, expiration, required),
1822 (2, retry_strategy, required),
1823 (4, max_total_routing_fee_msat, option),
1825 (7, InvoiceReceived) => {
1826 (0, payment_hash, required),
1827 (2, retry_strategy, required),
1828 (4, max_total_routing_fee_msat, option),
1834 use bitcoin::network::constants::Network;
1835 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1837 use core::time::Duration;
1839 use crate::events::{Event, PathFailure, PaymentFailureReason};
1840 use crate::ln::PaymentHash;
1841 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1842 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1843 use crate::ln::msgs::{ErrorAction, LightningError};
1844 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1845 #[cfg(feature = "std")]
1846 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1847 use crate::offers::offer::OfferBuilder;
1848 use crate::offers::test_utils::*;
1849 use crate::routing::gossip::NetworkGraph;
1850 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1851 use crate::sync::{Arc, Mutex, RwLock};
1852 use crate::util::errors::APIError;
1853 use crate::util::test_utils;
1855 use alloc::collections::VecDeque;
1858 fn test_recipient_onion_fields_with_custom_tlvs() {
1859 let onion_fields = RecipientOnionFields::spontaneous_empty();
1861 let bad_type_range_tlvs = vec![
1865 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1867 let keysend_tlv = vec![
1868 (5482373484, vec![42; 32]),
1870 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1872 let good_tlvs = vec![
1873 ((1 << 16) + 1, vec![42]),
1874 ((1 << 16) + 3, vec![42; 32]),
1876 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1880 #[cfg(feature = "std")]
1881 fn fails_paying_after_expiration() {
1882 do_fails_paying_after_expiration(false);
1883 do_fails_paying_after_expiration(true);
1885 #[cfg(feature = "std")]
1886 fn do_fails_paying_after_expiration(on_retry: bool) {
1887 let outbound_payments = OutboundPayments::new();
1888 let logger = test_utils::TestLogger::new();
1889 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1890 let scorer = RwLock::new(test_utils::TestScorer::new());
1891 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1892 let secp_ctx = Secp256k1::new();
1893 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1895 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1896 let payment_params = PaymentParameters::from_node_id(
1897 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1899 ).with_expiry_time(past_expiry_time);
1900 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1901 let pending_events = Mutex::new(VecDeque::new());
1903 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1904 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1905 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1906 &&keys_manager, 0).unwrap();
1907 outbound_payments.find_route_and_send_payment(
1908 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1909 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1911 let events = pending_events.lock().unwrap();
1912 assert_eq!(events.len(), 1);
1913 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1914 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1915 } else { panic!("Unexpected event"); }
1917 let err = outbound_payments.send_payment(
1918 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1919 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1920 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1921 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1926 fn find_route_error() {
1927 do_find_route_error(false);
1928 do_find_route_error(true);
1930 fn do_find_route_error(on_retry: bool) {
1931 let outbound_payments = OutboundPayments::new();
1932 let logger = test_utils::TestLogger::new();
1933 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1934 let scorer = RwLock::new(test_utils::TestScorer::new());
1935 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1936 let secp_ctx = Secp256k1::new();
1937 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1939 let payment_params = PaymentParameters::from_node_id(
1940 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1941 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1942 router.expect_find_route(route_params.clone(),
1943 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1945 let pending_events = Mutex::new(VecDeque::new());
1947 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1948 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1949 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1950 &&keys_manager, 0).unwrap();
1951 outbound_payments.find_route_and_send_payment(
1952 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1953 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1955 let events = pending_events.lock().unwrap();
1956 assert_eq!(events.len(), 1);
1957 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1959 let err = outbound_payments.send_payment(
1960 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1961 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1962 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1963 if let RetryableSendFailure::RouteNotFound = err {
1964 } else { panic!("Unexpected error"); }
1969 fn initial_send_payment_path_failed_evs() {
1970 let outbound_payments = OutboundPayments::new();
1971 let logger = test_utils::TestLogger::new();
1972 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1973 let scorer = RwLock::new(test_utils::TestScorer::new());
1974 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
1975 let secp_ctx = Secp256k1::new();
1976 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1978 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1979 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1980 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1981 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1982 let failed_scid = 42;
1984 paths: vec![Path { hops: vec![RouteHop {
1985 pubkey: receiver_pk,
1986 node_features: NodeFeatures::empty(),
1987 short_channel_id: failed_scid,
1988 channel_features: ChannelFeatures::empty(),
1990 cltv_expiry_delta: 0,
1991 maybe_announced_channel: true,
1992 }], blinded_tail: None }],
1993 route_params: Some(route_params.clone()),
1995 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1996 let mut route_params_w_failed_scid = route_params.clone();
1997 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1998 let mut route_w_failed_scid = route.clone();
1999 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
2000 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
2001 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2002 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2004 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
2005 // PaymentPathFailed event.
2006 let pending_events = Mutex::new(VecDeque::new());
2007 outbound_payments.send_payment(
2008 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2009 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2010 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2011 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2012 let mut events = pending_events.lock().unwrap();
2013 assert_eq!(events.len(), 2);
2014 if let Event::PaymentPathFailed {
2016 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2018 assert_eq!(short_channel_id, Some(failed_scid));
2019 } else { panic!("Unexpected event"); }
2020 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2022 core::mem::drop(events);
2024 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2025 outbound_payments.send_payment(
2026 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2027 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2028 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2029 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2030 assert_eq!(pending_events.lock().unwrap().len(), 0);
2032 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2033 outbound_payments.send_payment(
2034 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2035 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2036 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2037 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2038 let events = pending_events.lock().unwrap();
2039 assert_eq!(events.len(), 2);
2040 if let Event::PaymentPathFailed {
2042 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2044 assert_eq!(short_channel_id, None);
2045 } else { panic!("Unexpected event"); }
2046 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2050 fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2051 let pending_events = Mutex::new(VecDeque::new());
2052 let outbound_payments = OutboundPayments::new();
2053 let payment_id = PaymentId([0; 32]);
2054 let absolute_expiry = 100;
2055 let tick_interval = 10;
2056 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2058 assert!(!outbound_payments.has_pending_payments());
2060 outbound_payments.add_new_awaiting_invoice(
2061 payment_id, expiration, Retry::Attempts(0), None
2064 assert!(outbound_payments.has_pending_payments());
2066 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2067 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2068 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2070 assert!(outbound_payments.has_pending_payments());
2071 assert!(pending_events.lock().unwrap().is_empty());
2074 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2075 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2077 assert!(!outbound_payments.has_pending_payments());
2078 assert!(!pending_events.lock().unwrap().is_empty());
2080 pending_events.lock().unwrap().pop_front(),
2081 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2083 assert!(pending_events.lock().unwrap().is_empty());
2086 outbound_payments.add_new_awaiting_invoice(
2087 payment_id, expiration, Retry::Attempts(0), None
2090 assert!(outbound_payments.has_pending_payments());
2093 outbound_payments.add_new_awaiting_invoice(
2094 payment_id, expiration, Retry::Attempts(0), None
2100 fn removes_stale_awaiting_invoice_using_timer_ticks() {
2101 let pending_events = Mutex::new(VecDeque::new());
2102 let outbound_payments = OutboundPayments::new();
2103 let payment_id = PaymentId([0; 32]);
2104 let timer_ticks = 3;
2105 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2107 assert!(!outbound_payments.has_pending_payments());
2109 outbound_payments.add_new_awaiting_invoice(
2110 payment_id, expiration, Retry::Attempts(0), None
2113 assert!(outbound_payments.has_pending_payments());
2115 for i in 0..timer_ticks {
2116 let duration_since_epoch = Duration::from_secs(i * 60);
2117 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2119 assert!(outbound_payments.has_pending_payments());
2120 assert!(pending_events.lock().unwrap().is_empty());
2123 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2124 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2126 assert!(!outbound_payments.has_pending_payments());
2127 assert!(!pending_events.lock().unwrap().is_empty());
2129 pending_events.lock().unwrap().pop_front(),
2130 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2132 assert!(pending_events.lock().unwrap().is_empty());
2135 outbound_payments.add_new_awaiting_invoice(
2136 payment_id, expiration, Retry::Attempts(0), None
2139 assert!(outbound_payments.has_pending_payments());
2142 outbound_payments.add_new_awaiting_invoice(
2143 payment_id, expiration, Retry::Attempts(0), None
2149 fn removes_abandoned_awaiting_invoice() {
2150 let pending_events = Mutex::new(VecDeque::new());
2151 let outbound_payments = OutboundPayments::new();
2152 let payment_id = PaymentId([0; 32]);
2153 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
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 outbound_payments.abandon_payment(
2164 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2166 assert!(!outbound_payments.has_pending_payments());
2167 assert!(!pending_events.lock().unwrap().is_empty());
2169 pending_events.lock().unwrap().pop_front(),
2170 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2172 assert!(pending_events.lock().unwrap().is_empty());
2175 #[cfg(feature = "std")]
2177 fn fails_sending_payment_for_expired_bolt12_invoice() {
2178 let logger = test_utils::TestLogger::new();
2179 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2180 let scorer = RwLock::new(test_utils::TestScorer::new());
2181 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2182 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2184 let pending_events = Mutex::new(VecDeque::new());
2185 let outbound_payments = OutboundPayments::new();
2186 let payment_id = PaymentId([0; 32]);
2187 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2190 outbound_payments.add_new_awaiting_invoice(
2191 payment_id, expiration, Retry::Attempts(0), None
2194 assert!(outbound_payments.has_pending_payments());
2196 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2197 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2200 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2202 .sign(payer_sign).unwrap()
2203 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2205 .sign(recipient_sign).unwrap();
2208 outbound_payments.send_payment_for_bolt12_invoice(
2209 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2210 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2214 assert!(!outbound_payments.has_pending_payments());
2216 let payment_hash = invoice.payment_hash();
2217 let reason = Some(PaymentFailureReason::PaymentExpired);
2219 assert!(!pending_events.lock().unwrap().is_empty());
2221 pending_events.lock().unwrap().pop_front(),
2222 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2224 assert!(pending_events.lock().unwrap().is_empty());
2228 fn fails_finding_route_for_bolt12_invoice() {
2229 let logger = test_utils::TestLogger::new();
2230 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2231 let scorer = RwLock::new(test_utils::TestScorer::new());
2232 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2233 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2235 let pending_events = Mutex::new(VecDeque::new());
2236 let outbound_payments = OutboundPayments::new();
2237 let payment_id = PaymentId([0; 32]);
2238 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2240 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2243 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2245 .sign(payer_sign).unwrap()
2246 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2248 .sign(recipient_sign).unwrap();
2251 outbound_payments.add_new_awaiting_invoice(
2252 payment_id, expiration, Retry::Attempts(0),
2253 Some(invoice.amount_msats() / 100 + 50_000)
2256 assert!(outbound_payments.has_pending_payments());
2258 router.expect_find_route(
2259 RouteParameters::from_payment_params_and_value(
2260 PaymentParameters::from_bolt12_invoice(&invoice),
2261 invoice.amount_msats(),
2263 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2267 outbound_payments.send_payment_for_bolt12_invoice(
2268 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2269 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2273 assert!(!outbound_payments.has_pending_payments());
2275 let payment_hash = invoice.payment_hash();
2276 let reason = Some(PaymentFailureReason::RouteNotFound);
2278 assert!(!pending_events.lock().unwrap().is_empty());
2280 pending_events.lock().unwrap().pop_front(),
2281 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2283 assert!(pending_events.lock().unwrap().is_empty());
2287 fn sends_payment_for_bolt12_invoice() {
2288 let logger = test_utils::TestLogger::new();
2289 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2290 let scorer = RwLock::new(test_utils::TestScorer::new());
2291 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2292 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2294 let pending_events = Mutex::new(VecDeque::new());
2295 let outbound_payments = OutboundPayments::new();
2296 let payment_id = PaymentId([0; 32]);
2297 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2299 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2302 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2304 .sign(payer_sign).unwrap()
2305 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2307 .sign(recipient_sign).unwrap();
2309 let route_params = RouteParameters {
2310 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2311 final_value_msat: invoice.amount_msats(),
2312 max_total_routing_fee_msat: Some(1234),
2314 router.expect_find_route(
2315 route_params.clone(),
2321 pubkey: recipient_pubkey(),
2322 node_features: NodeFeatures::empty(),
2323 short_channel_id: 42,
2324 channel_features: ChannelFeatures::empty(),
2325 fee_msat: invoice.amount_msats(),
2326 cltv_expiry_delta: 0,
2327 maybe_announced_channel: true,
2333 route_params: Some(route_params),
2337 assert!(!outbound_payments.has_pending_payments());
2339 outbound_payments.send_payment_for_bolt12_invoice(
2340 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2341 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2343 Err(Bolt12PaymentError::UnexpectedInvoice),
2345 assert!(!outbound_payments.has_pending_payments());
2346 assert!(pending_events.lock().unwrap().is_empty());
2349 outbound_payments.add_new_awaiting_invoice(
2350 payment_id, expiration, Retry::Attempts(0), Some(1234)
2353 assert!(outbound_payments.has_pending_payments());
2356 outbound_payments.send_payment_for_bolt12_invoice(
2357 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2358 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2362 assert!(outbound_payments.has_pending_payments());
2363 assert!(pending_events.lock().unwrap().is_empty());
2366 outbound_payments.send_payment_for_bolt12_invoice(
2367 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2368 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2370 Err(Bolt12PaymentError::DuplicateInvoice),
2372 assert!(outbound_payments.has_pending_payments());
2373 assert!(pending_events.lock().unwrap().is_empty());