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};
33 use crate::prelude::*;
34 use crate::sync::Mutex;
36 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
37 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
39 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
40 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
42 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until an invoice request without
43 /// a response is timed out.
45 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
46 const INVOICE_REQUEST_TIMEOUT_TICKS: u8 = 3;
48 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
49 /// and later, also stores information for retrying the payment.
50 pub(crate) enum PendingOutboundPayment {
52 session_privs: HashSet<[u8; 32]>,
55 timer_ticks_without_response: u8,
56 retry_strategy: Retry,
59 payment_hash: PaymentHash,
60 retry_strategy: Retry,
63 retry_strategy: Option<Retry>,
64 attempts: PaymentAttempts,
65 payment_params: Option<PaymentParameters>,
66 session_privs: HashSet<[u8; 32]>,
67 payment_hash: PaymentHash,
68 payment_secret: Option<PaymentSecret>,
69 payment_metadata: Option<Vec<u8>>,
70 keysend_preimage: Option<PaymentPreimage>,
71 custom_tlvs: Vec<(u64, Vec<u8>)>,
72 pending_amt_msat: u64,
73 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
74 pending_fee_msat: Option<u64>,
75 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
77 /// Our best known block height at the time this payment was initiated.
78 starting_block_height: u32,
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 { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
214 let path = path.expect("Fulfilling a payment should always come with a path");
215 *pending_amt_msat -= path.final_value_msat();
216 if let Some(fee_msat) = pending_fee_msat.as_mut() {
217 *fee_msat -= path.fee_msat();
224 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
225 let insert_res = match self {
226 PendingOutboundPayment::Legacy { session_privs } |
227 PendingOutboundPayment::Retryable { session_privs, .. } => {
228 session_privs.insert(session_priv)
230 PendingOutboundPayment::AwaitingInvoice { .. } |
231 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
232 PendingOutboundPayment::Fulfilled { .. } => false,
233 PendingOutboundPayment::Abandoned { .. } => false,
236 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
237 *pending_amt_msat += path.final_value_msat();
238 if let Some(fee_msat) = pending_fee_msat.as_mut() {
239 *fee_msat += path.fee_msat();
246 pub(super) fn remaining_parts(&self) -> usize {
248 PendingOutboundPayment::Legacy { session_privs } |
249 PendingOutboundPayment::Retryable { session_privs, .. } |
250 PendingOutboundPayment::Fulfilled { session_privs, .. } |
251 PendingOutboundPayment::Abandoned { session_privs, .. } => {
254 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
255 PendingOutboundPayment::InvoiceReceived { .. } => 0,
260 /// Strategies available to retry payment path failures.
261 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
263 /// Max number of attempts to retry payment.
265 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
266 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
267 /// were retried along a route from a single call to [`Router::find_route_with_id`].
269 #[cfg(not(feature = "no-std"))]
270 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
271 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
273 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
274 Timeout(core::time::Duration),
277 #[cfg(feature = "no-std")]
278 impl_writeable_tlv_based_enum!(Retry,
283 #[cfg(not(feature = "no-std"))]
284 impl_writeable_tlv_based_enum!(Retry,
291 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
292 match (self, attempts) {
293 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
294 max_retry_count > count
296 #[cfg(all(not(feature = "no-std"), not(test)))]
297 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
298 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
299 #[cfg(all(not(feature = "no-std"), test))]
300 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
301 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
306 #[cfg(feature = "std")]
307 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
308 if let Some(expiry_time) = route_params.payment_params.expiry_time {
309 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
310 return elapsed > core::time::Duration::from_secs(expiry_time)
316 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
318 /// Storing minimal payment attempts information required for determining if a outbound payment can
320 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
321 /// This count will be incremented only after the result of the attempt is known. When it's 0,
322 /// it means the result of the first attempt is not known yet.
323 pub(crate) count: u32,
324 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
325 #[cfg(not(feature = "no-std"))]
326 first_attempted_at: T,
327 #[cfg(feature = "no-std")]
328 phantom: core::marker::PhantomData<T>,
332 #[cfg(not(any(feature = "no-std", test)))]
333 type ConfiguredTime = crate::util::time::MonotonicTime;
334 #[cfg(feature = "no-std")]
335 type ConfiguredTime = crate::util::time::Eternity;
336 #[cfg(all(not(feature = "no-std"), test))]
337 type ConfiguredTime = SinceEpoch;
339 impl<T: Time> PaymentAttemptsUsingTime<T> {
340 pub(crate) fn new() -> Self {
341 PaymentAttemptsUsingTime {
343 #[cfg(not(feature = "no-std"))]
344 first_attempted_at: T::now(),
345 #[cfg(feature = "no-std")]
346 phantom: core::marker::PhantomData,
351 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
352 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
353 #[cfg(feature = "no-std")]
354 return write!(f, "attempts: {}", self.count);
355 #[cfg(not(feature = "no-std"))]
358 "attempts: {}, duration: {}s",
360 T::now().duration_since(self.first_attempted_at).as_secs()
365 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
366 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
368 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
369 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
370 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
371 #[derive(Clone, Debug, PartialEq, Eq)]
372 pub enum RetryableSendFailure {
373 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
374 /// that this error is *not* caused by [`Retry::Timeout`].
376 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
378 /// We were unable to find a route to the destination.
380 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
381 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
383 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
384 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
385 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
389 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
390 /// of several states. This enum is returned as the Err() type describing which state the payment
391 /// is in, see the description of individual enum states for more.
393 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
394 #[derive(Clone, Debug, PartialEq, Eq)]
395 pub enum PaymentSendFailure {
396 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
397 /// send the payment at all.
399 /// You can freely resend the payment in full (with the parameter error fixed).
401 /// Because the payment failed outright, no payment tracking is done and no
402 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
404 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
405 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
406 ParameterError(APIError),
407 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
408 /// from attempting to send the payment at all.
410 /// You can freely resend the payment in full (with the parameter error fixed).
412 /// Because the payment failed outright, no payment tracking is done and no
413 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
415 /// The results here are ordered the same as the paths in the route object which was passed to
418 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
419 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
420 PathParameterError(Vec<Result<(), APIError>>),
421 /// All paths which were attempted failed to send, with no channel state change taking place.
422 /// You can freely resend the payment in full (though you probably want to do so over different
423 /// paths than the ones selected).
425 /// Because the payment failed outright, no payment tracking is done and no
426 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
428 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
429 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
430 AllFailedResendSafe(Vec<APIError>),
431 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
432 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
434 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
435 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
436 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
438 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
439 /// some paths have irrevocably committed to the HTLC.
441 /// The results here are ordered the same as the paths in the route object that was passed to
444 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
445 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
447 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
449 /// The errors themselves, in the same order as the paths from the route.
450 results: Vec<Result<(), APIError>>,
451 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
452 /// contain a [`RouteParameters`] object for the failing paths.
453 failed_paths_retry: Option<RouteParameters>,
454 /// The payment id for the payment, which is now at least partially pending.
455 payment_id: PaymentId,
459 /// An error when attempting to pay a BOLT 12 invoice.
460 #[derive(Clone, Debug, PartialEq, Eq)]
461 pub(super) enum Bolt12PaymentError {
462 /// The invoice was not requested.
464 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
468 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
469 /// [`Event::ProbeFailed`].
471 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
472 #[derive(Clone, Debug, PartialEq, Eq)]
473 pub enum ProbeSendFailure {
474 /// We were unable to find a route to the destination.
476 /// We failed to send the payment probes.
477 SendingFailed(PaymentSendFailure),
480 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
482 /// This should generally be constructed with data communicated to us from the recipient (via a
483 /// BOLT11 or BOLT12 invoice).
484 #[derive(Clone, Debug, PartialEq, Eq)]
485 pub struct RecipientOnionFields {
486 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
487 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
488 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
491 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
492 /// multi-path payments require a recipient-provided secret.
494 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
495 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
496 /// recipient will not reject it.
497 pub payment_secret: Option<PaymentSecret>,
498 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
499 /// arbitrary length. This gives recipients substantially more flexibility to receive
502 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
503 /// scheme to authenticate received payments against expected payments and invoices, this field
504 /// is not used in LDK for received payments, and can be used to store arbitrary data in
505 /// invoices which will be received with the payment.
507 /// Note that this field was added to the lightning specification more recently than
508 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
509 /// may not be supported as universally.
510 pub payment_metadata: Option<Vec<u8>>,
511 /// See [`Self::custom_tlvs`] for more info.
512 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
515 impl_writeable_tlv_based!(RecipientOnionFields, {
516 (0, payment_secret, option),
517 (1, custom_tlvs, optional_vec),
518 (2, payment_metadata, option),
521 impl RecipientOnionFields {
522 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
523 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
524 /// but do not require or provide any further data.
525 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
526 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
529 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
530 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
531 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
532 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
533 /// instead want to use [`RecipientOnionFields::secret_only`].
535 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
536 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
537 pub fn spontaneous_empty() -> Self {
538 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
541 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
542 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
543 /// respectively. TLV type numbers must be unique and within the range
544 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
546 /// This method will also error for types in the experimental range which have been
547 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
549 /// See [`Self::custom_tlvs`] for more info.
550 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
551 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
552 let mut prev_type = None;
553 for (typ, _) in custom_tlvs.iter() {
554 if *typ < 1 << 16 { return Err(()); }
555 if *typ == 5482373484 { return Err(()); } // keysend
557 Some(prev) if prev >= *typ => return Err(()),
560 prev_type = Some(*typ);
562 self.custom_tlvs = custom_tlvs;
566 /// Gets the custom TLVs that will be sent or have been received.
568 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
569 /// additional flexibility on top of payment metadata, as while other implementations may
570 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
571 /// do not have this restriction.
573 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
574 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
575 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
576 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
580 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
581 /// have to make sure that some fields match exactly across the parts. For those that aren't
582 /// required to match, if they don't match we should remove them so as to not expose data
583 /// that's dependent on the HTLC receive order to users.
585 /// Here we implement this, first checking compatibility then mutating two objects and then
586 /// dropping any remaining non-matching fields from both.
587 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
588 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
589 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
591 let tlvs = &mut self.custom_tlvs;
592 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
594 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
595 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
596 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
598 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
599 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
605 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
606 pub(super) struct SendAlongPathArgs<'a> {
608 pub payment_hash: &'a PaymentHash,
609 pub recipient_onion: RecipientOnionFields,
610 pub total_value: u64,
612 pub payment_id: PaymentId,
613 pub keysend_preimage: &'a Option<PaymentPreimage>,
614 pub session_priv_bytes: [u8; 32],
617 pub(super) struct OutboundPayments {
618 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
619 pub(super) retry_lock: Mutex<()>,
622 impl OutboundPayments {
623 pub(super) fn new() -> Self {
625 pending_outbound_payments: Mutex::new(HashMap::new()),
626 retry_lock: Mutex::new(()),
630 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
631 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
632 retry_strategy: Retry, route_params: RouteParameters, router: &R,
633 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
634 node_signer: &NS, best_block_height: u32, logger: &L,
635 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
636 ) -> Result<(), RetryableSendFailure>
639 ES::Target: EntropySource,
640 NS::Target: NodeSigner,
642 IH: Fn() -> InFlightHtlcs,
643 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
645 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
646 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
647 best_block_height, logger, pending_events, &send_payment_along_path)
650 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
651 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
652 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
653 send_payment_along_path: F
654 ) -> Result<(), PaymentSendFailure>
656 ES::Target: EntropySource,
657 NS::Target: NodeSigner,
658 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
660 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)?;
661 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
662 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
663 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
666 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
667 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
668 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
669 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
670 node_signer: &NS, best_block_height: u32, logger: &L,
671 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
672 ) -> Result<PaymentHash, RetryableSendFailure>
675 ES::Target: EntropySource,
676 NS::Target: NodeSigner,
678 IH: Fn() -> InFlightHtlcs,
679 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
681 let preimage = payment_preimage
682 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
683 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
684 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
685 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
686 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
687 .map(|()| payment_hash)
690 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
691 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
692 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
693 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
694 ) -> Result<PaymentHash, PaymentSendFailure>
696 ES::Target: EntropySource,
697 NS::Target: NodeSigner,
698 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
700 let preimage = payment_preimage
701 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
702 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
703 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
704 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
706 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
707 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
709 Ok(()) => Ok(payment_hash),
711 self.remove_outbound_if_all_failed(payment_id, &e);
718 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
719 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
720 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
721 best_block_height: u32, logger: &L,
722 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
723 send_payment_along_path: SP,
724 ) -> Result<(), Bolt12PaymentError>
727 ES::Target: EntropySource,
728 NS::Target: NodeSigner,
730 IH: Fn() -> InFlightHtlcs,
731 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
733 let payment_hash = invoice.payment_hash();
734 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
735 hash_map::Entry::Occupied(entry) => match entry.get() {
736 PendingOutboundPayment::AwaitingInvoice { retry_strategy, .. } => {
737 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
739 retry_strategy: *retry_strategy,
742 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
744 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
747 let route_params = RouteParameters {
748 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
749 final_value_msat: invoice.amount_msats(),
752 self.find_route_and_send_payment(
753 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
754 entropy_source, node_signer, best_block_height, logger, pending_events,
755 &send_payment_along_path
761 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
762 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
763 best_block_height: u32,
764 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
765 send_payment_along_path: SP,
769 ES::Target: EntropySource,
770 NS::Target: NodeSigner,
771 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
772 IH: Fn() -> InFlightHtlcs,
773 FH: Fn() -> Vec<ChannelDetails>,
776 let _single_thread = self.retry_lock.lock().unwrap();
778 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
779 let mut retry_id_route_params = None;
780 for (pmt_id, pmt) in outbounds.iter_mut() {
781 if pmt.is_auto_retryable_now() {
782 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
783 if pending_amt_msat < total_msat {
784 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
785 final_value_msat: *total_msat - *pending_amt_msat,
786 payment_params: params.clone(),
790 } else { debug_assert!(false); }
793 core::mem::drop(outbounds);
794 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
795 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)
799 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
800 outbounds.retain(|pmt_id, pmt| {
801 let mut retain = true;
802 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
803 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
804 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
805 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
807 payment_hash: *payment_hash,
817 pub(super) fn needs_abandon(&self) -> bool {
818 let outbounds = self.pending_outbound_payments.lock().unwrap();
819 outbounds.iter().any(|(_, pmt)|
820 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
821 !pmt.is_awaiting_invoice())
824 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
825 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
827 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
828 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
829 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
830 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
831 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
832 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
833 node_signer: &NS, best_block_height: u32, logger: &L,
834 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
835 ) -> Result<(), RetryableSendFailure>
838 ES::Target: EntropySource,
839 NS::Target: NodeSigner,
841 IH: Fn() -> InFlightHtlcs,
842 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
844 #[cfg(feature = "std")] {
845 if has_expired(&route_params) {
846 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
847 payment_id, payment_hash);
848 return Err(RetryableSendFailure::PaymentExpired)
852 let route = router.find_route_with_id(
853 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
854 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
855 payment_hash, payment_id,
857 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
858 payment_id, payment_hash);
859 RetryableSendFailure::RouteNotFound
862 let onion_session_privs = self.add_new_pending_payment(payment_hash,
863 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
864 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
866 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
867 payment_id, payment_hash);
868 RetryableSendFailure::DuplicatePayment
871 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
872 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
873 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
874 payment_id, payment_hash, res);
875 if let Err(e) = res {
876 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);
881 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
882 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
883 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
884 node_signer: &NS, best_block_height: u32, logger: &L,
885 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
889 ES::Target: EntropySource,
890 NS::Target: NodeSigner,
892 IH: Fn() -> InFlightHtlcs,
893 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
895 #[cfg(feature = "std")] {
896 if has_expired(&route_params) {
897 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
898 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
903 let route = match router.find_route_with_id(
904 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
905 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
906 payment_hash, payment_id,
910 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
911 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
915 for path in route.paths.iter() {
916 if path.hops.len() == 0 {
917 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
918 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
923 macro_rules! abandon_with_entry {
924 ($payment: expr, $reason: expr) => {
925 $payment.get_mut().mark_abandoned($reason);
926 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
927 if $payment.get().remaining_parts() == 0 {
928 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
938 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
939 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
940 match outbounds.entry(payment_id) {
941 hash_map::Entry::Occupied(mut payment) => {
942 match payment.get() {
943 PendingOutboundPayment::Retryable {
944 total_msat, keysend_preimage, payment_secret, payment_metadata,
945 custom_tlvs, pending_amt_msat, ..
947 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
948 let retry_amt_msat = route.get_total_amount();
949 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
950 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);
951 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
955 if !payment.get().is_retryable_now() {
956 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
957 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
961 let total_msat = *total_msat;
962 let recipient_onion = RecipientOnionFields {
963 payment_secret: *payment_secret,
964 payment_metadata: payment_metadata.clone(),
965 custom_tlvs: custom_tlvs.clone(),
967 let keysend_preimage = *keysend_preimage;
969 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
970 for _ in 0..route.paths.len() {
971 onion_session_privs.push(entropy_source.get_secure_random_bytes());
974 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
975 assert!(payment.get_mut().insert(*session_priv_bytes, path));
978 payment.get_mut().increment_attempts();
980 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
982 PendingOutboundPayment::Legacy { .. } => {
983 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
986 PendingOutboundPayment::AwaitingInvoice { .. } => {
987 log_error!(logger, "Payment not yet sent");
990 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy } => {
991 let total_amount = route_params.final_value_msat;
992 let recipient_onion = RecipientOnionFields {
993 payment_secret: None,
994 payment_metadata: None,
997 let retry_strategy = Some(*retry_strategy);
998 let payment_params = Some(route_params.payment_params.clone());
999 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1000 *payment_hash, recipient_onion.clone(), None, &route,
1001 retry_strategy, payment_params, entropy_source, best_block_height
1003 *payment.into_mut() = retryable_payment;
1004 (total_amount, recipient_onion, None, onion_session_privs)
1006 PendingOutboundPayment::Fulfilled { .. } => {
1007 log_error!(logger, "Payment already completed");
1010 PendingOutboundPayment::Abandoned { .. } => {
1011 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1016 hash_map::Entry::Vacant(_) => {
1017 log_error!(logger, "Payment with ID {} not found", &payment_id);
1022 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1023 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1024 &send_payment_along_path);
1025 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1026 if let Err(e) = res {
1027 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);
1031 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1032 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1033 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1034 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1035 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1039 ES::Target: EntropySource,
1040 NS::Target: NodeSigner,
1042 IH: Fn() -> InFlightHtlcs,
1043 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1046 PaymentSendFailure::AllFailedResendSafe(errs) => {
1047 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);
1048 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);
1050 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1051 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1052 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1053 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1054 // return `Ok()` here, ignoring any retry errors.
1055 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);
1057 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1058 // This may happen if we send a payment and some paths fail, but only due to a temporary
1059 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1060 // initial HTLC-Add messages yet.
1062 PaymentSendFailure::PathParameterError(results) => {
1063 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1064 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1065 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1067 PaymentSendFailure::ParameterError(e) => {
1068 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1069 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1071 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1075 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1076 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1077 paths: Vec<Path>, path_results: I, logger: &L,
1078 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1079 ) where L::Target: Logger {
1080 let mut events = pending_events.lock().unwrap();
1081 debug_assert_eq!(paths.len(), path_results.len());
1082 for (path, path_res) in paths.into_iter().zip(path_results) {
1083 if let Err(e) = path_res {
1084 if let APIError::MonitorUpdateInProgress = e { continue }
1085 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1086 let mut failed_scid = None;
1087 if let APIError::ChannelUnavailable { .. } = e {
1088 let scid = path.hops[0].short_channel_id;
1089 failed_scid = Some(scid);
1090 route_params.payment_params.previously_failed_channels.push(scid);
1092 events.push_back((events::Event::PaymentPathFailed {
1093 payment_id: Some(payment_id),
1095 payment_failed_permanently: false,
1096 failure: events::PathFailure::InitialSend { err: e },
1098 short_channel_id: failed_scid,
1108 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1109 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1110 best_block_height: u32, send_payment_along_path: F
1111 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1113 ES::Target: EntropySource,
1114 NS::Target: NodeSigner,
1115 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1117 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1118 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1120 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1122 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1123 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1124 err: "No need probing a path with less than two hops".to_string()
1128 let route = Route { paths: vec![path], route_params: None };
1129 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1130 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1131 entropy_source, best_block_height)?;
1133 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1134 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1136 Ok(()) => Ok((payment_hash, payment_id)),
1138 self.remove_outbound_if_all_failed(payment_id, &e);
1145 pub(super) fn test_set_payment_metadata(
1146 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1148 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1149 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1150 *payment_metadata = new_payment_metadata;
1152 _ => panic!("Need a retryable payment to update metadata on"),
1157 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1158 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1159 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1160 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1161 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1164 pub(super) fn add_new_pending_payment<ES: Deref>(
1165 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1166 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1167 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1168 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1169 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1170 match pending_outbounds.entry(payment_id) {
1171 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1172 hash_map::Entry::Vacant(entry) => {
1173 let (payment, onion_session_privs) = self.create_pending_payment(
1174 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1175 payment_params, entropy_source, best_block_height
1177 entry.insert(payment);
1178 Ok(onion_session_privs)
1183 fn create_pending_payment<ES: Deref>(
1184 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1185 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1186 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1187 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1189 ES::Target: EntropySource,
1191 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1192 for _ in 0..route.paths.len() {
1193 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1196 let mut payment = PendingOutboundPayment::Retryable {
1198 attempts: PaymentAttempts::new(),
1200 session_privs: HashSet::new(),
1201 pending_amt_msat: 0,
1202 pending_fee_msat: Some(0),
1204 payment_secret: recipient_onion.payment_secret,
1205 payment_metadata: recipient_onion.payment_metadata,
1207 custom_tlvs: recipient_onion.custom_tlvs,
1208 starting_block_height: best_block_height,
1209 total_msat: route.get_total_amount(),
1212 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1213 assert!(payment.insert(*session_priv_bytes, path));
1216 (payment, onion_session_privs)
1220 pub(super) fn add_new_awaiting_invoice(
1221 &self, payment_id: PaymentId, retry_strategy: Retry
1222 ) -> Result<(), ()> {
1223 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1224 match pending_outbounds.entry(payment_id) {
1225 hash_map::Entry::Occupied(_) => Err(()),
1226 hash_map::Entry::Vacant(entry) => {
1227 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1228 timer_ticks_without_response: 0,
1237 fn pay_route_internal<NS: Deref, F>(
1238 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1239 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1240 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1241 send_payment_along_path: &F
1242 ) -> Result<(), PaymentSendFailure>
1244 NS::Target: NodeSigner,
1245 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1247 if route.paths.len() < 1 {
1248 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1250 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1251 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1253 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1255 let mut total_value = 0;
1256 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1257 let mut path_errs = Vec::with_capacity(route.paths.len());
1258 'path_check: for path in route.paths.iter() {
1259 if path.hops.len() < 1 || path.hops.len() > 20 {
1260 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1261 continue 'path_check;
1263 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1264 usize::max_value() } else { path.hops.len() - 1 };
1265 for (idx, hop) in path.hops.iter().enumerate() {
1266 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1267 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1268 continue 'path_check;
1271 total_value += path.final_value_msat();
1272 path_errs.push(Ok(()));
1274 if path_errs.iter().any(|e| e.is_err()) {
1275 return Err(PaymentSendFailure::PathParameterError(path_errs));
1277 if let Some(amt_msat) = recv_value_msat {
1278 total_value = amt_msat;
1281 let cur_height = best_block_height + 1;
1282 let mut results = Vec::new();
1283 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1284 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1285 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1286 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1287 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1291 Err(APIError::MonitorUpdateInProgress) => {
1292 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1293 // considered "in flight" and we shouldn't remove it from the
1294 // PendingOutboundPayment set.
1297 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1298 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1299 let removed = payment.remove(&session_priv_bytes, Some(path));
1300 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1302 debug_assert!(false, "This can't happen as the payment was added by callers");
1303 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1307 results.push(path_res);
1309 let mut has_ok = false;
1310 let mut has_err = false;
1311 let mut pending_amt_unsent = 0;
1312 for (res, path) in results.iter().zip(route.paths.iter()) {
1313 if res.is_ok() { has_ok = true; }
1314 if res.is_err() { has_err = true; }
1315 if let &Err(APIError::MonitorUpdateInProgress) = res {
1316 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1320 } else if res.is_err() {
1321 pending_amt_unsent += path.final_value_msat();
1324 if has_err && has_ok {
1325 Err(PaymentSendFailure::PartialFailure {
1328 failed_paths_retry: if pending_amt_unsent != 0 {
1329 if let Some(payment_params) = route.route_params.as_ref().map(|p| p.payment_params.clone()) {
1330 Some(RouteParameters {
1331 payment_params: payment_params,
1332 final_value_msat: pending_amt_unsent,
1338 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1345 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1346 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1347 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1348 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1349 send_payment_along_path: F
1350 ) -> Result<(), PaymentSendFailure>
1352 NS::Target: NodeSigner,
1353 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1355 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1356 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1357 &send_payment_along_path)
1358 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1361 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1362 // map as the payment is free to be resent.
1363 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1364 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1365 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1366 debug_assert!(removed, "We should always have a pending payment to remove here");
1370 pub(super) fn claim_htlc<L: Deref>(
1371 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1372 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1373 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1375 ) where L::Target: Logger {
1376 let mut session_priv_bytes = [0; 32];
1377 session_priv_bytes.copy_from_slice(&session_priv[..]);
1378 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1379 let mut pending_events = pending_events.lock().unwrap();
1380 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1381 if !payment.get().is_fulfilled() {
1382 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1383 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1384 let fee_paid_msat = payment.get().get_pending_fee_msat();
1385 pending_events.push_back((events::Event::PaymentSent {
1386 payment_id: Some(payment_id),
1390 }, Some(ev_completion_action.clone())));
1391 payment.get_mut().mark_fulfilled();
1395 // We currently immediately remove HTLCs which were fulfilled on-chain.
1396 // This could potentially lead to removing a pending payment too early,
1397 // with a reorg of one block causing us to re-add the fulfilled payment on
1399 // TODO: We should have a second monitor event that informs us of payments
1400 // irrevocably fulfilled.
1401 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1402 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1403 pending_events.push_back((events::Event::PaymentPathSuccessful {
1407 }, Some(ev_completion_action)));
1411 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1415 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1416 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1418 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1419 let mut pending_events = pending_events.lock().unwrap();
1420 for source in sources {
1421 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1422 let mut session_priv_bytes = [0; 32];
1423 session_priv_bytes.copy_from_slice(&session_priv[..]);
1424 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1425 assert!(payment.get().is_fulfilled());
1426 if payment.get_mut().remove(&session_priv_bytes, None) {
1427 let payment_hash = payment.get().payment_hash();
1428 debug_assert!(payment_hash.is_some());
1429 pending_events.push_back((events::Event::PaymentPathSuccessful {
1440 pub(super) fn remove_stale_payments(
1441 &self, pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1443 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1444 let mut pending_events = pending_events.lock().unwrap();
1445 pending_outbound_payments.retain(|payment_id, payment| {
1446 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1447 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1448 // this could race the user making a duplicate send_payment call and our idempotency
1449 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1450 // removal. This should be more than sufficient to ensure the idempotency of any
1451 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1453 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1454 let mut no_remaining_entries = session_privs.is_empty();
1455 if no_remaining_entries {
1456 for (ev, _) in pending_events.iter() {
1458 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1459 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1460 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1461 if payment_id == ev_payment_id {
1462 no_remaining_entries = false;
1470 if no_remaining_entries {
1471 *timer_ticks_without_htlcs += 1;
1472 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1474 *timer_ticks_without_htlcs = 0;
1477 } else if let PendingOutboundPayment::AwaitingInvoice { timer_ticks_without_response, .. } = payment {
1478 *timer_ticks_without_response += 1;
1479 if *timer_ticks_without_response <= INVOICE_REQUEST_TIMEOUT_TICKS {
1482 pending_events.push_back(
1483 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1491 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1492 pub(super) fn fail_htlc<L: Deref>(
1493 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1494 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1495 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1496 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1497 ) -> bool where L::Target: Logger {
1499 let DecodedOnionFailure {
1500 network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data
1501 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1503 let DecodedOnionFailure { network_update, short_channel_id, payment_retryable } =
1504 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1506 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1507 let mut session_priv_bytes = [0; 32];
1508 session_priv_bytes.copy_from_slice(&session_priv[..]);
1509 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1511 // If any payments already need retry, there's no need to generate a redundant
1512 // `PendingHTLCsForwardable`.
1513 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1514 let mut awaiting_retry = false;
1515 if pmt.is_auto_retryable_now() {
1516 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1517 if pending_amt_msat < total_msat {
1518 awaiting_retry = true;
1525 let mut full_failure_ev = None;
1526 let mut pending_retry_ev = false;
1527 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1528 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1529 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1532 if payment.get().is_fulfilled() {
1533 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1536 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1537 if let Some(scid) = short_channel_id {
1538 // TODO: If we decided to blame ourselves (or one of our channels) in
1539 // process_onion_failure we should close that channel as it implies our
1540 // next-hop is needlessly blaming us!
1541 payment.get_mut().insert_previously_failed_scid(scid);
1544 if payment_is_probe || !is_retryable_now || !payment_retryable {
1545 let reason = if !payment_retryable {
1546 PaymentFailureReason::RecipientRejected
1548 PaymentFailureReason::RetriesExhausted
1550 payment.get_mut().mark_abandoned(reason);
1551 is_retryable_now = false;
1553 if payment.get().remaining_parts() == 0 {
1554 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1555 if !payment_is_probe {
1556 full_failure_ev = Some(events::Event::PaymentFailed {
1557 payment_id: *payment_id,
1558 payment_hash: *payment_hash,
1567 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1570 core::mem::drop(outbounds);
1571 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1573 let path_failure = {
1574 if payment_is_probe {
1575 if !payment_retryable {
1576 events::Event::ProbeSuccessful {
1577 payment_id: *payment_id,
1578 payment_hash: payment_hash.clone(),
1582 events::Event::ProbeFailed {
1583 payment_id: *payment_id,
1584 payment_hash: payment_hash.clone(),
1590 // If we miss abandoning the payment above, we *must* generate an event here or else the
1591 // payment will sit in our outbounds forever.
1592 if attempts_remaining && !already_awaiting_retry {
1593 debug_assert!(full_failure_ev.is_none());
1594 pending_retry_ev = true;
1596 events::Event::PaymentPathFailed {
1597 payment_id: Some(*payment_id),
1598 payment_hash: payment_hash.clone(),
1599 payment_failed_permanently: !payment_retryable,
1600 failure: events::PathFailure::OnPath { network_update },
1604 error_code: onion_error_code,
1606 error_data: onion_error_data
1610 let mut pending_events = pending_events.lock().unwrap();
1611 pending_events.push_back((path_failure, None));
1612 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1616 pub(super) fn abandon_payment(
1617 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1618 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1620 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1621 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1622 payment.get_mut().mark_abandoned(reason);
1623 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1624 if payment.get().remaining_parts() == 0 {
1625 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1627 payment_hash: *payment_hash,
1632 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1633 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1642 pub fn has_pending_payments(&self) -> bool {
1643 !self.pending_outbound_payments.lock().unwrap().is_empty()
1647 pub fn clear_pending_payments(&self) {
1648 self.pending_outbound_payments.lock().unwrap().clear()
1652 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1654 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1655 probing_cookie_secret: [u8; 32]) -> bool
1657 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1658 target_payment_hash == *payment_hash
1661 /// Returns the 'probing cookie' for the given [`PaymentId`].
1662 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1663 let mut preimage = [0u8; 64];
1664 preimage[..32].copy_from_slice(&probing_cookie_secret);
1665 preimage[32..].copy_from_slice(&payment_id.0);
1666 PaymentHash(Sha256::hash(&preimage).into_inner())
1669 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1671 (0, session_privs, required),
1674 (0, session_privs, required),
1675 (1, payment_hash, option),
1676 (3, timer_ticks_without_htlcs, (default_value, 0)),
1679 (0, session_privs, required),
1680 (1, pending_fee_msat, option),
1681 (2, payment_hash, required),
1682 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1683 // never see it - `payment_params` was added here after the field was added/required.
1684 (3, payment_params, (option: ReadableArgs, 0)),
1685 (4, payment_secret, option),
1686 (5, keysend_preimage, option),
1687 (6, total_msat, required),
1688 (7, payment_metadata, option),
1689 (8, pending_amt_msat, required),
1690 (9, custom_tlvs, optional_vec),
1691 (10, starting_block_height, required),
1692 (not_written, retry_strategy, (static_value, None)),
1693 (not_written, attempts, (static_value, PaymentAttempts::new())),
1696 (0, session_privs, required),
1697 (1, reason, option),
1698 (2, payment_hash, required),
1700 (5, AwaitingInvoice) => {
1701 (0, timer_ticks_without_response, required),
1702 (2, retry_strategy, required),
1704 (7, InvoiceReceived) => {
1705 (0, payment_hash, required),
1706 (2, retry_strategy, required),
1712 use bitcoin::network::constants::Network;
1713 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1715 use crate::events::{Event, PathFailure, PaymentFailureReason};
1716 use crate::ln::PaymentHash;
1717 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1718 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1719 use crate::ln::msgs::{ErrorAction, LightningError};
1720 use crate::ln::outbound_payment::{Bolt12PaymentError, INVOICE_REQUEST_TIMEOUT_TICKS, OutboundPayments, Retry, RetryableSendFailure};
1721 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1722 use crate::offers::offer::OfferBuilder;
1723 use crate::offers::test_utils::*;
1724 use crate::routing::gossip::NetworkGraph;
1725 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1726 use crate::sync::{Arc, Mutex, RwLock};
1727 use crate::util::errors::APIError;
1728 use crate::util::test_utils;
1730 use alloc::collections::VecDeque;
1733 fn test_recipient_onion_fields_with_custom_tlvs() {
1734 let onion_fields = RecipientOnionFields::spontaneous_empty();
1736 let bad_type_range_tlvs = vec![
1740 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1742 let keysend_tlv = vec![
1743 (5482373484, vec![42; 32]),
1745 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1747 let good_tlvs = vec![
1748 ((1 << 16) + 1, vec![42]),
1749 ((1 << 16) + 3, vec![42; 32]),
1751 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1755 #[cfg(feature = "std")]
1756 fn fails_paying_after_expiration() {
1757 do_fails_paying_after_expiration(false);
1758 do_fails_paying_after_expiration(true);
1760 #[cfg(feature = "std")]
1761 fn do_fails_paying_after_expiration(on_retry: bool) {
1762 let outbound_payments = OutboundPayments::new();
1763 let logger = test_utils::TestLogger::new();
1764 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1765 let scorer = RwLock::new(test_utils::TestScorer::new());
1766 let router = test_utils::TestRouter::new(network_graph, &scorer);
1767 let secp_ctx = Secp256k1::new();
1768 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1770 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1771 let payment_params = PaymentParameters::from_node_id(
1772 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1774 ).with_expiry_time(past_expiry_time);
1775 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1776 let pending_events = Mutex::new(VecDeque::new());
1778 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1779 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1780 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1781 &&keys_manager, 0).unwrap();
1782 outbound_payments.find_route_and_send_payment(
1783 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1784 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1786 let events = pending_events.lock().unwrap();
1787 assert_eq!(events.len(), 1);
1788 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1789 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1790 } else { panic!("Unexpected event"); }
1792 let err = outbound_payments.send_payment(
1793 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1794 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1795 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1796 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1801 fn find_route_error() {
1802 do_find_route_error(false);
1803 do_find_route_error(true);
1805 fn do_find_route_error(on_retry: bool) {
1806 let outbound_payments = OutboundPayments::new();
1807 let logger = test_utils::TestLogger::new();
1808 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1809 let scorer = RwLock::new(test_utils::TestScorer::new());
1810 let router = test_utils::TestRouter::new(network_graph, &scorer);
1811 let secp_ctx = Secp256k1::new();
1812 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1814 let payment_params = PaymentParameters::from_node_id(
1815 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1816 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1817 router.expect_find_route(route_params.clone(),
1818 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1820 let pending_events = Mutex::new(VecDeque::new());
1822 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1823 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1824 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1825 &&keys_manager, 0).unwrap();
1826 outbound_payments.find_route_and_send_payment(
1827 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1828 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1830 let events = pending_events.lock().unwrap();
1831 assert_eq!(events.len(), 1);
1832 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1834 let err = outbound_payments.send_payment(
1835 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1836 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1837 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1838 if let RetryableSendFailure::RouteNotFound = err {
1839 } else { panic!("Unexpected error"); }
1844 fn initial_send_payment_path_failed_evs() {
1845 let outbound_payments = OutboundPayments::new();
1846 let logger = test_utils::TestLogger::new();
1847 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1848 let scorer = RwLock::new(test_utils::TestScorer::new());
1849 let router = test_utils::TestRouter::new(network_graph, &scorer);
1850 let secp_ctx = Secp256k1::new();
1851 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1853 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1854 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1855 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1856 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1857 let failed_scid = 42;
1859 paths: vec![Path { hops: vec![RouteHop {
1860 pubkey: receiver_pk,
1861 node_features: NodeFeatures::empty(),
1862 short_channel_id: failed_scid,
1863 channel_features: ChannelFeatures::empty(),
1865 cltv_expiry_delta: 0,
1866 maybe_announced_channel: true,
1867 }], blinded_tail: None }],
1868 route_params: Some(route_params.clone()),
1870 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1871 let mut route_params_w_failed_scid = route_params.clone();
1872 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1873 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1874 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1875 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1877 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1878 // PaymentPathFailed event.
1879 let pending_events = Mutex::new(VecDeque::new());
1880 outbound_payments.send_payment(
1881 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1882 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1883 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1884 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1885 let mut events = pending_events.lock().unwrap();
1886 assert_eq!(events.len(), 2);
1887 if let Event::PaymentPathFailed {
1889 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1891 assert_eq!(short_channel_id, Some(failed_scid));
1892 } else { panic!("Unexpected event"); }
1893 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1895 core::mem::drop(events);
1897 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1898 outbound_payments.send_payment(
1899 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1900 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1901 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1902 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1903 assert_eq!(pending_events.lock().unwrap().len(), 0);
1905 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1906 outbound_payments.send_payment(
1907 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1908 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1909 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1910 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1911 let events = pending_events.lock().unwrap();
1912 assert_eq!(events.len(), 2);
1913 if let Event::PaymentPathFailed {
1915 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1917 assert_eq!(short_channel_id, None);
1918 } else { panic!("Unexpected event"); }
1919 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1923 fn removes_stale_awaiting_invoice() {
1924 let pending_events = Mutex::new(VecDeque::new());
1925 let outbound_payments = OutboundPayments::new();
1926 let payment_id = PaymentId([0; 32]);
1928 assert!(!outbound_payments.has_pending_payments());
1929 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1930 assert!(outbound_payments.has_pending_payments());
1932 for _ in 0..INVOICE_REQUEST_TIMEOUT_TICKS {
1933 outbound_payments.remove_stale_payments(&pending_events);
1934 assert!(outbound_payments.has_pending_payments());
1935 assert!(pending_events.lock().unwrap().is_empty());
1938 outbound_payments.remove_stale_payments(&pending_events);
1939 assert!(!outbound_payments.has_pending_payments());
1940 assert!(!pending_events.lock().unwrap().is_empty());
1942 pending_events.lock().unwrap().pop_front(),
1943 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1945 assert!(pending_events.lock().unwrap().is_empty());
1947 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1948 assert!(outbound_payments.has_pending_payments());
1950 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_err());
1954 fn removes_abandoned_awaiting_invoice() {
1955 let pending_events = Mutex::new(VecDeque::new());
1956 let outbound_payments = OutboundPayments::new();
1957 let payment_id = PaymentId([0; 32]);
1959 assert!(!outbound_payments.has_pending_payments());
1960 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1961 assert!(outbound_payments.has_pending_payments());
1963 outbound_payments.abandon_payment(
1964 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
1966 assert!(!outbound_payments.has_pending_payments());
1967 assert!(!pending_events.lock().unwrap().is_empty());
1969 pending_events.lock().unwrap().pop_front(),
1970 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1972 assert!(pending_events.lock().unwrap().is_empty());
1975 #[cfg(feature = "std")]
1977 fn fails_sending_payment_for_expired_bolt12_invoice() {
1978 let logger = test_utils::TestLogger::new();
1979 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1980 let scorer = RwLock::new(test_utils::TestScorer::new());
1981 let router = test_utils::TestRouter::new(network_graph, &scorer);
1982 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1984 let pending_events = Mutex::new(VecDeque::new());
1985 let outbound_payments = OutboundPayments::new();
1986 let payment_id = PaymentId([0; 32]);
1988 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1989 assert!(outbound_payments.has_pending_payments());
1991 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
1992 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1995 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1997 .sign(payer_sign).unwrap()
1998 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2000 .sign(recipient_sign).unwrap();
2003 outbound_payments.send_payment_for_bolt12_invoice(
2004 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2005 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2009 assert!(!outbound_payments.has_pending_payments());
2011 let payment_hash = invoice.payment_hash();
2012 let reason = Some(PaymentFailureReason::PaymentExpired);
2014 assert!(!pending_events.lock().unwrap().is_empty());
2016 pending_events.lock().unwrap().pop_front(),
2017 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2019 assert!(pending_events.lock().unwrap().is_empty());
2023 fn fails_finding_route_for_bolt12_invoice() {
2024 let logger = test_utils::TestLogger::new();
2025 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2026 let scorer = RwLock::new(test_utils::TestScorer::new());
2027 let router = test_utils::TestRouter::new(network_graph, &scorer);
2028 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2030 let pending_events = Mutex::new(VecDeque::new());
2031 let outbound_payments = OutboundPayments::new();
2032 let payment_id = PaymentId([0; 32]);
2034 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2035 assert!(outbound_payments.has_pending_payments());
2037 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2040 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2042 .sign(payer_sign).unwrap()
2043 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2045 .sign(recipient_sign).unwrap();
2047 router.expect_find_route(
2049 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2050 final_value_msat: invoice.amount_msats(),
2052 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2056 outbound_payments.send_payment_for_bolt12_invoice(
2057 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2058 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2062 assert!(!outbound_payments.has_pending_payments());
2064 let payment_hash = invoice.payment_hash();
2065 let reason = Some(PaymentFailureReason::RouteNotFound);
2067 assert!(!pending_events.lock().unwrap().is_empty());
2069 pending_events.lock().unwrap().pop_front(),
2070 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2072 assert!(pending_events.lock().unwrap().is_empty());
2076 fn fails_paying_for_bolt12_invoice() {
2077 let logger = test_utils::TestLogger::new();
2078 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2079 let scorer = RwLock::new(test_utils::TestScorer::new());
2080 let router = test_utils::TestRouter::new(network_graph, &scorer);
2081 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2083 let pending_events = Mutex::new(VecDeque::new());
2084 let outbound_payments = OutboundPayments::new();
2085 let payment_id = PaymentId([0; 32]);
2087 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2088 assert!(outbound_payments.has_pending_payments());
2090 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2093 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2095 .sign(payer_sign).unwrap()
2096 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2098 .sign(recipient_sign).unwrap();
2100 let route_params = RouteParameters {
2101 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2102 final_value_msat: invoice.amount_msats(),
2104 router.expect_find_route(
2105 route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2109 outbound_payments.send_payment_for_bolt12_invoice(
2110 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2111 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2115 assert!(!outbound_payments.has_pending_payments());
2117 let payment_hash = invoice.payment_hash();
2118 let reason = Some(PaymentFailureReason::UnexpectedError);
2120 assert!(!pending_events.lock().unwrap().is_empty());
2122 pending_events.lock().unwrap().pop_front(),
2123 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2125 assert!(pending_events.lock().unwrap().is_empty());
2129 fn sends_payment_for_bolt12_invoice() {
2130 let logger = test_utils::TestLogger::new();
2131 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2132 let scorer = RwLock::new(test_utils::TestScorer::new());
2133 let router = test_utils::TestRouter::new(network_graph, &scorer);
2134 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2136 let pending_events = Mutex::new(VecDeque::new());
2137 let outbound_payments = OutboundPayments::new();
2138 let payment_id = PaymentId([0; 32]);
2140 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2143 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2145 .sign(payer_sign).unwrap()
2146 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2148 .sign(recipient_sign).unwrap();
2150 let route_params = RouteParameters {
2151 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2152 final_value_msat: invoice.amount_msats(),
2154 router.expect_find_route(
2155 route_params.clone(),
2161 pubkey: recipient_pubkey(),
2162 node_features: NodeFeatures::empty(),
2163 short_channel_id: 42,
2164 channel_features: ChannelFeatures::empty(),
2165 fee_msat: invoice.amount_msats(),
2166 cltv_expiry_delta: 0,
2167 maybe_announced_channel: true,
2173 route_params: Some(route_params),
2177 assert!(!outbound_payments.has_pending_payments());
2179 outbound_payments.send_payment_for_bolt12_invoice(
2180 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2181 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2183 Err(Bolt12PaymentError::UnexpectedInvoice),
2185 assert!(!outbound_payments.has_pending_payments());
2186 assert!(pending_events.lock().unwrap().is_empty());
2188 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2189 assert!(outbound_payments.has_pending_payments());
2192 outbound_payments.send_payment_for_bolt12_invoice(
2193 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2194 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2198 assert!(outbound_payments.has_pending_payments());
2199 assert!(pending_events.lock().unwrap().is_empty());
2202 outbound_payments.send_payment_for_bolt12_invoice(
2203 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2204 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2206 Err(Bolt12PaymentError::DuplicateInvoice),
2208 assert!(outbound_payments.has_pending_payments());
2209 assert!(pending_events.lock().unwrap().is_empty());