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::{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(not(feature = "no-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 fn is_awaiting_invoice(&self) -> bool {
134 PendingOutboundPayment::AwaitingInvoice { .. } => true,
138 pub(super) fn is_fulfilled(&self) -> bool {
140 PendingOutboundPayment::Fulfilled { .. } => true,
144 pub(super) fn abandoned(&self) -> bool {
146 PendingOutboundPayment::Abandoned { .. } => true,
150 fn get_pending_fee_msat(&self) -> Option<u64> {
152 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
157 fn payment_hash(&self) -> Option<PaymentHash> {
159 PendingOutboundPayment::Legacy { .. } => None,
160 PendingOutboundPayment::AwaitingInvoice { .. } => None,
161 PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
162 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
163 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
164 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
168 fn mark_fulfilled(&mut self) {
169 let mut session_privs = HashSet::new();
170 core::mem::swap(&mut session_privs, match self {
171 PendingOutboundPayment::Legacy { session_privs } |
172 PendingOutboundPayment::Retryable { session_privs, .. } |
173 PendingOutboundPayment::Fulfilled { session_privs, .. } |
174 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
175 PendingOutboundPayment::AwaitingInvoice { .. } |
176 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
178 let payment_hash = self.payment_hash();
179 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
182 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
183 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
184 let mut our_session_privs = HashSet::new();
185 core::mem::swap(&mut our_session_privs, session_privs);
186 *self = PendingOutboundPayment::Abandoned {
187 session_privs: our_session_privs,
188 payment_hash: *payment_hash,
191 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash, .. } = self {
192 *self = PendingOutboundPayment::Abandoned {
193 session_privs: HashSet::new(),
194 payment_hash: *payment_hash,
200 /// panics if path is None and !self.is_fulfilled
201 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
202 let remove_res = match self {
203 PendingOutboundPayment::Legacy { session_privs } |
204 PendingOutboundPayment::Retryable { session_privs, .. } |
205 PendingOutboundPayment::Fulfilled { session_privs, .. } |
206 PendingOutboundPayment::Abandoned { session_privs, .. } => {
207 session_privs.remove(session_priv)
209 PendingOutboundPayment::AwaitingInvoice { .. } |
210 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
213 if let PendingOutboundPayment::Retryable {
214 ref mut pending_amt_msat, ref mut pending_fee_msat,
215 ref mut remaining_max_total_routing_fee_msat, ..
217 let path = path.expect("Removing a failed payment should always come with a path");
218 *pending_amt_msat -= path.final_value_msat();
219 let path_fee_msat = path.fee_msat();
220 if let Some(fee_msat) = pending_fee_msat.as_mut() {
221 *fee_msat -= path_fee_msat;
224 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
225 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
232 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
233 let insert_res = match self {
234 PendingOutboundPayment::Legacy { session_privs } |
235 PendingOutboundPayment::Retryable { session_privs, .. } => {
236 session_privs.insert(session_priv)
238 PendingOutboundPayment::AwaitingInvoice { .. } |
239 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
240 PendingOutboundPayment::Fulfilled { .. } => false,
241 PendingOutboundPayment::Abandoned { .. } => false,
244 if let PendingOutboundPayment::Retryable {
245 ref mut pending_amt_msat, ref mut pending_fee_msat,
246 ref mut remaining_max_total_routing_fee_msat, ..
248 *pending_amt_msat += path.final_value_msat();
249 let path_fee_msat = path.fee_msat();
250 if let Some(fee_msat) = pending_fee_msat.as_mut() {
251 *fee_msat += path_fee_msat;
254 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
255 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
262 pub(super) fn remaining_parts(&self) -> usize {
264 PendingOutboundPayment::Legacy { session_privs } |
265 PendingOutboundPayment::Retryable { session_privs, .. } |
266 PendingOutboundPayment::Fulfilled { session_privs, .. } |
267 PendingOutboundPayment::Abandoned { session_privs, .. } => {
270 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
271 PendingOutboundPayment::InvoiceReceived { .. } => 0,
276 /// Strategies available to retry payment path failures.
277 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
279 /// Max number of attempts to retry payment.
281 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
282 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
283 /// were retried along a route from a single call to [`Router::find_route_with_id`].
285 #[cfg(not(feature = "no-std"))]
286 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
287 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
289 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
290 Timeout(core::time::Duration),
293 #[cfg(feature = "no-std")]
294 impl_writeable_tlv_based_enum!(Retry,
299 #[cfg(not(feature = "no-std"))]
300 impl_writeable_tlv_based_enum!(Retry,
307 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
308 match (self, attempts) {
309 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
310 max_retry_count > count
312 #[cfg(all(not(feature = "no-std"), not(test)))]
313 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
314 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
315 #[cfg(all(not(feature = "no-std"), test))]
316 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
317 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
322 #[cfg(feature = "std")]
323 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
324 if let Some(expiry_time) = route_params.payment_params.expiry_time {
325 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
326 return elapsed > core::time::Duration::from_secs(expiry_time)
332 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
334 /// Storing minimal payment attempts information required for determining if a outbound payment can
336 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
337 /// This count will be incremented only after the result of the attempt is known. When it's 0,
338 /// it means the result of the first attempt is not known yet.
339 pub(crate) count: u32,
340 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
341 #[cfg(not(feature = "no-std"))]
342 first_attempted_at: T,
343 #[cfg(feature = "no-std")]
344 phantom: core::marker::PhantomData<T>,
348 #[cfg(not(any(feature = "no-std", test)))]
349 type ConfiguredTime = crate::util::time::MonotonicTime;
350 #[cfg(feature = "no-std")]
351 type ConfiguredTime = crate::util::time::Eternity;
352 #[cfg(all(not(feature = "no-std"), test))]
353 type ConfiguredTime = SinceEpoch;
355 impl<T: Time> PaymentAttemptsUsingTime<T> {
356 pub(crate) fn new() -> Self {
357 PaymentAttemptsUsingTime {
359 #[cfg(not(feature = "no-std"))]
360 first_attempted_at: T::now(),
361 #[cfg(feature = "no-std")]
362 phantom: core::marker::PhantomData,
367 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
368 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
369 #[cfg(feature = "no-std")]
370 return write!(f, "attempts: {}", self.count);
371 #[cfg(not(feature = "no-std"))]
374 "attempts: {}, duration: {}s",
376 T::now().duration_since(self.first_attempted_at).as_secs()
381 /// How long before a [`PendingOutboundPayment::AwaitingInvoice`] should be considered stale and
382 /// candidate for removal in [`OutboundPayments::remove_stale_payments`].
383 #[derive(Clone, Copy)]
384 pub(crate) enum StaleExpiration {
385 /// Number of times [`OutboundPayments::remove_stale_payments`] is called.
387 /// Duration since the Unix epoch.
388 AbsoluteTimeout(core::time::Duration),
391 impl_writeable_tlv_based_enum!(StaleExpiration,
397 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
398 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
400 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
401 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
402 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
403 #[derive(Clone, Debug, PartialEq, Eq)]
404 pub enum RetryableSendFailure {
405 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
406 /// that this error is *not* caused by [`Retry::Timeout`].
408 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
410 /// We were unable to find a route to the destination.
412 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
413 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
415 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
416 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
417 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
421 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
422 /// of several states. This enum is returned as the Err() type describing which state the payment
423 /// is in, see the description of individual enum states for more.
425 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
426 #[derive(Clone, Debug, PartialEq, Eq)]
427 pub enum PaymentSendFailure {
428 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
429 /// send the payment at all.
431 /// You can freely resend the payment in full (with the parameter error fixed).
433 /// Because the payment failed outright, no payment tracking is done and no
434 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
436 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
437 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
438 ParameterError(APIError),
439 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
440 /// from attempting to send the payment at all.
442 /// You can freely resend the payment in full (with the parameter error fixed).
444 /// Because the payment failed outright, no payment tracking is done and no
445 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
447 /// The results here are ordered the same as the paths in the route object which was passed to
450 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
451 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
452 PathParameterError(Vec<Result<(), APIError>>),
453 /// All paths which were attempted failed to send, with no channel state change taking place.
454 /// You can freely resend the payment in full (though you probably want to do so over different
455 /// paths than the ones selected).
457 /// Because the payment failed outright, no payment tracking is done and no
458 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
460 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
461 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
462 AllFailedResendSafe(Vec<APIError>),
463 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
464 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
466 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
467 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
468 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
470 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
471 /// some paths have irrevocably committed to the HTLC.
473 /// The results here are ordered the same as the paths in the route object that was passed to
476 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
477 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
479 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
481 /// The errors themselves, in the same order as the paths from the route.
482 results: Vec<Result<(), APIError>>,
483 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
484 /// contain a [`RouteParameters`] object for the failing paths.
485 failed_paths_retry: Option<RouteParameters>,
486 /// The payment id for the payment, which is now at least partially pending.
487 payment_id: PaymentId,
491 /// An error when attempting to pay a BOLT 12 invoice.
492 #[derive(Clone, Debug, PartialEq, Eq)]
493 pub(super) enum Bolt12PaymentError {
494 /// The invoice was not requested.
496 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
500 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
501 /// [`Event::ProbeFailed`].
503 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
504 #[derive(Clone, Debug, PartialEq, Eq)]
505 pub enum ProbeSendFailure {
506 /// We were unable to find a route to the destination.
508 /// We failed to send the payment probes.
509 SendingFailed(PaymentSendFailure),
512 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
514 /// This should generally be constructed with data communicated to us from the recipient (via a
515 /// BOLT11 or BOLT12 invoice).
516 #[derive(Clone, Debug, PartialEq, Eq)]
517 pub struct RecipientOnionFields {
518 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
519 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
520 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
523 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
524 /// multi-path payments require a recipient-provided secret.
526 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
527 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
528 /// recipient will not reject it.
529 pub payment_secret: Option<PaymentSecret>,
530 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
531 /// arbitrary length. This gives recipients substantially more flexibility to receive
534 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
535 /// scheme to authenticate received payments against expected payments and invoices, this field
536 /// is not used in LDK for received payments, and can be used to store arbitrary data in
537 /// invoices which will be received with the payment.
539 /// Note that this field was added to the lightning specification more recently than
540 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
541 /// may not be supported as universally.
542 pub payment_metadata: Option<Vec<u8>>,
543 /// See [`Self::custom_tlvs`] for more info.
544 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
547 impl_writeable_tlv_based!(RecipientOnionFields, {
548 (0, payment_secret, option),
549 (1, custom_tlvs, optional_vec),
550 (2, payment_metadata, option),
553 impl RecipientOnionFields {
554 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
555 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
556 /// but do not require or provide any further data.
557 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
558 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
561 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
562 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
563 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
564 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
565 /// instead want to use [`RecipientOnionFields::secret_only`].
567 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
568 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
569 pub fn spontaneous_empty() -> Self {
570 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
573 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
574 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
575 /// respectively. TLV type numbers must be unique and within the range
576 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
578 /// This method will also error for types in the experimental range which have been
579 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
581 /// See [`Self::custom_tlvs`] for more info.
582 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
583 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
584 let mut prev_type = None;
585 for (typ, _) in custom_tlvs.iter() {
586 if *typ < 1 << 16 { return Err(()); }
587 if *typ == 5482373484 { return Err(()); } // keysend
589 Some(prev) if prev >= *typ => return Err(()),
592 prev_type = Some(*typ);
594 self.custom_tlvs = custom_tlvs;
598 /// Gets the custom TLVs that will be sent or have been received.
600 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
601 /// additional flexibility on top of payment metadata, as while other implementations may
602 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
603 /// do not have this restriction.
605 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
606 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
607 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
608 #[cfg(not(c_bindings))]
609 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
613 /// Gets the custom TLVs that will be sent or have been received.
615 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
616 /// additional flexibility on top of payment metadata, as while other implementations may
617 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
618 /// do not have this restriction.
620 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
621 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
622 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
624 pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
625 self.custom_tlvs.clone()
628 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
629 /// have to make sure that some fields match exactly across the parts. For those that aren't
630 /// required to match, if they don't match we should remove them so as to not expose data
631 /// that's dependent on the HTLC receive order to users.
633 /// Here we implement this, first checking compatibility then mutating two objects and then
634 /// dropping any remaining non-matching fields from both.
635 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
636 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
637 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
639 let tlvs = &mut self.custom_tlvs;
640 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
642 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
643 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
644 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
646 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
647 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
653 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
654 pub(super) struct SendAlongPathArgs<'a> {
656 pub payment_hash: &'a PaymentHash,
657 pub recipient_onion: RecipientOnionFields,
658 pub total_value: u64,
660 pub payment_id: PaymentId,
661 pub keysend_preimage: &'a Option<PaymentPreimage>,
662 pub session_priv_bytes: [u8; 32],
665 pub(super) struct OutboundPayments {
666 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
667 pub(super) retry_lock: Mutex<()>,
670 impl OutboundPayments {
671 pub(super) fn new() -> Self {
673 pending_outbound_payments: Mutex::new(HashMap::new()),
674 retry_lock: Mutex::new(()),
678 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
679 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
680 retry_strategy: Retry, route_params: RouteParameters, router: &R,
681 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
682 node_signer: &NS, best_block_height: u32, logger: &L,
683 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
684 ) -> Result<(), RetryableSendFailure>
687 ES::Target: EntropySource,
688 NS::Target: NodeSigner,
690 IH: Fn() -> InFlightHtlcs,
691 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
693 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
694 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
695 best_block_height, logger, pending_events, &send_payment_along_path)
698 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
699 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
700 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
701 send_payment_along_path: F
702 ) -> Result<(), PaymentSendFailure>
704 ES::Target: EntropySource,
705 NS::Target: NodeSigner,
706 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
708 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)?;
709 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
710 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
711 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
714 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
715 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
716 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
717 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
718 node_signer: &NS, best_block_height: u32, logger: &L,
719 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
720 ) -> Result<PaymentHash, RetryableSendFailure>
723 ES::Target: EntropySource,
724 NS::Target: NodeSigner,
726 IH: Fn() -> InFlightHtlcs,
727 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
729 let preimage = payment_preimage
730 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
731 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
732 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
733 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
734 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
735 .map(|()| payment_hash)
738 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
739 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
740 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
741 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
742 ) -> Result<PaymentHash, PaymentSendFailure>
744 ES::Target: EntropySource,
745 NS::Target: NodeSigner,
746 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
748 let preimage = payment_preimage
749 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
750 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
751 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
752 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
754 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
755 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
757 Ok(()) => Ok(payment_hash),
759 self.remove_outbound_if_all_failed(payment_id, &e);
765 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
766 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
767 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
768 best_block_height: u32, logger: &L,
769 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
770 send_payment_along_path: SP,
771 ) -> Result<(), Bolt12PaymentError>
774 ES::Target: EntropySource,
775 NS::Target: NodeSigner,
777 IH: Fn() -> InFlightHtlcs,
778 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
780 let payment_hash = invoice.payment_hash();
781 let max_total_routing_fee_msat;
782 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
783 hash_map::Entry::Occupied(entry) => match entry.get() {
784 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
785 max_total_routing_fee_msat = *max_total_fee;
786 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
788 retry_strategy: *retry_strategy,
789 max_total_routing_fee_msat,
792 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
794 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
797 let pay_params = PaymentParameters::from_bolt12_invoice(&invoice);
798 let amount_msat = invoice.amount_msats();
799 let mut route_params = RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
800 if let Some(max_fee_msat) = max_total_routing_fee_msat {
801 route_params.max_total_routing_fee_msat = Some(max_fee_msat);
804 self.find_route_and_send_payment(
805 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
806 entropy_source, node_signer, best_block_height, logger, pending_events,
807 &send_payment_along_path
813 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
814 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
815 best_block_height: u32,
816 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
817 send_payment_along_path: SP,
821 ES::Target: EntropySource,
822 NS::Target: NodeSigner,
823 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
824 IH: Fn() -> InFlightHtlcs,
825 FH: Fn() -> Vec<ChannelDetails>,
828 let _single_thread = self.retry_lock.lock().unwrap();
830 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
831 let mut retry_id_route_params = None;
832 for (pmt_id, pmt) in outbounds.iter_mut() {
833 if pmt.is_auto_retryable_now() {
834 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
835 if pending_amt_msat < total_msat {
836 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
837 final_value_msat: *total_msat - *pending_amt_msat,
838 payment_params: params.clone(),
839 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
843 } else { debug_assert!(false); }
846 core::mem::drop(outbounds);
847 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
848 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)
852 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
853 outbounds.retain(|pmt_id, pmt| {
854 let mut retain = true;
855 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
856 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
857 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
858 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
860 payment_hash: *payment_hash,
870 pub(super) fn needs_abandon(&self) -> bool {
871 let outbounds = self.pending_outbound_payments.lock().unwrap();
872 outbounds.iter().any(|(_, pmt)|
873 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
874 !pmt.is_awaiting_invoice())
877 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
878 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
880 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
881 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
882 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
883 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
884 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
885 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
886 node_signer: &NS, best_block_height: u32, logger: &L,
887 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
888 ) -> Result<(), RetryableSendFailure>
891 ES::Target: EntropySource,
892 NS::Target: NodeSigner,
894 IH: Fn() -> InFlightHtlcs,
895 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
897 #[cfg(feature = "std")] {
898 if has_expired(&route_params) {
899 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
900 payment_id, payment_hash);
901 return Err(RetryableSendFailure::PaymentExpired)
905 let mut route = router.find_route_with_id(
906 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
907 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
908 payment_hash, payment_id,
910 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
911 payment_id, payment_hash);
912 RetryableSendFailure::RouteNotFound
915 if route.route_params.as_ref() != Some(&route_params) {
917 "Routers are expected to return a Route which includes the requested RouteParameters");
918 route.route_params = Some(route_params.clone());
921 let onion_session_privs = self.add_new_pending_payment(payment_hash,
922 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
923 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
925 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
926 payment_id, payment_hash);
927 RetryableSendFailure::DuplicatePayment
930 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
931 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
932 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
933 payment_id, payment_hash, res);
934 if let Err(e) = res {
935 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);
940 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
941 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
942 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
943 node_signer: &NS, best_block_height: u32, logger: &L,
944 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
948 ES::Target: EntropySource,
949 NS::Target: NodeSigner,
951 IH: Fn() -> InFlightHtlcs,
952 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
954 #[cfg(feature = "std")] {
955 if has_expired(&route_params) {
956 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
957 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
962 let mut route = match router.find_route_with_id(
963 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
964 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
965 payment_hash, payment_id,
969 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
970 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
975 if route.route_params.as_ref() != Some(&route_params) {
977 "Routers are expected to return a Route which includes the requested RouteParameters");
978 route.route_params = Some(route_params.clone());
981 for path in route.paths.iter() {
982 if path.hops.len() == 0 {
983 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
984 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
989 macro_rules! abandon_with_entry {
990 ($payment: expr, $reason: expr) => {
991 $payment.get_mut().mark_abandoned($reason);
992 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
993 if $payment.get().remaining_parts() == 0 {
994 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1004 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
1005 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1006 match outbounds.entry(payment_id) {
1007 hash_map::Entry::Occupied(mut payment) => {
1008 match payment.get() {
1009 PendingOutboundPayment::Retryable {
1010 total_msat, keysend_preimage, payment_secret, payment_metadata,
1011 custom_tlvs, pending_amt_msat, ..
1013 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1014 let retry_amt_msat = route.get_total_amount();
1015 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1016 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);
1017 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1021 if !payment.get().is_retryable_now() {
1022 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1023 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1027 let total_msat = *total_msat;
1028 let recipient_onion = RecipientOnionFields {
1029 payment_secret: *payment_secret,
1030 payment_metadata: payment_metadata.clone(),
1031 custom_tlvs: custom_tlvs.clone(),
1033 let keysend_preimage = *keysend_preimage;
1035 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1036 for _ in 0..route.paths.len() {
1037 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1040 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1041 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1044 payment.get_mut().increment_attempts();
1046 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1048 PendingOutboundPayment::Legacy { .. } => {
1049 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1052 PendingOutboundPayment::AwaitingInvoice { .. } => {
1053 log_error!(logger, "Payment not yet sent");
1056 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1057 let total_amount = route_params.final_value_msat;
1058 let recipient_onion = RecipientOnionFields {
1059 payment_secret: None,
1060 payment_metadata: None,
1061 custom_tlvs: vec![],
1063 let retry_strategy = Some(*retry_strategy);
1064 let payment_params = Some(route_params.payment_params.clone());
1065 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1066 *payment_hash, recipient_onion.clone(), None, &route,
1067 retry_strategy, payment_params, entropy_source, best_block_height
1069 *payment.into_mut() = retryable_payment;
1070 (total_amount, recipient_onion, None, onion_session_privs)
1072 PendingOutboundPayment::Fulfilled { .. } => {
1073 log_error!(logger, "Payment already completed");
1076 PendingOutboundPayment::Abandoned { .. } => {
1077 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1082 hash_map::Entry::Vacant(_) => {
1083 log_error!(logger, "Payment with ID {} not found", &payment_id);
1088 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1089 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1090 &send_payment_along_path);
1091 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1092 if let Err(e) = res {
1093 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);
1097 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1098 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1099 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1100 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1101 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1105 ES::Target: EntropySource,
1106 NS::Target: NodeSigner,
1108 IH: Fn() -> InFlightHtlcs,
1109 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1112 PaymentSendFailure::AllFailedResendSafe(errs) => {
1113 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);
1114 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);
1116 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1117 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1118 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1119 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1120 // return `Ok()` here, ignoring any retry errors.
1121 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);
1123 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1124 // This may happen if we send a payment and some paths fail, but only due to a temporary
1125 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1126 // initial HTLC-Add messages yet.
1128 PaymentSendFailure::PathParameterError(results) => {
1129 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1130 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1131 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1133 PaymentSendFailure::ParameterError(e) => {
1134 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1135 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1137 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1141 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1142 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1143 paths: Vec<Path>, path_results: I, logger: &L,
1144 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1145 ) where L::Target: Logger {
1146 let mut events = pending_events.lock().unwrap();
1147 debug_assert_eq!(paths.len(), path_results.len());
1148 for (path, path_res) in paths.into_iter().zip(path_results) {
1149 if let Err(e) = path_res {
1150 if let APIError::MonitorUpdateInProgress = e { continue }
1151 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1152 let mut failed_scid = None;
1153 if let APIError::ChannelUnavailable { .. } = e {
1154 let scid = path.hops[0].short_channel_id;
1155 failed_scid = Some(scid);
1156 route_params.payment_params.previously_failed_channels.push(scid);
1158 events.push_back((events::Event::PaymentPathFailed {
1159 payment_id: Some(payment_id),
1161 payment_failed_permanently: false,
1162 failure: events::PathFailure::InitialSend { err: e },
1164 short_channel_id: failed_scid,
1174 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1175 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1176 best_block_height: u32, send_payment_along_path: F
1177 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1179 ES::Target: EntropySource,
1180 NS::Target: NodeSigner,
1181 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1183 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1184 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1186 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1188 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1189 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1190 err: "No need probing a path with less than two hops".to_string()
1194 let route = Route { paths: vec![path], route_params: None };
1195 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1196 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1197 entropy_source, best_block_height)?;
1199 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1200 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1202 Ok(()) => Ok((payment_hash, payment_id)),
1204 self.remove_outbound_if_all_failed(payment_id, &e);
1211 pub(super) fn test_set_payment_metadata(
1212 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1214 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1215 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1216 *payment_metadata = new_payment_metadata;
1218 _ => panic!("Need a retryable payment to update metadata on"),
1223 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1224 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1225 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1226 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1227 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1230 pub(super) fn add_new_pending_payment<ES: Deref>(
1231 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1232 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1233 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1234 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1235 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1236 match pending_outbounds.entry(payment_id) {
1237 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1238 hash_map::Entry::Vacant(entry) => {
1239 let (payment, onion_session_privs) = self.create_pending_payment(
1240 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1241 payment_params, entropy_source, best_block_height
1243 entry.insert(payment);
1244 Ok(onion_session_privs)
1249 fn create_pending_payment<ES: Deref>(
1250 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1251 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1252 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1253 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1255 ES::Target: EntropySource,
1257 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1258 for _ in 0..route.paths.len() {
1259 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1262 let mut payment = PendingOutboundPayment::Retryable {
1264 attempts: PaymentAttempts::new(),
1266 session_privs: HashSet::new(),
1267 pending_amt_msat: 0,
1268 pending_fee_msat: Some(0),
1270 payment_secret: recipient_onion.payment_secret,
1271 payment_metadata: recipient_onion.payment_metadata,
1273 custom_tlvs: recipient_onion.custom_tlvs,
1274 starting_block_height: best_block_height,
1275 total_msat: route.get_total_amount(),
1276 remaining_max_total_routing_fee_msat:
1277 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1280 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1281 assert!(payment.insert(*session_priv_bytes, path));
1284 (payment, onion_session_privs)
1287 pub(super) fn add_new_awaiting_invoice(
1288 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1289 max_total_routing_fee_msat: Option<u64>
1290 ) -> Result<(), ()> {
1291 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1292 match pending_outbounds.entry(payment_id) {
1293 hash_map::Entry::Occupied(_) => Err(()),
1294 hash_map::Entry::Vacant(entry) => {
1295 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1298 max_total_routing_fee_msat,
1306 fn pay_route_internal<NS: Deref, F>(
1307 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1308 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1309 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1310 send_payment_along_path: &F
1311 ) -> Result<(), PaymentSendFailure>
1313 NS::Target: NodeSigner,
1314 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1316 if route.paths.len() < 1 {
1317 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1319 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1320 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1322 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1324 let mut total_value = 0;
1325 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1326 let mut path_errs = Vec::with_capacity(route.paths.len());
1327 'path_check: for path in route.paths.iter() {
1328 if path.hops.len() < 1 || path.hops.len() > 20 {
1329 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1330 continue 'path_check;
1332 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1333 usize::max_value() } else { path.hops.len() - 1 };
1334 for (idx, hop) in path.hops.iter().enumerate() {
1335 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1336 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1337 continue 'path_check;
1340 total_value += path.final_value_msat();
1341 path_errs.push(Ok(()));
1343 if path_errs.iter().any(|e| e.is_err()) {
1344 return Err(PaymentSendFailure::PathParameterError(path_errs));
1346 if let Some(amt_msat) = recv_value_msat {
1347 total_value = amt_msat;
1350 let cur_height = best_block_height + 1;
1351 let mut results = Vec::new();
1352 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1353 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1354 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1355 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1356 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1360 Err(APIError::MonitorUpdateInProgress) => {
1361 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1362 // considered "in flight" and we shouldn't remove it from the
1363 // PendingOutboundPayment set.
1366 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1367 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1368 let removed = payment.remove(&session_priv_bytes, Some(path));
1369 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1371 debug_assert!(false, "This can't happen as the payment was added by callers");
1372 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1376 results.push(path_res);
1378 let mut has_ok = false;
1379 let mut has_err = false;
1380 let mut has_unsent = false;
1381 let mut total_ok_fees_msat = 0;
1382 let mut total_ok_amt_sent_msat = 0;
1383 for (res, path) in results.iter().zip(route.paths.iter()) {
1386 total_ok_fees_msat += path.fee_msat();
1387 total_ok_amt_sent_msat += path.final_value_msat();
1389 if res.is_err() { has_err = true; }
1390 if let &Err(APIError::MonitorUpdateInProgress) = res {
1391 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1395 total_ok_fees_msat += path.fee_msat();
1396 total_ok_amt_sent_msat += path.final_value_msat();
1397 } else if res.is_err() {
1401 if has_err && has_ok {
1402 Err(PaymentSendFailure::PartialFailure {
1405 failed_paths_retry: if has_unsent {
1406 if let Some(route_params) = &route.route_params {
1407 let mut route_params = route_params.clone();
1408 // We calculate the leftover fee budget we're allowed to spend by
1409 // subtracting the used fee from the total fee budget.
1410 route_params.max_total_routing_fee_msat = route_params
1411 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1413 // We calculate the remaining target amount by subtracting the succeded
1415 route_params.final_value_msat = route_params.final_value_msat
1416 .saturating_sub(total_ok_amt_sent_msat);
1422 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1429 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1430 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1431 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1432 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1433 send_payment_along_path: F
1434 ) -> Result<(), PaymentSendFailure>
1436 NS::Target: NodeSigner,
1437 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1439 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1440 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1441 &send_payment_along_path)
1442 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1445 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1446 // map as the payment is free to be resent.
1447 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1448 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1449 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1450 debug_assert!(removed, "We should always have a pending payment to remove here");
1454 pub(super) fn claim_htlc<L: Deref>(
1455 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1456 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1457 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1459 ) where L::Target: Logger {
1460 let mut session_priv_bytes = [0; 32];
1461 session_priv_bytes.copy_from_slice(&session_priv[..]);
1462 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1463 let mut pending_events = pending_events.lock().unwrap();
1464 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1465 if !payment.get().is_fulfilled() {
1466 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1467 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1468 let fee_paid_msat = payment.get().get_pending_fee_msat();
1469 pending_events.push_back((events::Event::PaymentSent {
1470 payment_id: Some(payment_id),
1474 }, Some(ev_completion_action.clone())));
1475 payment.get_mut().mark_fulfilled();
1479 // We currently immediately remove HTLCs which were fulfilled on-chain.
1480 // This could potentially lead to removing a pending payment too early,
1481 // with a reorg of one block causing us to re-add the fulfilled payment on
1483 // TODO: We should have a second monitor event that informs us of payments
1484 // irrevocably fulfilled.
1485 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1486 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1487 pending_events.push_back((events::Event::PaymentPathSuccessful {
1491 }, Some(ev_completion_action)));
1495 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1499 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1500 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1502 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1503 let mut pending_events = pending_events.lock().unwrap();
1504 for source in sources {
1505 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1506 let mut session_priv_bytes = [0; 32];
1507 session_priv_bytes.copy_from_slice(&session_priv[..]);
1508 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1509 assert!(payment.get().is_fulfilled());
1510 if payment.get_mut().remove(&session_priv_bytes, None) {
1511 let payment_hash = payment.get().payment_hash();
1512 debug_assert!(payment_hash.is_some());
1513 pending_events.push_back((events::Event::PaymentPathSuccessful {
1524 pub(super) fn remove_stale_payments(
1525 &self, duration_since_epoch: Duration,
1526 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1528 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1529 let mut pending_events = pending_events.lock().unwrap();
1530 pending_outbound_payments.retain(|payment_id, payment| match payment {
1531 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1532 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1533 // this could race the user making a duplicate send_payment call and our idempotency
1534 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1535 // removal. This should be more than sufficient to ensure the idempotency of any
1536 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1538 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1539 let mut no_remaining_entries = session_privs.is_empty();
1540 if no_remaining_entries {
1541 for (ev, _) in pending_events.iter() {
1543 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1544 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1545 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1546 if payment_id == ev_payment_id {
1547 no_remaining_entries = false;
1555 if no_remaining_entries {
1556 *timer_ticks_without_htlcs += 1;
1557 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1559 *timer_ticks_without_htlcs = 0;
1563 PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1564 let is_stale = match expiration {
1565 StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1566 *absolute_expiry <= duration_since_epoch
1568 StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1569 if *timer_ticks_remaining > 0 {
1570 *timer_ticks_remaining -= 1;
1578 pending_events.push_back(
1579 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1590 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1591 pub(super) fn fail_htlc<L: Deref>(
1592 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1593 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1594 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1595 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1596 ) -> bool where L::Target: Logger {
1598 let DecodedOnionFailure {
1599 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1601 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1603 let DecodedOnionFailure { network_update, short_channel_id, payment_failed_permanently } =
1604 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1606 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1607 let mut session_priv_bytes = [0; 32];
1608 session_priv_bytes.copy_from_slice(&session_priv[..]);
1609 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1611 // If any payments already need retry, there's no need to generate a redundant
1612 // `PendingHTLCsForwardable`.
1613 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1614 let mut awaiting_retry = false;
1615 if pmt.is_auto_retryable_now() {
1616 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1617 if pending_amt_msat < total_msat {
1618 awaiting_retry = true;
1625 let mut full_failure_ev = None;
1626 let mut pending_retry_ev = false;
1627 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1628 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1629 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1632 if payment.get().is_fulfilled() {
1633 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1636 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1637 if let Some(scid) = short_channel_id {
1638 // TODO: If we decided to blame ourselves (or one of our channels) in
1639 // process_onion_failure we should close that channel as it implies our
1640 // next-hop is needlessly blaming us!
1641 payment.get_mut().insert_previously_failed_scid(scid);
1644 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1645 let reason = if payment_failed_permanently {
1646 PaymentFailureReason::RecipientRejected
1648 PaymentFailureReason::RetriesExhausted
1650 payment.get_mut().mark_abandoned(reason);
1651 is_retryable_now = false;
1653 if payment.get().remaining_parts() == 0 {
1654 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1655 if !payment_is_probe {
1656 full_failure_ev = Some(events::Event::PaymentFailed {
1657 payment_id: *payment_id,
1658 payment_hash: *payment_hash,
1667 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1670 core::mem::drop(outbounds);
1671 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1673 let path_failure = {
1674 if payment_is_probe {
1675 if payment_failed_permanently {
1676 events::Event::ProbeSuccessful {
1677 payment_id: *payment_id,
1678 payment_hash: payment_hash.clone(),
1682 events::Event::ProbeFailed {
1683 payment_id: *payment_id,
1684 payment_hash: payment_hash.clone(),
1690 // If we miss abandoning the payment above, we *must* generate an event here or else the
1691 // payment will sit in our outbounds forever.
1692 if attempts_remaining && !already_awaiting_retry {
1693 debug_assert!(full_failure_ev.is_none());
1694 pending_retry_ev = true;
1696 events::Event::PaymentPathFailed {
1697 payment_id: Some(*payment_id),
1698 payment_hash: payment_hash.clone(),
1699 payment_failed_permanently,
1700 failure: events::PathFailure::OnPath { network_update },
1704 error_code: onion_error_code,
1706 error_data: onion_error_data
1710 let mut pending_events = pending_events.lock().unwrap();
1711 pending_events.push_back((path_failure, None));
1712 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1716 pub(super) fn abandon_payment(
1717 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1718 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1720 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1721 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1722 payment.get_mut().mark_abandoned(reason);
1723 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1724 if payment.get().remaining_parts() == 0 {
1725 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1727 payment_hash: *payment_hash,
1732 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1733 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1742 pub fn has_pending_payments(&self) -> bool {
1743 !self.pending_outbound_payments.lock().unwrap().is_empty()
1747 pub fn clear_pending_payments(&self) {
1748 self.pending_outbound_payments.lock().unwrap().clear()
1752 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1754 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1755 probing_cookie_secret: [u8; 32]) -> bool
1757 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1758 target_payment_hash == *payment_hash
1761 /// Returns the 'probing cookie' for the given [`PaymentId`].
1762 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1763 let mut preimage = [0u8; 64];
1764 preimage[..32].copy_from_slice(&probing_cookie_secret);
1765 preimage[32..].copy_from_slice(&payment_id.0);
1766 PaymentHash(Sha256::hash(&preimage).into_inner())
1769 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1771 (0, session_privs, required),
1774 (0, session_privs, required),
1775 (1, payment_hash, option),
1776 (3, timer_ticks_without_htlcs, (default_value, 0)),
1779 (0, session_privs, required),
1780 (1, pending_fee_msat, option),
1781 (2, payment_hash, required),
1782 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1783 // never see it - `payment_params` was added here after the field was added/required.
1784 (3, payment_params, (option: ReadableArgs, 0)),
1785 (4, payment_secret, option),
1786 (5, keysend_preimage, option),
1787 (6, total_msat, required),
1788 (7, payment_metadata, option),
1789 (8, pending_amt_msat, required),
1790 (9, custom_tlvs, optional_vec),
1791 (10, starting_block_height, required),
1792 (11, remaining_max_total_routing_fee_msat, option),
1793 (not_written, retry_strategy, (static_value, None)),
1794 (not_written, attempts, (static_value, PaymentAttempts::new())),
1797 (0, session_privs, required),
1798 (1, reason, option),
1799 (2, payment_hash, required),
1801 (5, AwaitingInvoice) => {
1802 (0, expiration, required),
1803 (2, retry_strategy, required),
1804 (4, max_total_routing_fee_msat, option),
1806 (7, InvoiceReceived) => {
1807 (0, payment_hash, required),
1808 (2, retry_strategy, required),
1809 (4, max_total_routing_fee_msat, option),
1815 use bitcoin::network::constants::Network;
1816 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1818 use core::time::Duration;
1820 use crate::events::{Event, PathFailure, PaymentFailureReason};
1821 use crate::ln::PaymentHash;
1822 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1823 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1824 use crate::ln::msgs::{ErrorAction, LightningError};
1825 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1826 #[cfg(feature = "std")]
1827 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1828 use crate::offers::offer::OfferBuilder;
1829 use crate::offers::test_utils::*;
1830 use crate::routing::gossip::NetworkGraph;
1831 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1832 use crate::sync::{Arc, Mutex, RwLock};
1833 use crate::util::errors::APIError;
1834 use crate::util::test_utils;
1836 use alloc::collections::VecDeque;
1839 fn test_recipient_onion_fields_with_custom_tlvs() {
1840 let onion_fields = RecipientOnionFields::spontaneous_empty();
1842 let bad_type_range_tlvs = vec![
1846 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1848 let keysend_tlv = vec![
1849 (5482373484, vec![42; 32]),
1851 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1853 let good_tlvs = vec![
1854 ((1 << 16) + 1, vec![42]),
1855 ((1 << 16) + 3, vec![42; 32]),
1857 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1861 #[cfg(feature = "std")]
1862 fn fails_paying_after_expiration() {
1863 do_fails_paying_after_expiration(false);
1864 do_fails_paying_after_expiration(true);
1866 #[cfg(feature = "std")]
1867 fn do_fails_paying_after_expiration(on_retry: bool) {
1868 let outbound_payments = OutboundPayments::new();
1869 let logger = test_utils::TestLogger::new();
1870 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1871 let scorer = RwLock::new(test_utils::TestScorer::new());
1872 let router = test_utils::TestRouter::new(network_graph, &scorer);
1873 let secp_ctx = Secp256k1::new();
1874 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1876 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1877 let payment_params = PaymentParameters::from_node_id(
1878 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1880 ).with_expiry_time(past_expiry_time);
1881 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1882 let pending_events = Mutex::new(VecDeque::new());
1884 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1885 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1886 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1887 &&keys_manager, 0).unwrap();
1888 outbound_payments.find_route_and_send_payment(
1889 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1890 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1892 let events = pending_events.lock().unwrap();
1893 assert_eq!(events.len(), 1);
1894 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1895 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1896 } else { panic!("Unexpected event"); }
1898 let err = outbound_payments.send_payment(
1899 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1900 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1901 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1902 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1907 fn find_route_error() {
1908 do_find_route_error(false);
1909 do_find_route_error(true);
1911 fn do_find_route_error(on_retry: bool) {
1912 let outbound_payments = OutboundPayments::new();
1913 let logger = test_utils::TestLogger::new();
1914 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1915 let scorer = RwLock::new(test_utils::TestScorer::new());
1916 let router = test_utils::TestRouter::new(network_graph, &scorer);
1917 let secp_ctx = Secp256k1::new();
1918 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1920 let payment_params = PaymentParameters::from_node_id(
1921 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1922 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1923 router.expect_find_route(route_params.clone(),
1924 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1926 let pending_events = Mutex::new(VecDeque::new());
1928 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1929 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1930 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1931 &&keys_manager, 0).unwrap();
1932 outbound_payments.find_route_and_send_payment(
1933 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1934 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1936 let events = pending_events.lock().unwrap();
1937 assert_eq!(events.len(), 1);
1938 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1940 let err = outbound_payments.send_payment(
1941 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1942 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1943 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1944 if let RetryableSendFailure::RouteNotFound = err {
1945 } else { panic!("Unexpected error"); }
1950 fn initial_send_payment_path_failed_evs() {
1951 let outbound_payments = OutboundPayments::new();
1952 let logger = test_utils::TestLogger::new();
1953 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1954 let scorer = RwLock::new(test_utils::TestScorer::new());
1955 let router = test_utils::TestRouter::new(network_graph, &scorer);
1956 let secp_ctx = Secp256k1::new();
1957 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1959 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1960 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1961 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1962 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1963 let failed_scid = 42;
1965 paths: vec![Path { hops: vec![RouteHop {
1966 pubkey: receiver_pk,
1967 node_features: NodeFeatures::empty(),
1968 short_channel_id: failed_scid,
1969 channel_features: ChannelFeatures::empty(),
1971 cltv_expiry_delta: 0,
1972 maybe_announced_channel: true,
1973 }], blinded_tail: None }],
1974 route_params: Some(route_params.clone()),
1976 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1977 let mut route_params_w_failed_scid = route_params.clone();
1978 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1979 let mut route_w_failed_scid = route.clone();
1980 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
1981 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
1982 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1983 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1985 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1986 // PaymentPathFailed event.
1987 let pending_events = Mutex::new(VecDeque::new());
1988 outbound_payments.send_payment(
1989 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1990 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1991 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1992 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1993 let mut events = pending_events.lock().unwrap();
1994 assert_eq!(events.len(), 2);
1995 if let Event::PaymentPathFailed {
1997 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1999 assert_eq!(short_channel_id, Some(failed_scid));
2000 } else { panic!("Unexpected event"); }
2001 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2003 core::mem::drop(events);
2005 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2006 outbound_payments.send_payment(
2007 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2008 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2009 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2010 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2011 assert_eq!(pending_events.lock().unwrap().len(), 0);
2013 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2014 outbound_payments.send_payment(
2015 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2016 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2017 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2018 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2019 let events = pending_events.lock().unwrap();
2020 assert_eq!(events.len(), 2);
2021 if let Event::PaymentPathFailed {
2023 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2025 assert_eq!(short_channel_id, None);
2026 } else { panic!("Unexpected event"); }
2027 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2031 fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2032 let pending_events = Mutex::new(VecDeque::new());
2033 let outbound_payments = OutboundPayments::new();
2034 let payment_id = PaymentId([0; 32]);
2035 let absolute_expiry = 100;
2036 let tick_interval = 10;
2037 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2039 assert!(!outbound_payments.has_pending_payments());
2041 outbound_payments.add_new_awaiting_invoice(
2042 payment_id, expiration, Retry::Attempts(0), None
2045 assert!(outbound_payments.has_pending_payments());
2047 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2048 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2049 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2051 assert!(outbound_payments.has_pending_payments());
2052 assert!(pending_events.lock().unwrap().is_empty());
2055 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2056 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2058 assert!(!outbound_payments.has_pending_payments());
2059 assert!(!pending_events.lock().unwrap().is_empty());
2061 pending_events.lock().unwrap().pop_front(),
2062 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2064 assert!(pending_events.lock().unwrap().is_empty());
2067 outbound_payments.add_new_awaiting_invoice(
2068 payment_id, expiration, Retry::Attempts(0), None
2071 assert!(outbound_payments.has_pending_payments());
2074 outbound_payments.add_new_awaiting_invoice(
2075 payment_id, expiration, Retry::Attempts(0), None
2081 fn removes_stale_awaiting_invoice_using_timer_ticks() {
2082 let pending_events = Mutex::new(VecDeque::new());
2083 let outbound_payments = OutboundPayments::new();
2084 let payment_id = PaymentId([0; 32]);
2085 let timer_ticks = 3;
2086 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2088 assert!(!outbound_payments.has_pending_payments());
2090 outbound_payments.add_new_awaiting_invoice(
2091 payment_id, expiration, Retry::Attempts(0), None
2094 assert!(outbound_payments.has_pending_payments());
2096 for i in 0..timer_ticks {
2097 let duration_since_epoch = Duration::from_secs(i * 60);
2098 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2100 assert!(outbound_payments.has_pending_payments());
2101 assert!(pending_events.lock().unwrap().is_empty());
2104 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2105 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2107 assert!(!outbound_payments.has_pending_payments());
2108 assert!(!pending_events.lock().unwrap().is_empty());
2110 pending_events.lock().unwrap().pop_front(),
2111 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2113 assert!(pending_events.lock().unwrap().is_empty());
2116 outbound_payments.add_new_awaiting_invoice(
2117 payment_id, expiration, Retry::Attempts(0), None
2120 assert!(outbound_payments.has_pending_payments());
2123 outbound_payments.add_new_awaiting_invoice(
2124 payment_id, expiration, Retry::Attempts(0), None
2130 fn removes_abandoned_awaiting_invoice() {
2131 let pending_events = Mutex::new(VecDeque::new());
2132 let outbound_payments = OutboundPayments::new();
2133 let payment_id = PaymentId([0; 32]);
2134 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2136 assert!(!outbound_payments.has_pending_payments());
2138 outbound_payments.add_new_awaiting_invoice(
2139 payment_id, expiration, Retry::Attempts(0), None
2142 assert!(outbound_payments.has_pending_payments());
2144 outbound_payments.abandon_payment(
2145 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2147 assert!(!outbound_payments.has_pending_payments());
2148 assert!(!pending_events.lock().unwrap().is_empty());
2150 pending_events.lock().unwrap().pop_front(),
2151 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2153 assert!(pending_events.lock().unwrap().is_empty());
2156 #[cfg(feature = "std")]
2158 fn fails_sending_payment_for_expired_bolt12_invoice() {
2159 let logger = test_utils::TestLogger::new();
2160 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2161 let scorer = RwLock::new(test_utils::TestScorer::new());
2162 let router = test_utils::TestRouter::new(network_graph, &scorer);
2163 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2165 let pending_events = Mutex::new(VecDeque::new());
2166 let outbound_payments = OutboundPayments::new();
2167 let payment_id = PaymentId([0; 32]);
2168 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2171 outbound_payments.add_new_awaiting_invoice(
2172 payment_id, expiration, Retry::Attempts(0), None
2175 assert!(outbound_payments.has_pending_payments());
2177 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2178 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2181 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2183 .sign(payer_sign).unwrap()
2184 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2186 .sign(recipient_sign).unwrap();
2189 outbound_payments.send_payment_for_bolt12_invoice(
2190 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2191 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2195 assert!(!outbound_payments.has_pending_payments());
2197 let payment_hash = invoice.payment_hash();
2198 let reason = Some(PaymentFailureReason::PaymentExpired);
2200 assert!(!pending_events.lock().unwrap().is_empty());
2202 pending_events.lock().unwrap().pop_front(),
2203 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2205 assert!(pending_events.lock().unwrap().is_empty());
2209 fn fails_finding_route_for_bolt12_invoice() {
2210 let logger = test_utils::TestLogger::new();
2211 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2212 let scorer = RwLock::new(test_utils::TestScorer::new());
2213 let router = test_utils::TestRouter::new(network_graph, &scorer);
2214 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2216 let pending_events = Mutex::new(VecDeque::new());
2217 let outbound_payments = OutboundPayments::new();
2218 let payment_id = PaymentId([0; 32]);
2219 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2221 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2224 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2226 .sign(payer_sign).unwrap()
2227 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2229 .sign(recipient_sign).unwrap();
2232 outbound_payments.add_new_awaiting_invoice(
2233 payment_id, expiration, Retry::Attempts(0),
2234 Some(invoice.amount_msats() / 100 + 50_000)
2237 assert!(outbound_payments.has_pending_payments());
2239 router.expect_find_route(
2240 RouteParameters::from_payment_params_and_value(
2241 PaymentParameters::from_bolt12_invoice(&invoice),
2242 invoice.amount_msats(),
2244 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2248 outbound_payments.send_payment_for_bolt12_invoice(
2249 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2250 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2254 assert!(!outbound_payments.has_pending_payments());
2256 let payment_hash = invoice.payment_hash();
2257 let reason = Some(PaymentFailureReason::RouteNotFound);
2259 assert!(!pending_events.lock().unwrap().is_empty());
2261 pending_events.lock().unwrap().pop_front(),
2262 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2264 assert!(pending_events.lock().unwrap().is_empty());
2268 fn fails_paying_for_bolt12_invoice() {
2269 let logger = test_utils::TestLogger::new();
2270 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2271 let scorer = RwLock::new(test_utils::TestScorer::new());
2272 let router = test_utils::TestRouter::new(network_graph, &scorer);
2273 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2275 let pending_events = Mutex::new(VecDeque::new());
2276 let outbound_payments = OutboundPayments::new();
2277 let payment_id = PaymentId([0; 32]);
2278 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2280 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2283 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2285 .sign(payer_sign).unwrap()
2286 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2288 .sign(recipient_sign).unwrap();
2291 outbound_payments.add_new_awaiting_invoice(
2292 payment_id, expiration, Retry::Attempts(0),
2293 Some(invoice.amount_msats() / 100 + 50_000)
2296 assert!(outbound_payments.has_pending_payments());
2298 let route_params = RouteParameters::from_payment_params_and_value(
2299 PaymentParameters::from_bolt12_invoice(&invoice),
2300 invoice.amount_msats(),
2302 router.expect_find_route(
2303 route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2307 outbound_payments.send_payment_for_bolt12_invoice(
2308 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2309 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2313 assert!(!outbound_payments.has_pending_payments());
2315 let payment_hash = invoice.payment_hash();
2316 let reason = Some(PaymentFailureReason::UnexpectedError);
2318 assert!(!pending_events.lock().unwrap().is_empty());
2320 pending_events.lock().unwrap().pop_front(),
2321 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2323 assert!(pending_events.lock().unwrap().is_empty());
2327 fn sends_payment_for_bolt12_invoice() {
2328 let logger = test_utils::TestLogger::new();
2329 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2330 let scorer = RwLock::new(test_utils::TestScorer::new());
2331 let router = test_utils::TestRouter::new(network_graph, &scorer);
2332 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2334 let pending_events = Mutex::new(VecDeque::new());
2335 let outbound_payments = OutboundPayments::new();
2336 let payment_id = PaymentId([0; 32]);
2337 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2339 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2342 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2344 .sign(payer_sign).unwrap()
2345 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2347 .sign(recipient_sign).unwrap();
2349 let route_params = RouteParameters {
2350 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2351 final_value_msat: invoice.amount_msats(),
2352 max_total_routing_fee_msat: Some(1234),
2354 router.expect_find_route(
2355 route_params.clone(),
2361 pubkey: recipient_pubkey(),
2362 node_features: NodeFeatures::empty(),
2363 short_channel_id: 42,
2364 channel_features: ChannelFeatures::empty(),
2365 fee_msat: invoice.amount_msats(),
2366 cltv_expiry_delta: 0,
2367 maybe_announced_channel: true,
2373 route_params: Some(route_params),
2377 assert!(!outbound_payments.has_pending_payments());
2379 outbound_payments.send_payment_for_bolt12_invoice(
2380 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2381 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2383 Err(Bolt12PaymentError::UnexpectedInvoice),
2385 assert!(!outbound_payments.has_pending_payments());
2386 assert!(pending_events.lock().unwrap().is_empty());
2389 outbound_payments.add_new_awaiting_invoice(
2390 payment_id, expiration, Retry::Attempts(0), Some(1234)
2393 assert!(outbound_payments.has_pending_payments());
2396 outbound_payments.send_payment_for_bolt12_invoice(
2397 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2398 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2402 assert!(outbound_payments.has_pending_payments());
2403 assert!(pending_events.lock().unwrap().is_empty());
2406 outbound_payments.send_payment_for_bolt12_invoice(
2407 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2408 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2410 Err(Bolt12PaymentError::DuplicateInvoice),
2412 assert!(outbound_payments.has_pending_payments());
2413 assert!(pending_events.lock().unwrap().is_empty());