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)]
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 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
470 /// This should generally be constructed with data communicated to us from the recipient (via a
471 /// BOLT11 or BOLT12 invoice).
472 #[derive(Clone, Debug, PartialEq, Eq)]
473 pub struct RecipientOnionFields {
474 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
475 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
476 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
479 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
480 /// multi-path payments require a recipient-provided secret.
482 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
483 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
484 /// recipient will not reject it.
485 pub payment_secret: Option<PaymentSecret>,
486 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
487 /// arbitrary length. This gives recipients substantially more flexibility to receive
490 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
491 /// scheme to authenticate received payments against expected payments and invoices, this field
492 /// is not used in LDK for received payments, and can be used to store arbitrary data in
493 /// invoices which will be received with the payment.
495 /// Note that this field was added to the lightning specification more recently than
496 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
497 /// may not be supported as universally.
498 pub payment_metadata: Option<Vec<u8>>,
499 /// See [`Self::custom_tlvs`] for more info.
500 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
503 impl_writeable_tlv_based!(RecipientOnionFields, {
504 (0, payment_secret, option),
505 (1, custom_tlvs, optional_vec),
506 (2, payment_metadata, option),
509 impl RecipientOnionFields {
510 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
511 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
512 /// but do not require or provide any further data.
513 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
514 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
517 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
518 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
519 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
520 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
521 /// instead want to use [`RecipientOnionFields::secret_only`].
523 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
524 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
525 pub fn spontaneous_empty() -> Self {
526 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
529 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
530 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
531 /// respectively. TLV type numbers must be unique and within the range
532 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
534 /// This method will also error for types in the experimental range which have been
535 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
537 /// See [`Self::custom_tlvs`] for more info.
538 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
539 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
540 let mut prev_type = None;
541 for (typ, _) in custom_tlvs.iter() {
542 if *typ < 1 << 16 { return Err(()); }
543 if *typ == 5482373484 { return Err(()); } // keysend
545 Some(prev) if prev >= *typ => return Err(()),
548 prev_type = Some(*typ);
550 self.custom_tlvs = custom_tlvs;
554 /// Gets the custom TLVs that will be sent or have been received.
556 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
557 /// additional flexibility on top of payment metadata, as while other implementations may
558 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
559 /// do not have this restriction.
561 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
562 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
563 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
564 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
568 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
569 /// have to make sure that some fields match exactly across the parts. For those that aren't
570 /// required to match, if they don't match we should remove them so as to not expose data
571 /// that's dependent on the HTLC receive order to users.
573 /// Here we implement this, first checking compatibility then mutating two objects and then
574 /// dropping any remaining non-matching fields from both.
575 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
576 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
577 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
579 let tlvs = &mut self.custom_tlvs;
580 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
582 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
583 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
584 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
586 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
587 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
593 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
594 pub(super) struct SendAlongPathArgs<'a> {
596 pub payment_hash: &'a PaymentHash,
597 pub recipient_onion: RecipientOnionFields,
598 pub total_value: u64,
600 pub payment_id: PaymentId,
601 pub keysend_preimage: &'a Option<PaymentPreimage>,
602 pub session_priv_bytes: [u8; 32],
605 pub(super) struct OutboundPayments {
606 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
607 pub(super) retry_lock: Mutex<()>,
610 impl OutboundPayments {
611 pub(super) fn new() -> Self {
613 pending_outbound_payments: Mutex::new(HashMap::new()),
614 retry_lock: Mutex::new(()),
618 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
619 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
620 retry_strategy: Retry, route_params: RouteParameters, router: &R,
621 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
622 node_signer: &NS, best_block_height: u32, logger: &L,
623 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
624 ) -> Result<(), RetryableSendFailure>
627 ES::Target: EntropySource,
628 NS::Target: NodeSigner,
630 IH: Fn() -> InFlightHtlcs,
631 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
633 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
634 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
635 best_block_height, logger, pending_events, &send_payment_along_path)
638 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
639 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
640 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
641 send_payment_along_path: F
642 ) -> Result<(), PaymentSendFailure>
644 ES::Target: EntropySource,
645 NS::Target: NodeSigner,
646 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
648 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)?;
649 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
650 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
651 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
654 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
655 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
656 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
657 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
658 node_signer: &NS, best_block_height: u32, logger: &L,
659 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
660 ) -> Result<PaymentHash, RetryableSendFailure>
663 ES::Target: EntropySource,
664 NS::Target: NodeSigner,
666 IH: Fn() -> InFlightHtlcs,
667 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
669 let preimage = payment_preimage
670 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
671 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
672 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
673 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
674 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
675 .map(|()| payment_hash)
678 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
679 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
680 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
681 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
682 ) -> Result<PaymentHash, PaymentSendFailure>
684 ES::Target: EntropySource,
685 NS::Target: NodeSigner,
686 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
688 let preimage = payment_preimage
689 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
690 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
691 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
692 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
694 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
695 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
697 Ok(()) => Ok(payment_hash),
699 self.remove_outbound_if_all_failed(payment_id, &e);
706 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
707 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
708 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
709 best_block_height: u32, logger: &L,
710 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
711 send_payment_along_path: SP,
712 ) -> Result<(), Bolt12PaymentError>
715 ES::Target: EntropySource,
716 NS::Target: NodeSigner,
718 IH: Fn() -> InFlightHtlcs,
719 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
721 let payment_hash = invoice.payment_hash();
722 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
723 hash_map::Entry::Occupied(entry) => match entry.get() {
724 PendingOutboundPayment::AwaitingInvoice { retry_strategy, .. } => {
725 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
727 retry_strategy: *retry_strategy,
730 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
732 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
735 let route_params = RouteParameters {
736 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
737 final_value_msat: invoice.amount_msats(),
740 self.find_route_and_send_payment(
741 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
742 entropy_source, node_signer, best_block_height, logger, pending_events,
743 &send_payment_along_path
749 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
750 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
751 best_block_height: u32,
752 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
753 send_payment_along_path: SP,
757 ES::Target: EntropySource,
758 NS::Target: NodeSigner,
759 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
760 IH: Fn() -> InFlightHtlcs,
761 FH: Fn() -> Vec<ChannelDetails>,
764 let _single_thread = self.retry_lock.lock().unwrap();
766 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
767 let mut retry_id_route_params = None;
768 for (pmt_id, pmt) in outbounds.iter_mut() {
769 if pmt.is_auto_retryable_now() {
770 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
771 if pending_amt_msat < total_msat {
772 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
773 final_value_msat: *total_msat - *pending_amt_msat,
774 payment_params: params.clone(),
778 } else { debug_assert!(false); }
781 core::mem::drop(outbounds);
782 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
783 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)
787 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
788 outbounds.retain(|pmt_id, pmt| {
789 let mut retain = true;
790 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
791 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
792 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
793 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
795 payment_hash: *payment_hash,
805 pub(super) fn needs_abandon(&self) -> bool {
806 let outbounds = self.pending_outbound_payments.lock().unwrap();
807 outbounds.iter().any(|(_, pmt)|
808 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
809 !pmt.is_awaiting_invoice())
812 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
813 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
815 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
816 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
817 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
818 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
819 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
820 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
821 node_signer: &NS, best_block_height: u32, logger: &L,
822 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
823 ) -> Result<(), RetryableSendFailure>
826 ES::Target: EntropySource,
827 NS::Target: NodeSigner,
829 IH: Fn() -> InFlightHtlcs,
830 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
832 #[cfg(feature = "std")] {
833 if has_expired(&route_params) {
834 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
835 payment_id, payment_hash);
836 return Err(RetryableSendFailure::PaymentExpired)
840 let route = router.find_route_with_id(
841 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
842 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
843 payment_hash, payment_id,
845 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
846 payment_id, payment_hash);
847 RetryableSendFailure::RouteNotFound
850 let onion_session_privs = self.add_new_pending_payment(payment_hash,
851 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
852 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
854 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
855 payment_id, payment_hash);
856 RetryableSendFailure::DuplicatePayment
859 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
860 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
861 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
862 payment_id, payment_hash, res);
863 if let Err(e) = res {
864 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);
869 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
870 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
871 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
872 node_signer: &NS, best_block_height: u32, logger: &L,
873 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
877 ES::Target: EntropySource,
878 NS::Target: NodeSigner,
880 IH: Fn() -> InFlightHtlcs,
881 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
883 #[cfg(feature = "std")] {
884 if has_expired(&route_params) {
885 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
886 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
891 let route = match router.find_route_with_id(
892 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
893 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
894 payment_hash, payment_id,
898 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
899 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
903 for path in route.paths.iter() {
904 if path.hops.len() == 0 {
905 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
906 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
911 macro_rules! abandon_with_entry {
912 ($payment: expr, $reason: expr) => {
913 $payment.get_mut().mark_abandoned($reason);
914 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
915 if $payment.get().remaining_parts() == 0 {
916 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
926 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
927 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
928 match outbounds.entry(payment_id) {
929 hash_map::Entry::Occupied(mut payment) => {
930 match payment.get() {
931 PendingOutboundPayment::Retryable {
932 total_msat, keysend_preimage, payment_secret, payment_metadata,
933 custom_tlvs, pending_amt_msat, ..
935 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
936 let retry_amt_msat = route.get_total_amount();
937 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
938 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);
939 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
943 if !payment.get().is_retryable_now() {
944 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
945 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
949 let total_msat = *total_msat;
950 let recipient_onion = RecipientOnionFields {
951 payment_secret: *payment_secret,
952 payment_metadata: payment_metadata.clone(),
953 custom_tlvs: custom_tlvs.clone(),
955 let keysend_preimage = *keysend_preimage;
957 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
958 for _ in 0..route.paths.len() {
959 onion_session_privs.push(entropy_source.get_secure_random_bytes());
962 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
963 assert!(payment.get_mut().insert(*session_priv_bytes, path));
966 payment.get_mut().increment_attempts();
968 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
970 PendingOutboundPayment::Legacy { .. } => {
971 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
974 PendingOutboundPayment::AwaitingInvoice { .. } => {
975 log_error!(logger, "Payment not yet sent");
978 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy } => {
979 let total_amount = route_params.final_value_msat;
980 let recipient_onion = RecipientOnionFields {
981 payment_secret: None,
982 payment_metadata: None,
985 let retry_strategy = Some(*retry_strategy);
986 let payment_params = Some(route_params.payment_params.clone());
987 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
988 *payment_hash, recipient_onion.clone(), None, &route,
989 retry_strategy, payment_params, entropy_source, best_block_height
991 *payment.into_mut() = retryable_payment;
992 (total_amount, recipient_onion, None, onion_session_privs)
994 PendingOutboundPayment::Fulfilled { .. } => {
995 log_error!(logger, "Payment already completed");
998 PendingOutboundPayment::Abandoned { .. } => {
999 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1004 hash_map::Entry::Vacant(_) => {
1005 log_error!(logger, "Payment with ID {} not found", &payment_id);
1010 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1011 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1012 &send_payment_along_path);
1013 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1014 if let Err(e) = res {
1015 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);
1019 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1020 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1021 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1022 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1023 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1027 ES::Target: EntropySource,
1028 NS::Target: NodeSigner,
1030 IH: Fn() -> InFlightHtlcs,
1031 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1034 PaymentSendFailure::AllFailedResendSafe(errs) => {
1035 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);
1036 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);
1038 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1039 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1040 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1041 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1042 // return `Ok()` here, ignoring any retry errors.
1043 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);
1045 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1046 // This may happen if we send a payment and some paths fail, but only due to a temporary
1047 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1048 // initial HTLC-Add messages yet.
1050 PaymentSendFailure::PathParameterError(results) => {
1051 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1052 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1053 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1055 PaymentSendFailure::ParameterError(e) => {
1056 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1057 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1059 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1063 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1064 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1065 paths: Vec<Path>, path_results: I, logger: &L,
1066 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1067 ) where L::Target: Logger {
1068 let mut events = pending_events.lock().unwrap();
1069 debug_assert_eq!(paths.len(), path_results.len());
1070 for (path, path_res) in paths.into_iter().zip(path_results) {
1071 if let Err(e) = path_res {
1072 if let APIError::MonitorUpdateInProgress = e { continue }
1073 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1074 let mut failed_scid = None;
1075 if let APIError::ChannelUnavailable { .. } = e {
1076 let scid = path.hops[0].short_channel_id;
1077 failed_scid = Some(scid);
1078 route_params.payment_params.previously_failed_channels.push(scid);
1080 events.push_back((events::Event::PaymentPathFailed {
1081 payment_id: Some(payment_id),
1083 payment_failed_permanently: false,
1084 failure: events::PathFailure::InitialSend { err: e },
1086 short_channel_id: failed_scid,
1096 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1097 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1098 best_block_height: u32, send_payment_along_path: F
1099 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1101 ES::Target: EntropySource,
1102 NS::Target: NodeSigner,
1103 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1105 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1107 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1109 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1110 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1111 err: "No need probing a path with less than two hops".to_string()
1115 let route = Route { paths: vec![path], route_params: None };
1116 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1117 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
1118 entropy_source, best_block_height)?;
1120 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1121 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1123 Ok(()) => Ok((payment_hash, payment_id)),
1125 self.remove_outbound_if_all_failed(payment_id, &e);
1132 pub(super) fn test_set_payment_metadata(
1133 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1135 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1136 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1137 *payment_metadata = new_payment_metadata;
1139 _ => panic!("Need a retryable payment to update metadata on"),
1144 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1145 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1146 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1147 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1148 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1151 pub(super) fn add_new_pending_payment<ES: Deref>(
1152 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1153 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1154 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1155 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1156 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1157 match pending_outbounds.entry(payment_id) {
1158 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1159 hash_map::Entry::Vacant(entry) => {
1160 let (payment, onion_session_privs) = self.create_pending_payment(
1161 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1162 payment_params, entropy_source, best_block_height
1164 entry.insert(payment);
1165 Ok(onion_session_privs)
1170 fn create_pending_payment<ES: Deref>(
1171 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1172 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1173 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1174 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1176 ES::Target: EntropySource,
1178 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1179 for _ in 0..route.paths.len() {
1180 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1183 let mut payment = PendingOutboundPayment::Retryable {
1185 attempts: PaymentAttempts::new(),
1187 session_privs: HashSet::new(),
1188 pending_amt_msat: 0,
1189 pending_fee_msat: Some(0),
1191 payment_secret: recipient_onion.payment_secret,
1192 payment_metadata: recipient_onion.payment_metadata,
1194 custom_tlvs: recipient_onion.custom_tlvs,
1195 starting_block_height: best_block_height,
1196 total_msat: route.get_total_amount(),
1199 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1200 assert!(payment.insert(*session_priv_bytes, path));
1203 (payment, onion_session_privs)
1207 pub(super) fn add_new_awaiting_invoice(
1208 &self, payment_id: PaymentId, retry_strategy: Retry
1209 ) -> Result<(), ()> {
1210 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1211 match pending_outbounds.entry(payment_id) {
1212 hash_map::Entry::Occupied(_) => Err(()),
1213 hash_map::Entry::Vacant(entry) => {
1214 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1215 timer_ticks_without_response: 0,
1224 fn pay_route_internal<NS: Deref, F>(
1225 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1226 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1227 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1228 send_payment_along_path: &F
1229 ) -> Result<(), PaymentSendFailure>
1231 NS::Target: NodeSigner,
1232 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1234 if route.paths.len() < 1 {
1235 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1237 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1238 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1240 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1242 let mut total_value = 0;
1243 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1244 let mut path_errs = Vec::with_capacity(route.paths.len());
1245 'path_check: for path in route.paths.iter() {
1246 if path.hops.len() < 1 || path.hops.len() > 20 {
1247 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1248 continue 'path_check;
1250 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1251 usize::max_value() } else { path.hops.len() - 1 };
1252 for (idx, hop) in path.hops.iter().enumerate() {
1253 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1254 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1255 continue 'path_check;
1258 total_value += path.final_value_msat();
1259 path_errs.push(Ok(()));
1261 if path_errs.iter().any(|e| e.is_err()) {
1262 return Err(PaymentSendFailure::PathParameterError(path_errs));
1264 if let Some(amt_msat) = recv_value_msat {
1265 total_value = amt_msat;
1268 let cur_height = best_block_height + 1;
1269 let mut results = Vec::new();
1270 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1271 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1272 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1273 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1274 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1278 Err(APIError::MonitorUpdateInProgress) => {
1279 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1280 // considered "in flight" and we shouldn't remove it from the
1281 // PendingOutboundPayment set.
1284 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1285 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1286 let removed = payment.remove(&session_priv_bytes, Some(path));
1287 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1289 debug_assert!(false, "This can't happen as the payment was added by callers");
1290 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1294 results.push(path_res);
1296 let mut has_ok = false;
1297 let mut has_err = false;
1298 let mut pending_amt_unsent = 0;
1299 for (res, path) in results.iter().zip(route.paths.iter()) {
1300 if res.is_ok() { has_ok = true; }
1301 if res.is_err() { has_err = true; }
1302 if let &Err(APIError::MonitorUpdateInProgress) = res {
1303 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1307 } else if res.is_err() {
1308 pending_amt_unsent += path.final_value_msat();
1311 if has_err && has_ok {
1312 Err(PaymentSendFailure::PartialFailure {
1315 failed_paths_retry: if pending_amt_unsent != 0 {
1316 if let Some(payment_params) = route.route_params.as_ref().map(|p| p.payment_params.clone()) {
1317 Some(RouteParameters {
1318 payment_params: payment_params,
1319 final_value_msat: pending_amt_unsent,
1325 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1332 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1333 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1334 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1335 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1336 send_payment_along_path: F
1337 ) -> Result<(), PaymentSendFailure>
1339 NS::Target: NodeSigner,
1340 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1342 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1343 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1344 &send_payment_along_path)
1345 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1348 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1349 // map as the payment is free to be resent.
1350 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1351 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1352 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1353 debug_assert!(removed, "We should always have a pending payment to remove here");
1357 pub(super) fn claim_htlc<L: Deref>(
1358 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1359 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1360 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1362 ) where L::Target: Logger {
1363 let mut session_priv_bytes = [0; 32];
1364 session_priv_bytes.copy_from_slice(&session_priv[..]);
1365 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1366 let mut pending_events = pending_events.lock().unwrap();
1367 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1368 if !payment.get().is_fulfilled() {
1369 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1370 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1371 let fee_paid_msat = payment.get().get_pending_fee_msat();
1372 pending_events.push_back((events::Event::PaymentSent {
1373 payment_id: Some(payment_id),
1377 }, Some(ev_completion_action.clone())));
1378 payment.get_mut().mark_fulfilled();
1382 // We currently immediately remove HTLCs which were fulfilled on-chain.
1383 // This could potentially lead to removing a pending payment too early,
1384 // with a reorg of one block causing us to re-add the fulfilled payment on
1386 // TODO: We should have a second monitor event that informs us of payments
1387 // irrevocably fulfilled.
1388 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1389 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1390 pending_events.push_back((events::Event::PaymentPathSuccessful {
1394 }, Some(ev_completion_action)));
1398 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1402 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1403 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1405 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1406 let mut pending_events = pending_events.lock().unwrap();
1407 for source in sources {
1408 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1409 let mut session_priv_bytes = [0; 32];
1410 session_priv_bytes.copy_from_slice(&session_priv[..]);
1411 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1412 assert!(payment.get().is_fulfilled());
1413 if payment.get_mut().remove(&session_priv_bytes, None) {
1414 let payment_hash = payment.get().payment_hash();
1415 debug_assert!(payment_hash.is_some());
1416 pending_events.push_back((events::Event::PaymentPathSuccessful {
1427 pub(super) fn remove_stale_payments(
1428 &self, pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1430 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1431 let mut pending_events = pending_events.lock().unwrap();
1432 pending_outbound_payments.retain(|payment_id, payment| {
1433 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1434 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1435 // this could race the user making a duplicate send_payment call and our idempotency
1436 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1437 // removal. This should be more than sufficient to ensure the idempotency of any
1438 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1440 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1441 let mut no_remaining_entries = session_privs.is_empty();
1442 if no_remaining_entries {
1443 for (ev, _) in pending_events.iter() {
1445 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1446 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1447 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1448 if payment_id == ev_payment_id {
1449 no_remaining_entries = false;
1457 if no_remaining_entries {
1458 *timer_ticks_without_htlcs += 1;
1459 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1461 *timer_ticks_without_htlcs = 0;
1464 } else if let PendingOutboundPayment::AwaitingInvoice { timer_ticks_without_response, .. } = payment {
1465 *timer_ticks_without_response += 1;
1466 if *timer_ticks_without_response <= INVOICE_REQUEST_TIMEOUT_TICKS {
1469 pending_events.push_back(
1470 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1478 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1479 pub(super) fn fail_htlc<L: Deref>(
1480 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1481 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1482 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1483 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1484 ) -> bool where L::Target: Logger {
1486 let DecodedOnionFailure {
1487 network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data
1488 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1490 let DecodedOnionFailure { network_update, short_channel_id, payment_retryable } =
1491 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1493 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1494 let mut session_priv_bytes = [0; 32];
1495 session_priv_bytes.copy_from_slice(&session_priv[..]);
1496 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1498 // If any payments already need retry, there's no need to generate a redundant
1499 // `PendingHTLCsForwardable`.
1500 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1501 let mut awaiting_retry = false;
1502 if pmt.is_auto_retryable_now() {
1503 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1504 if pending_amt_msat < total_msat {
1505 awaiting_retry = true;
1512 let mut full_failure_ev = None;
1513 let mut pending_retry_ev = false;
1514 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1515 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1516 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1519 if payment.get().is_fulfilled() {
1520 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1523 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1524 if let Some(scid) = short_channel_id {
1525 // TODO: If we decided to blame ourselves (or one of our channels) in
1526 // process_onion_failure we should close that channel as it implies our
1527 // next-hop is needlessly blaming us!
1528 payment.get_mut().insert_previously_failed_scid(scid);
1531 if payment_is_probe || !is_retryable_now || !payment_retryable {
1532 let reason = if !payment_retryable {
1533 PaymentFailureReason::RecipientRejected
1535 PaymentFailureReason::RetriesExhausted
1537 payment.get_mut().mark_abandoned(reason);
1538 is_retryable_now = false;
1540 if payment.get().remaining_parts() == 0 {
1541 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1542 if !payment_is_probe {
1543 full_failure_ev = Some(events::Event::PaymentFailed {
1544 payment_id: *payment_id,
1545 payment_hash: *payment_hash,
1554 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1557 core::mem::drop(outbounds);
1558 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1560 let path_failure = {
1561 if payment_is_probe {
1562 if !payment_retryable {
1563 events::Event::ProbeSuccessful {
1564 payment_id: *payment_id,
1565 payment_hash: payment_hash.clone(),
1569 events::Event::ProbeFailed {
1570 payment_id: *payment_id,
1571 payment_hash: payment_hash.clone(),
1577 // If we miss abandoning the payment above, we *must* generate an event here or else the
1578 // payment will sit in our outbounds forever.
1579 if attempts_remaining && !already_awaiting_retry {
1580 debug_assert!(full_failure_ev.is_none());
1581 pending_retry_ev = true;
1583 events::Event::PaymentPathFailed {
1584 payment_id: Some(*payment_id),
1585 payment_hash: payment_hash.clone(),
1586 payment_failed_permanently: !payment_retryable,
1587 failure: events::PathFailure::OnPath { network_update },
1591 error_code: onion_error_code,
1593 error_data: onion_error_data
1597 let mut pending_events = pending_events.lock().unwrap();
1598 pending_events.push_back((path_failure, None));
1599 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1603 pub(super) fn abandon_payment(
1604 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1605 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1607 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1608 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1609 payment.get_mut().mark_abandoned(reason);
1610 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1611 if payment.get().remaining_parts() == 0 {
1612 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1614 payment_hash: *payment_hash,
1619 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1620 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1629 pub fn has_pending_payments(&self) -> bool {
1630 !self.pending_outbound_payments.lock().unwrap().is_empty()
1634 pub fn clear_pending_payments(&self) {
1635 self.pending_outbound_payments.lock().unwrap().clear()
1639 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1641 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1642 probing_cookie_secret: [u8; 32]) -> bool
1644 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1645 target_payment_hash == *payment_hash
1648 /// Returns the 'probing cookie' for the given [`PaymentId`].
1649 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1650 let mut preimage = [0u8; 64];
1651 preimage[..32].copy_from_slice(&probing_cookie_secret);
1652 preimage[32..].copy_from_slice(&payment_id.0);
1653 PaymentHash(Sha256::hash(&preimage).into_inner())
1656 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1658 (0, session_privs, required),
1661 (0, session_privs, required),
1662 (1, payment_hash, option),
1663 (3, timer_ticks_without_htlcs, (default_value, 0)),
1666 (0, session_privs, required),
1667 (1, pending_fee_msat, option),
1668 (2, payment_hash, required),
1669 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1670 // never see it - `payment_params` was added here after the field was added/required.
1671 (3, payment_params, (option: ReadableArgs, 0)),
1672 (4, payment_secret, option),
1673 (5, keysend_preimage, option),
1674 (6, total_msat, required),
1675 (7, payment_metadata, option),
1676 (8, pending_amt_msat, required),
1677 (9, custom_tlvs, optional_vec),
1678 (10, starting_block_height, required),
1679 (not_written, retry_strategy, (static_value, None)),
1680 (not_written, attempts, (static_value, PaymentAttempts::new())),
1683 (0, session_privs, required),
1684 (1, reason, option),
1685 (2, payment_hash, required),
1687 (5, AwaitingInvoice) => {
1688 (0, timer_ticks_without_response, required),
1689 (2, retry_strategy, required),
1691 (7, InvoiceReceived) => {
1692 (0, payment_hash, required),
1693 (2, retry_strategy, required),
1699 use bitcoin::network::constants::Network;
1700 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1702 use crate::events::{Event, PathFailure, PaymentFailureReason};
1703 use crate::ln::PaymentHash;
1704 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1705 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1706 use crate::ln::msgs::{ErrorAction, LightningError};
1707 use crate::ln::outbound_payment::{Bolt12PaymentError, INVOICE_REQUEST_TIMEOUT_TICKS, OutboundPayments, Retry, RetryableSendFailure};
1708 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1709 use crate::offers::offer::OfferBuilder;
1710 use crate::offers::test_utils::*;
1711 use crate::routing::gossip::NetworkGraph;
1712 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1713 use crate::sync::{Arc, Mutex, RwLock};
1714 use crate::util::errors::APIError;
1715 use crate::util::test_utils;
1717 use alloc::collections::VecDeque;
1720 fn test_recipient_onion_fields_with_custom_tlvs() {
1721 let onion_fields = RecipientOnionFields::spontaneous_empty();
1723 let bad_type_range_tlvs = vec![
1727 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1729 let keysend_tlv = vec![
1730 (5482373484, vec![42; 32]),
1732 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1734 let good_tlvs = vec![
1735 ((1 << 16) + 1, vec![42]),
1736 ((1 << 16) + 3, vec![42; 32]),
1738 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1742 #[cfg(feature = "std")]
1743 fn fails_paying_after_expiration() {
1744 do_fails_paying_after_expiration(false);
1745 do_fails_paying_after_expiration(true);
1747 #[cfg(feature = "std")]
1748 fn do_fails_paying_after_expiration(on_retry: bool) {
1749 let outbound_payments = OutboundPayments::new();
1750 let logger = test_utils::TestLogger::new();
1751 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1752 let scorer = RwLock::new(test_utils::TestScorer::new());
1753 let router = test_utils::TestRouter::new(network_graph, &scorer);
1754 let secp_ctx = Secp256k1::new();
1755 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1757 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1758 let payment_params = PaymentParameters::from_node_id(
1759 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1761 ).with_expiry_time(past_expiry_time);
1762 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1763 let pending_events = Mutex::new(VecDeque::new());
1765 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1766 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1767 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1768 &&keys_manager, 0).unwrap();
1769 outbound_payments.find_route_and_send_payment(
1770 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1771 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1773 let events = pending_events.lock().unwrap();
1774 assert_eq!(events.len(), 1);
1775 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1776 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1777 } else { panic!("Unexpected event"); }
1779 let err = outbound_payments.send_payment(
1780 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1781 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1782 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1783 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1788 fn find_route_error() {
1789 do_find_route_error(false);
1790 do_find_route_error(true);
1792 fn do_find_route_error(on_retry: bool) {
1793 let outbound_payments = OutboundPayments::new();
1794 let logger = test_utils::TestLogger::new();
1795 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1796 let scorer = RwLock::new(test_utils::TestScorer::new());
1797 let router = test_utils::TestRouter::new(network_graph, &scorer);
1798 let secp_ctx = Secp256k1::new();
1799 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1801 let payment_params = PaymentParameters::from_node_id(
1802 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1803 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1804 router.expect_find_route(route_params.clone(),
1805 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1807 let pending_events = Mutex::new(VecDeque::new());
1809 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1810 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1811 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1812 &&keys_manager, 0).unwrap();
1813 outbound_payments.find_route_and_send_payment(
1814 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1815 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1817 let events = pending_events.lock().unwrap();
1818 assert_eq!(events.len(), 1);
1819 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1821 let err = outbound_payments.send_payment(
1822 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1823 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1824 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1825 if let RetryableSendFailure::RouteNotFound = err {
1826 } else { panic!("Unexpected error"); }
1831 fn initial_send_payment_path_failed_evs() {
1832 let outbound_payments = OutboundPayments::new();
1833 let logger = test_utils::TestLogger::new();
1834 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1835 let scorer = RwLock::new(test_utils::TestScorer::new());
1836 let router = test_utils::TestRouter::new(network_graph, &scorer);
1837 let secp_ctx = Secp256k1::new();
1838 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1840 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1841 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1842 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1843 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1844 let failed_scid = 42;
1846 paths: vec![Path { hops: vec![RouteHop {
1847 pubkey: receiver_pk,
1848 node_features: NodeFeatures::empty(),
1849 short_channel_id: failed_scid,
1850 channel_features: ChannelFeatures::empty(),
1852 cltv_expiry_delta: 0,
1853 }], blinded_tail: None }],
1854 route_params: Some(route_params.clone()),
1856 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1857 let mut route_params_w_failed_scid = route_params.clone();
1858 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1859 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1860 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1861 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1863 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1864 // PaymentPathFailed event.
1865 let pending_events = Mutex::new(VecDeque::new());
1866 outbound_payments.send_payment(
1867 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1868 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1869 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1870 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1871 let mut events = pending_events.lock().unwrap();
1872 assert_eq!(events.len(), 2);
1873 if let Event::PaymentPathFailed {
1875 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1877 assert_eq!(short_channel_id, Some(failed_scid));
1878 } else { panic!("Unexpected event"); }
1879 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1881 core::mem::drop(events);
1883 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1884 outbound_payments.send_payment(
1885 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1886 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1887 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1888 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1889 assert_eq!(pending_events.lock().unwrap().len(), 0);
1891 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1892 outbound_payments.send_payment(
1893 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1894 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1895 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1896 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1897 let events = pending_events.lock().unwrap();
1898 assert_eq!(events.len(), 2);
1899 if let Event::PaymentPathFailed {
1901 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1903 assert_eq!(short_channel_id, None);
1904 } else { panic!("Unexpected event"); }
1905 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1909 fn removes_stale_awaiting_invoice() {
1910 let pending_events = Mutex::new(VecDeque::new());
1911 let outbound_payments = OutboundPayments::new();
1912 let payment_id = PaymentId([0; 32]);
1914 assert!(!outbound_payments.has_pending_payments());
1915 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1916 assert!(outbound_payments.has_pending_payments());
1918 for _ in 0..INVOICE_REQUEST_TIMEOUT_TICKS {
1919 outbound_payments.remove_stale_payments(&pending_events);
1920 assert!(outbound_payments.has_pending_payments());
1921 assert!(pending_events.lock().unwrap().is_empty());
1924 outbound_payments.remove_stale_payments(&pending_events);
1925 assert!(!outbound_payments.has_pending_payments());
1926 assert!(!pending_events.lock().unwrap().is_empty());
1928 pending_events.lock().unwrap().pop_front(),
1929 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1931 assert!(pending_events.lock().unwrap().is_empty());
1933 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1934 assert!(outbound_payments.has_pending_payments());
1936 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_err());
1940 fn removes_abandoned_awaiting_invoice() {
1941 let pending_events = Mutex::new(VecDeque::new());
1942 let outbound_payments = OutboundPayments::new();
1943 let payment_id = PaymentId([0; 32]);
1945 assert!(!outbound_payments.has_pending_payments());
1946 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1947 assert!(outbound_payments.has_pending_payments());
1949 outbound_payments.abandon_payment(
1950 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
1952 assert!(!outbound_payments.has_pending_payments());
1953 assert!(!pending_events.lock().unwrap().is_empty());
1955 pending_events.lock().unwrap().pop_front(),
1956 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1958 assert!(pending_events.lock().unwrap().is_empty());
1961 #[cfg(feature = "std")]
1963 fn fails_sending_payment_for_expired_bolt12_invoice() {
1964 let logger = test_utils::TestLogger::new();
1965 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1966 let scorer = RwLock::new(test_utils::TestScorer::new());
1967 let router = test_utils::TestRouter::new(network_graph, &scorer);
1968 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1970 let pending_events = Mutex::new(VecDeque::new());
1971 let outbound_payments = OutboundPayments::new();
1972 let payment_id = PaymentId([0; 32]);
1974 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
1975 assert!(outbound_payments.has_pending_payments());
1977 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
1978 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
1981 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
1983 .sign(payer_sign).unwrap()
1984 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
1986 .sign(recipient_sign).unwrap();
1989 outbound_payments.send_payment_for_bolt12_invoice(
1990 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
1991 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
1995 assert!(!outbound_payments.has_pending_payments());
1997 let payment_hash = invoice.payment_hash();
1998 let reason = Some(PaymentFailureReason::PaymentExpired);
2000 assert!(!pending_events.lock().unwrap().is_empty());
2002 pending_events.lock().unwrap().pop_front(),
2003 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2005 assert!(pending_events.lock().unwrap().is_empty());
2009 fn fails_finding_route_for_bolt12_invoice() {
2010 let logger = test_utils::TestLogger::new();
2011 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2012 let scorer = RwLock::new(test_utils::TestScorer::new());
2013 let router = test_utils::TestRouter::new(network_graph, &scorer);
2014 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2016 let pending_events = Mutex::new(VecDeque::new());
2017 let outbound_payments = OutboundPayments::new();
2018 let payment_id = PaymentId([0; 32]);
2020 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2021 assert!(outbound_payments.has_pending_payments());
2023 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2026 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2028 .sign(payer_sign).unwrap()
2029 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2031 .sign(recipient_sign).unwrap();
2033 router.expect_find_route(
2035 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2036 final_value_msat: invoice.amount_msats(),
2038 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2042 outbound_payments.send_payment_for_bolt12_invoice(
2043 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2044 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2048 assert!(!outbound_payments.has_pending_payments());
2050 let payment_hash = invoice.payment_hash();
2051 let reason = Some(PaymentFailureReason::RouteNotFound);
2053 assert!(!pending_events.lock().unwrap().is_empty());
2055 pending_events.lock().unwrap().pop_front(),
2056 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2058 assert!(pending_events.lock().unwrap().is_empty());
2062 fn fails_paying_for_bolt12_invoice() {
2063 let logger = test_utils::TestLogger::new();
2064 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2065 let scorer = RwLock::new(test_utils::TestScorer::new());
2066 let router = test_utils::TestRouter::new(network_graph, &scorer);
2067 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2069 let pending_events = Mutex::new(VecDeque::new());
2070 let outbound_payments = OutboundPayments::new();
2071 let payment_id = PaymentId([0; 32]);
2073 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2074 assert!(outbound_payments.has_pending_payments());
2076 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2079 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2081 .sign(payer_sign).unwrap()
2082 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2084 .sign(recipient_sign).unwrap();
2086 let route_params = RouteParameters {
2087 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2088 final_value_msat: invoice.amount_msats(),
2090 router.expect_find_route(
2091 route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2095 outbound_payments.send_payment_for_bolt12_invoice(
2096 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2097 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2101 assert!(!outbound_payments.has_pending_payments());
2103 let payment_hash = invoice.payment_hash();
2104 let reason = Some(PaymentFailureReason::UnexpectedError);
2106 assert!(!pending_events.lock().unwrap().is_empty());
2108 pending_events.lock().unwrap().pop_front(),
2109 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2111 assert!(pending_events.lock().unwrap().is_empty());
2115 fn sends_payment_for_bolt12_invoice() {
2116 let logger = test_utils::TestLogger::new();
2117 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2118 let scorer = RwLock::new(test_utils::TestScorer::new());
2119 let router = test_utils::TestRouter::new(network_graph, &scorer);
2120 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2122 let pending_events = Mutex::new(VecDeque::new());
2123 let outbound_payments = OutboundPayments::new();
2124 let payment_id = PaymentId([0; 32]);
2126 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2129 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2131 .sign(payer_sign).unwrap()
2132 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2134 .sign(recipient_sign).unwrap();
2136 let route_params = RouteParameters {
2137 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2138 final_value_msat: invoice.amount_msats(),
2140 router.expect_find_route(
2141 route_params.clone(),
2147 pubkey: recipient_pubkey(),
2148 node_features: NodeFeatures::empty(),
2149 short_channel_id: 42,
2150 channel_features: ChannelFeatures::empty(),
2151 fee_msat: invoice.amount_msats(),
2152 cltv_expiry_delta: 0,
2158 route_params: Some(route_params),
2162 assert!(!outbound_payments.has_pending_payments());
2164 outbound_payments.send_payment_for_bolt12_invoice(
2165 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2166 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2168 Err(Bolt12PaymentError::UnexpectedInvoice),
2170 assert!(!outbound_payments.has_pending_payments());
2171 assert!(pending_events.lock().unwrap().is_empty());
2173 assert!(outbound_payments.add_new_awaiting_invoice(payment_id, Retry::Attempts(0)).is_ok());
2174 assert!(outbound_payments.has_pending_payments());
2177 outbound_payments.send_payment_for_bolt12_invoice(
2178 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2179 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2183 assert!(outbound_payments.has_pending_payments());
2184 assert!(pending_events.lock().unwrap().is_empty());
2187 outbound_payments.send_payment_for_bolt12_invoice(
2188 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2189 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2191 Err(Bolt12PaymentError::DuplicateInvoice),
2193 assert!(outbound_payments.has_pending_payments());
2194 assert!(pending_events.lock().unwrap().is_empty());