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).to_byte_array());
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).to_byte_array());
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 for (i, hop) in path.hops.iter().enumerate() {
1341 // Check for duplicate channel_id in the remaining hops of the path
1342 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1343 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1344 continue 'path_check;
1347 total_value += path.final_value_msat();
1348 path_errs.push(Ok(()));
1350 if path_errs.iter().any(|e| e.is_err()) {
1351 return Err(PaymentSendFailure::PathParameterError(path_errs));
1353 if let Some(amt_msat) = recv_value_msat {
1354 total_value = amt_msat;
1357 let cur_height = best_block_height + 1;
1358 let mut results = Vec::new();
1359 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1360 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1361 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1362 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1363 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1367 Err(APIError::MonitorUpdateInProgress) => {
1368 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1369 // considered "in flight" and we shouldn't remove it from the
1370 // PendingOutboundPayment set.
1373 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1374 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1375 let removed = payment.remove(&session_priv_bytes, Some(path));
1376 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1378 debug_assert!(false, "This can't happen as the payment was added by callers");
1379 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1383 results.push(path_res);
1385 let mut has_ok = false;
1386 let mut has_err = false;
1387 let mut has_unsent = false;
1388 let mut total_ok_fees_msat = 0;
1389 let mut total_ok_amt_sent_msat = 0;
1390 for (res, path) in results.iter().zip(route.paths.iter()) {
1393 total_ok_fees_msat += path.fee_msat();
1394 total_ok_amt_sent_msat += path.final_value_msat();
1396 if res.is_err() { has_err = true; }
1397 if let &Err(APIError::MonitorUpdateInProgress) = res {
1398 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1402 total_ok_fees_msat += path.fee_msat();
1403 total_ok_amt_sent_msat += path.final_value_msat();
1404 } else if res.is_err() {
1408 if has_err && has_ok {
1409 Err(PaymentSendFailure::PartialFailure {
1412 failed_paths_retry: if has_unsent {
1413 if let Some(route_params) = &route.route_params {
1414 let mut route_params = route_params.clone();
1415 // We calculate the leftover fee budget we're allowed to spend by
1416 // subtracting the used fee from the total fee budget.
1417 route_params.max_total_routing_fee_msat = route_params
1418 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1420 // We calculate the remaining target amount by subtracting the succeded
1422 route_params.final_value_msat = route_params.final_value_msat
1423 .saturating_sub(total_ok_amt_sent_msat);
1429 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1436 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1437 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1438 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1439 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1440 send_payment_along_path: F
1441 ) -> Result<(), PaymentSendFailure>
1443 NS::Target: NodeSigner,
1444 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1446 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1447 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1448 &send_payment_along_path)
1449 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1452 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1453 // map as the payment is free to be resent.
1454 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1455 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1456 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1457 debug_assert!(removed, "We should always have a pending payment to remove here");
1461 pub(super) fn claim_htlc<L: Deref>(
1462 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1463 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1464 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1466 ) where L::Target: Logger {
1467 let mut session_priv_bytes = [0; 32];
1468 session_priv_bytes.copy_from_slice(&session_priv[..]);
1469 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1470 let mut pending_events = pending_events.lock().unwrap();
1471 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1472 if !payment.get().is_fulfilled() {
1473 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1474 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1475 let fee_paid_msat = payment.get().get_pending_fee_msat();
1476 pending_events.push_back((events::Event::PaymentSent {
1477 payment_id: Some(payment_id),
1481 }, Some(ev_completion_action.clone())));
1482 payment.get_mut().mark_fulfilled();
1486 // We currently immediately remove HTLCs which were fulfilled on-chain.
1487 // This could potentially lead to removing a pending payment too early,
1488 // with a reorg of one block causing us to re-add the fulfilled payment on
1490 // TODO: We should have a second monitor event that informs us of payments
1491 // irrevocably fulfilled.
1492 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1493 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1494 pending_events.push_back((events::Event::PaymentPathSuccessful {
1498 }, Some(ev_completion_action)));
1502 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1506 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1507 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1509 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1510 let mut pending_events = pending_events.lock().unwrap();
1511 for source in sources {
1512 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1513 let mut session_priv_bytes = [0; 32];
1514 session_priv_bytes.copy_from_slice(&session_priv[..]);
1515 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1516 assert!(payment.get().is_fulfilled());
1517 if payment.get_mut().remove(&session_priv_bytes, None) {
1518 let payment_hash = payment.get().payment_hash();
1519 debug_assert!(payment_hash.is_some());
1520 pending_events.push_back((events::Event::PaymentPathSuccessful {
1531 pub(super) fn remove_stale_payments(
1532 &self, duration_since_epoch: Duration,
1533 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1535 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1536 let mut pending_events = pending_events.lock().unwrap();
1537 pending_outbound_payments.retain(|payment_id, payment| match payment {
1538 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1539 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1540 // this could race the user making a duplicate send_payment call and our idempotency
1541 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1542 // removal. This should be more than sufficient to ensure the idempotency of any
1543 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1545 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1546 let mut no_remaining_entries = session_privs.is_empty();
1547 if no_remaining_entries {
1548 for (ev, _) in pending_events.iter() {
1550 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1551 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1552 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1553 if payment_id == ev_payment_id {
1554 no_remaining_entries = false;
1562 if no_remaining_entries {
1563 *timer_ticks_without_htlcs += 1;
1564 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1566 *timer_ticks_without_htlcs = 0;
1570 PendingOutboundPayment::AwaitingInvoice { expiration, .. } => {
1571 let is_stale = match expiration {
1572 StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
1573 *absolute_expiry <= duration_since_epoch
1575 StaleExpiration::TimerTicks(timer_ticks_remaining) => {
1576 if *timer_ticks_remaining > 0 {
1577 *timer_ticks_remaining -= 1;
1585 pending_events.push_back(
1586 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1597 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1598 pub(super) fn fail_htlc<L: Deref>(
1599 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1600 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1601 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1602 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1603 ) -> bool where L::Target: Logger {
1605 let DecodedOnionFailure {
1606 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1608 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1610 let DecodedOnionFailure { network_update, short_channel_id, payment_failed_permanently } =
1611 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1613 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1614 let mut session_priv_bytes = [0; 32];
1615 session_priv_bytes.copy_from_slice(&session_priv[..]);
1616 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1618 // If any payments already need retry, there's no need to generate a redundant
1619 // `PendingHTLCsForwardable`.
1620 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1621 let mut awaiting_retry = false;
1622 if pmt.is_auto_retryable_now() {
1623 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1624 if pending_amt_msat < total_msat {
1625 awaiting_retry = true;
1632 let mut full_failure_ev = None;
1633 let mut pending_retry_ev = false;
1634 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1635 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1636 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1639 if payment.get().is_fulfilled() {
1640 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1643 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1644 if let Some(scid) = short_channel_id {
1645 // TODO: If we decided to blame ourselves (or one of our channels) in
1646 // process_onion_failure we should close that channel as it implies our
1647 // next-hop is needlessly blaming us!
1648 payment.get_mut().insert_previously_failed_scid(scid);
1651 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1652 let reason = if payment_failed_permanently {
1653 PaymentFailureReason::RecipientRejected
1655 PaymentFailureReason::RetriesExhausted
1657 payment.get_mut().mark_abandoned(reason);
1658 is_retryable_now = false;
1660 if payment.get().remaining_parts() == 0 {
1661 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1662 if !payment_is_probe {
1663 full_failure_ev = Some(events::Event::PaymentFailed {
1664 payment_id: *payment_id,
1665 payment_hash: *payment_hash,
1674 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1677 core::mem::drop(outbounds);
1678 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1680 let path_failure = {
1681 if payment_is_probe {
1682 if payment_failed_permanently {
1683 events::Event::ProbeSuccessful {
1684 payment_id: *payment_id,
1685 payment_hash: payment_hash.clone(),
1689 events::Event::ProbeFailed {
1690 payment_id: *payment_id,
1691 payment_hash: payment_hash.clone(),
1697 // If we miss abandoning the payment above, we *must* generate an event here or else the
1698 // payment will sit in our outbounds forever.
1699 if attempts_remaining && !already_awaiting_retry {
1700 debug_assert!(full_failure_ev.is_none());
1701 pending_retry_ev = true;
1703 events::Event::PaymentPathFailed {
1704 payment_id: Some(*payment_id),
1705 payment_hash: payment_hash.clone(),
1706 payment_failed_permanently,
1707 failure: events::PathFailure::OnPath { network_update },
1711 error_code: onion_error_code,
1713 error_data: onion_error_data
1717 let mut pending_events = pending_events.lock().unwrap();
1718 pending_events.push_back((path_failure, None));
1719 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1723 pub(super) fn abandon_payment(
1724 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1725 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1727 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1728 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1729 payment.get_mut().mark_abandoned(reason);
1730 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1731 if payment.get().remaining_parts() == 0 {
1732 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1734 payment_hash: *payment_hash,
1739 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1740 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1749 pub fn has_pending_payments(&self) -> bool {
1750 !self.pending_outbound_payments.lock().unwrap().is_empty()
1754 pub fn clear_pending_payments(&self) {
1755 self.pending_outbound_payments.lock().unwrap().clear()
1759 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1761 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1762 probing_cookie_secret: [u8; 32]) -> bool
1764 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1765 target_payment_hash == *payment_hash
1768 /// Returns the 'probing cookie' for the given [`PaymentId`].
1769 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1770 let mut preimage = [0u8; 64];
1771 preimage[..32].copy_from_slice(&probing_cookie_secret);
1772 preimage[32..].copy_from_slice(&payment_id.0);
1773 PaymentHash(Sha256::hash(&preimage).to_byte_array())
1776 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1778 (0, session_privs, required),
1781 (0, session_privs, required),
1782 (1, payment_hash, option),
1783 (3, timer_ticks_without_htlcs, (default_value, 0)),
1786 (0, session_privs, required),
1787 (1, pending_fee_msat, option),
1788 (2, payment_hash, required),
1789 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1790 // never see it - `payment_params` was added here after the field was added/required.
1791 (3, payment_params, (option: ReadableArgs, 0)),
1792 (4, payment_secret, option),
1793 (5, keysend_preimage, option),
1794 (6, total_msat, required),
1795 (7, payment_metadata, option),
1796 (8, pending_amt_msat, required),
1797 (9, custom_tlvs, optional_vec),
1798 (10, starting_block_height, required),
1799 (11, remaining_max_total_routing_fee_msat, option),
1800 (not_written, retry_strategy, (static_value, None)),
1801 (not_written, attempts, (static_value, PaymentAttempts::new())),
1804 (0, session_privs, required),
1805 (1, reason, option),
1806 (2, payment_hash, required),
1808 (5, AwaitingInvoice) => {
1809 (0, expiration, required),
1810 (2, retry_strategy, required),
1811 (4, max_total_routing_fee_msat, option),
1813 (7, InvoiceReceived) => {
1814 (0, payment_hash, required),
1815 (2, retry_strategy, required),
1816 (4, max_total_routing_fee_msat, option),
1822 use bitcoin::network::constants::Network;
1823 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1825 use core::time::Duration;
1827 use crate::events::{Event, PathFailure, PaymentFailureReason};
1828 use crate::ln::PaymentHash;
1829 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1830 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1831 use crate::ln::msgs::{ErrorAction, LightningError};
1832 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure, StaleExpiration};
1833 #[cfg(feature = "std")]
1834 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1835 use crate::offers::offer::OfferBuilder;
1836 use crate::offers::test_utils::*;
1837 use crate::routing::gossip::NetworkGraph;
1838 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1839 use crate::sync::{Arc, Mutex, RwLock};
1840 use crate::util::errors::APIError;
1841 use crate::util::test_utils;
1843 use alloc::collections::VecDeque;
1846 fn test_recipient_onion_fields_with_custom_tlvs() {
1847 let onion_fields = RecipientOnionFields::spontaneous_empty();
1849 let bad_type_range_tlvs = vec![
1853 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1855 let keysend_tlv = vec![
1856 (5482373484, vec![42; 32]),
1858 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1860 let good_tlvs = vec![
1861 ((1 << 16) + 1, vec![42]),
1862 ((1 << 16) + 3, vec![42; 32]),
1864 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1868 #[cfg(feature = "std")]
1869 fn fails_paying_after_expiration() {
1870 do_fails_paying_after_expiration(false);
1871 do_fails_paying_after_expiration(true);
1873 #[cfg(feature = "std")]
1874 fn do_fails_paying_after_expiration(on_retry: bool) {
1875 let outbound_payments = OutboundPayments::new();
1876 let logger = test_utils::TestLogger::new();
1877 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1878 let scorer = RwLock::new(test_utils::TestScorer::new());
1879 let router = test_utils::TestRouter::new(network_graph, &scorer);
1880 let secp_ctx = Secp256k1::new();
1881 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1883 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1884 let payment_params = PaymentParameters::from_node_id(
1885 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1887 ).with_expiry_time(past_expiry_time);
1888 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1889 let pending_events = Mutex::new(VecDeque::new());
1891 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1892 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1893 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1894 &&keys_manager, 0).unwrap();
1895 outbound_payments.find_route_and_send_payment(
1896 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1897 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1899 let events = pending_events.lock().unwrap();
1900 assert_eq!(events.len(), 1);
1901 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1902 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1903 } else { panic!("Unexpected event"); }
1905 let err = outbound_payments.send_payment(
1906 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1907 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1908 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1909 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1914 fn find_route_error() {
1915 do_find_route_error(false);
1916 do_find_route_error(true);
1918 fn do_find_route_error(on_retry: bool) {
1919 let outbound_payments = OutboundPayments::new();
1920 let logger = test_utils::TestLogger::new();
1921 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1922 let scorer = RwLock::new(test_utils::TestScorer::new());
1923 let router = test_utils::TestRouter::new(network_graph, &scorer);
1924 let secp_ctx = Secp256k1::new();
1925 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1927 let payment_params = PaymentParameters::from_node_id(
1928 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1929 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1930 router.expect_find_route(route_params.clone(),
1931 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1933 let pending_events = Mutex::new(VecDeque::new());
1935 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1936 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1937 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1938 &&keys_manager, 0).unwrap();
1939 outbound_payments.find_route_and_send_payment(
1940 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1941 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1943 let events = pending_events.lock().unwrap();
1944 assert_eq!(events.len(), 1);
1945 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1947 let err = outbound_payments.send_payment(
1948 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1949 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1950 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1951 if let RetryableSendFailure::RouteNotFound = err {
1952 } else { panic!("Unexpected error"); }
1957 fn initial_send_payment_path_failed_evs() {
1958 let outbound_payments = OutboundPayments::new();
1959 let logger = test_utils::TestLogger::new();
1960 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1961 let scorer = RwLock::new(test_utils::TestScorer::new());
1962 let router = test_utils::TestRouter::new(network_graph, &scorer);
1963 let secp_ctx = Secp256k1::new();
1964 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1966 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1967 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1968 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1969 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1970 let failed_scid = 42;
1972 paths: vec![Path { hops: vec![RouteHop {
1973 pubkey: receiver_pk,
1974 node_features: NodeFeatures::empty(),
1975 short_channel_id: failed_scid,
1976 channel_features: ChannelFeatures::empty(),
1978 cltv_expiry_delta: 0,
1979 maybe_announced_channel: true,
1980 }], blinded_tail: None }],
1981 route_params: Some(route_params.clone()),
1983 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1984 let mut route_params_w_failed_scid = route_params.clone();
1985 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1986 let mut route_w_failed_scid = route.clone();
1987 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
1988 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
1989 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1990 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1992 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1993 // PaymentPathFailed event.
1994 let pending_events = Mutex::new(VecDeque::new());
1995 outbound_payments.send_payment(
1996 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1997 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1998 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1999 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2000 let mut events = pending_events.lock().unwrap();
2001 assert_eq!(events.len(), 2);
2002 if let Event::PaymentPathFailed {
2004 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2006 assert_eq!(short_channel_id, Some(failed_scid));
2007 } else { panic!("Unexpected event"); }
2008 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2010 core::mem::drop(events);
2012 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
2013 outbound_payments.send_payment(
2014 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2015 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2016 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2017 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2018 assert_eq!(pending_events.lock().unwrap().len(), 0);
2020 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
2021 outbound_payments.send_payment(
2022 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2023 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2024 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2025 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2026 let events = pending_events.lock().unwrap();
2027 assert_eq!(events.len(), 2);
2028 if let Event::PaymentPathFailed {
2030 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2032 assert_eq!(short_channel_id, None);
2033 } else { panic!("Unexpected event"); }
2034 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2038 fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2039 let pending_events = Mutex::new(VecDeque::new());
2040 let outbound_payments = OutboundPayments::new();
2041 let payment_id = PaymentId([0; 32]);
2042 let absolute_expiry = 100;
2043 let tick_interval = 10;
2044 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2046 assert!(!outbound_payments.has_pending_payments());
2048 outbound_payments.add_new_awaiting_invoice(
2049 payment_id, expiration, Retry::Attempts(0), None
2052 assert!(outbound_payments.has_pending_payments());
2054 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2055 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
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());
2062 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2063 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2065 assert!(!outbound_payments.has_pending_payments());
2066 assert!(!pending_events.lock().unwrap().is_empty());
2068 pending_events.lock().unwrap().pop_front(),
2069 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2071 assert!(pending_events.lock().unwrap().is_empty());
2074 outbound_payments.add_new_awaiting_invoice(
2075 payment_id, expiration, Retry::Attempts(0), None
2078 assert!(outbound_payments.has_pending_payments());
2081 outbound_payments.add_new_awaiting_invoice(
2082 payment_id, expiration, Retry::Attempts(0), None
2088 fn removes_stale_awaiting_invoice_using_timer_ticks() {
2089 let pending_events = Mutex::new(VecDeque::new());
2090 let outbound_payments = OutboundPayments::new();
2091 let payment_id = PaymentId([0; 32]);
2092 let timer_ticks = 3;
2093 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2095 assert!(!outbound_payments.has_pending_payments());
2097 outbound_payments.add_new_awaiting_invoice(
2098 payment_id, expiration, Retry::Attempts(0), None
2101 assert!(outbound_payments.has_pending_payments());
2103 for i in 0..timer_ticks {
2104 let duration_since_epoch = Duration::from_secs(i * 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());
2111 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2112 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2114 assert!(!outbound_payments.has_pending_payments());
2115 assert!(!pending_events.lock().unwrap().is_empty());
2117 pending_events.lock().unwrap().pop_front(),
2118 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2120 assert!(pending_events.lock().unwrap().is_empty());
2123 outbound_payments.add_new_awaiting_invoice(
2124 payment_id, expiration, Retry::Attempts(0), None
2127 assert!(outbound_payments.has_pending_payments());
2130 outbound_payments.add_new_awaiting_invoice(
2131 payment_id, expiration, Retry::Attempts(0), None
2137 fn removes_abandoned_awaiting_invoice() {
2138 let pending_events = Mutex::new(VecDeque::new());
2139 let outbound_payments = OutboundPayments::new();
2140 let payment_id = PaymentId([0; 32]);
2141 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2143 assert!(!outbound_payments.has_pending_payments());
2145 outbound_payments.add_new_awaiting_invoice(
2146 payment_id, expiration, Retry::Attempts(0), None
2149 assert!(outbound_payments.has_pending_payments());
2151 outbound_payments.abandon_payment(
2152 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2154 assert!(!outbound_payments.has_pending_payments());
2155 assert!(!pending_events.lock().unwrap().is_empty());
2157 pending_events.lock().unwrap().pop_front(),
2158 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2160 assert!(pending_events.lock().unwrap().is_empty());
2163 #[cfg(feature = "std")]
2165 fn fails_sending_payment_for_expired_bolt12_invoice() {
2166 let logger = test_utils::TestLogger::new();
2167 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2168 let scorer = RwLock::new(test_utils::TestScorer::new());
2169 let router = test_utils::TestRouter::new(network_graph, &scorer);
2170 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2172 let pending_events = Mutex::new(VecDeque::new());
2173 let outbound_payments = OutboundPayments::new();
2174 let payment_id = PaymentId([0; 32]);
2175 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2178 outbound_payments.add_new_awaiting_invoice(
2179 payment_id, expiration, Retry::Attempts(0), None
2182 assert!(outbound_payments.has_pending_payments());
2184 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2185 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2188 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2190 .sign(payer_sign).unwrap()
2191 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2193 .sign(recipient_sign).unwrap();
2196 outbound_payments.send_payment_for_bolt12_invoice(
2197 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2198 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2202 assert!(!outbound_payments.has_pending_payments());
2204 let payment_hash = invoice.payment_hash();
2205 let reason = Some(PaymentFailureReason::PaymentExpired);
2207 assert!(!pending_events.lock().unwrap().is_empty());
2209 pending_events.lock().unwrap().pop_front(),
2210 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2212 assert!(pending_events.lock().unwrap().is_empty());
2216 fn fails_finding_route_for_bolt12_invoice() {
2217 let logger = test_utils::TestLogger::new();
2218 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2219 let scorer = RwLock::new(test_utils::TestScorer::new());
2220 let router = test_utils::TestRouter::new(network_graph, &scorer);
2221 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2223 let pending_events = Mutex::new(VecDeque::new());
2224 let outbound_payments = OutboundPayments::new();
2225 let payment_id = PaymentId([0; 32]);
2226 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2228 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2231 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2233 .sign(payer_sign).unwrap()
2234 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2236 .sign(recipient_sign).unwrap();
2239 outbound_payments.add_new_awaiting_invoice(
2240 payment_id, expiration, Retry::Attempts(0),
2241 Some(invoice.amount_msats() / 100 + 50_000)
2244 assert!(outbound_payments.has_pending_payments());
2246 router.expect_find_route(
2247 RouteParameters::from_payment_params_and_value(
2248 PaymentParameters::from_bolt12_invoice(&invoice),
2249 invoice.amount_msats(),
2251 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2255 outbound_payments.send_payment_for_bolt12_invoice(
2256 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2257 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2261 assert!(!outbound_payments.has_pending_payments());
2263 let payment_hash = invoice.payment_hash();
2264 let reason = Some(PaymentFailureReason::RouteNotFound);
2266 assert!(!pending_events.lock().unwrap().is_empty());
2268 pending_events.lock().unwrap().pop_front(),
2269 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2271 assert!(pending_events.lock().unwrap().is_empty());
2275 fn fails_paying_for_bolt12_invoice() {
2276 let logger = test_utils::TestLogger::new();
2277 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2278 let scorer = RwLock::new(test_utils::TestScorer::new());
2279 let router = test_utils::TestRouter::new(network_graph, &scorer);
2280 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2282 let pending_events = Mutex::new(VecDeque::new());
2283 let outbound_payments = OutboundPayments::new();
2284 let payment_id = PaymentId([0; 32]);
2285 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2287 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2290 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2292 .sign(payer_sign).unwrap()
2293 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2295 .sign(recipient_sign).unwrap();
2298 outbound_payments.add_new_awaiting_invoice(
2299 payment_id, expiration, Retry::Attempts(0),
2300 Some(invoice.amount_msats() / 100 + 50_000)
2303 assert!(outbound_payments.has_pending_payments());
2305 let route_params = RouteParameters::from_payment_params_and_value(
2306 PaymentParameters::from_bolt12_invoice(&invoice),
2307 invoice.amount_msats(),
2309 router.expect_find_route(
2310 route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2314 outbound_payments.send_payment_for_bolt12_invoice(
2315 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2316 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2320 assert!(!outbound_payments.has_pending_payments());
2322 let payment_hash = invoice.payment_hash();
2323 let reason = Some(PaymentFailureReason::UnexpectedError);
2325 assert!(!pending_events.lock().unwrap().is_empty());
2327 pending_events.lock().unwrap().pop_front(),
2328 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2330 assert!(pending_events.lock().unwrap().is_empty());
2334 fn sends_payment_for_bolt12_invoice() {
2335 let logger = test_utils::TestLogger::new();
2336 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2337 let scorer = RwLock::new(test_utils::TestScorer::new());
2338 let router = test_utils::TestRouter::new(network_graph, &scorer);
2339 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2341 let pending_events = Mutex::new(VecDeque::new());
2342 let outbound_payments = OutboundPayments::new();
2343 let payment_id = PaymentId([0; 32]);
2344 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2346 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2349 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2351 .sign(payer_sign).unwrap()
2352 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2354 .sign(recipient_sign).unwrap();
2356 let route_params = RouteParameters {
2357 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2358 final_value_msat: invoice.amount_msats(),
2359 max_total_routing_fee_msat: Some(1234),
2361 router.expect_find_route(
2362 route_params.clone(),
2368 pubkey: recipient_pubkey(),
2369 node_features: NodeFeatures::empty(),
2370 short_channel_id: 42,
2371 channel_features: ChannelFeatures::empty(),
2372 fee_msat: invoice.amount_msats(),
2373 cltv_expiry_delta: 0,
2374 maybe_announced_channel: true,
2380 route_params: Some(route_params),
2384 assert!(!outbound_payments.has_pending_payments());
2386 outbound_payments.send_payment_for_bolt12_invoice(
2387 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2388 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2390 Err(Bolt12PaymentError::UnexpectedInvoice),
2392 assert!(!outbound_payments.has_pending_payments());
2393 assert!(pending_events.lock().unwrap().is_empty());
2396 outbound_payments.add_new_awaiting_invoice(
2397 payment_id, expiration, Retry::Attempts(0), Some(1234)
2400 assert!(outbound_payments.has_pending_payments());
2403 outbound_payments.send_payment_for_bolt12_invoice(
2404 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2405 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2409 assert!(outbound_payments.has_pending_payments());
2410 assert!(pending_events.lock().unwrap().is_empty());
2413 outbound_payments.send_payment_for_bolt12_invoice(
2414 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2415 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2417 Err(Bolt12PaymentError::DuplicateInvoice),
2419 assert!(outbound_payments.has_pending_payments());
2420 assert!(pending_events.lock().unwrap().is_empty());