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, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
22 use crate::util::errors::APIError;
23 use crate::util::logger::Logger;
24 use crate::util::time::Time;
25 #[cfg(all(not(feature = "no-std"), test))]
26 use crate::util::time::tests::SinceEpoch;
27 use crate::util::ser::ReadableArgs;
29 use core::fmt::{self, Display, Formatter};
32 use crate::prelude::*;
33 use crate::sync::Mutex;
35 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
36 /// and later, also stores information for retrying the payment.
37 pub(crate) enum PendingOutboundPayment {
39 session_privs: HashSet<[u8; 32]>,
42 retry_strategy: Option<Retry>,
43 attempts: PaymentAttempts,
44 payment_params: Option<PaymentParameters>,
45 session_privs: HashSet<[u8; 32]>,
46 payment_hash: PaymentHash,
47 payment_secret: Option<PaymentSecret>,
48 payment_metadata: Option<Vec<u8>>,
49 keysend_preimage: Option<PaymentPreimage>,
50 custom_tlvs: Vec<(u64, Vec<u8>)>,
51 pending_amt_msat: u64,
52 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
53 pending_fee_msat: Option<u64>,
54 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
56 /// Our best known block height at the time this payment was initiated.
57 starting_block_height: u32,
59 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
60 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
61 /// and add a pending payment that was already fulfilled.
63 session_privs: HashSet<[u8; 32]>,
64 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
65 payment_hash: Option<PaymentHash>,
66 timer_ticks_without_htlcs: u8,
68 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
69 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
71 session_privs: HashSet<[u8; 32]>,
72 payment_hash: PaymentHash,
73 /// Will be `None` if the payment was serialized before 0.0.115.
74 reason: Option<PaymentFailureReason>,
78 impl PendingOutboundPayment {
79 fn increment_attempts(&mut self) {
80 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
84 fn is_auto_retryable_now(&self) -> bool {
86 PendingOutboundPayment::Retryable {
87 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
89 strategy.is_retryable_now(&attempts)
94 fn is_retryable_now(&self) -> bool {
96 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
97 // We're handling retries manually, we can always retry.
100 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
101 strategy.is_retryable_now(&attempts)
106 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
107 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
108 params.previously_failed_channels.push(scid);
111 pub(super) fn is_fulfilled(&self) -> bool {
113 PendingOutboundPayment::Fulfilled { .. } => true,
117 pub(super) fn abandoned(&self) -> bool {
119 PendingOutboundPayment::Abandoned { .. } => true,
123 fn get_pending_fee_msat(&self) -> Option<u64> {
125 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
130 fn payment_hash(&self) -> Option<PaymentHash> {
132 PendingOutboundPayment::Legacy { .. } => None,
133 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
134 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
135 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
139 fn mark_fulfilled(&mut self) {
140 let mut session_privs = HashSet::new();
141 core::mem::swap(&mut session_privs, match self {
142 PendingOutboundPayment::Legacy { session_privs } |
143 PendingOutboundPayment::Retryable { session_privs, .. } |
144 PendingOutboundPayment::Fulfilled { session_privs, .. } |
145 PendingOutboundPayment::Abandoned { session_privs, .. }
148 let payment_hash = self.payment_hash();
149 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
152 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
153 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
154 let mut our_session_privs = HashSet::new();
155 core::mem::swap(&mut our_session_privs, session_privs);
156 *self = PendingOutboundPayment::Abandoned {
157 session_privs: our_session_privs,
158 payment_hash: *payment_hash,
164 /// panics if path is None and !self.is_fulfilled
165 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
166 let remove_res = match self {
167 PendingOutboundPayment::Legacy { session_privs } |
168 PendingOutboundPayment::Retryable { session_privs, .. } |
169 PendingOutboundPayment::Fulfilled { session_privs, .. } |
170 PendingOutboundPayment::Abandoned { session_privs, .. } => {
171 session_privs.remove(session_priv)
175 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
176 let path = path.expect("Fulfilling a payment should always come with a path");
177 *pending_amt_msat -= path.final_value_msat();
178 if let Some(fee_msat) = pending_fee_msat.as_mut() {
179 *fee_msat -= path.fee_msat();
186 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
187 let insert_res = match self {
188 PendingOutboundPayment::Legacy { session_privs } |
189 PendingOutboundPayment::Retryable { session_privs, .. } => {
190 session_privs.insert(session_priv)
192 PendingOutboundPayment::Fulfilled { .. } => false,
193 PendingOutboundPayment::Abandoned { .. } => false,
196 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
197 *pending_amt_msat += path.final_value_msat();
198 if let Some(fee_msat) = pending_fee_msat.as_mut() {
199 *fee_msat += path.fee_msat();
206 pub(super) fn remaining_parts(&self) -> usize {
208 PendingOutboundPayment::Legacy { session_privs } |
209 PendingOutboundPayment::Retryable { session_privs, .. } |
210 PendingOutboundPayment::Fulfilled { session_privs, .. } |
211 PendingOutboundPayment::Abandoned { session_privs, .. } => {
218 /// Strategies available to retry payment path failures.
219 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
221 /// Max number of attempts to retry payment.
223 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
224 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
225 /// were retried along a route from a single call to [`Router::find_route_with_id`].
227 #[cfg(not(feature = "no-std"))]
228 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
229 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
231 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
232 Timeout(core::time::Duration),
236 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
237 match (self, attempts) {
238 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
239 max_retry_count > count
241 #[cfg(all(not(feature = "no-std"), not(test)))]
242 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
243 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
244 #[cfg(all(not(feature = "no-std"), test))]
245 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
246 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
251 #[cfg(feature = "std")]
252 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
253 if let Some(expiry_time) = route_params.payment_params.expiry_time {
254 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
255 return elapsed > core::time::Duration::from_secs(expiry_time)
261 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
263 /// Storing minimal payment attempts information required for determining if a outbound payment can
265 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
266 /// This count will be incremented only after the result of the attempt is known. When it's 0,
267 /// it means the result of the first attempt is not known yet.
268 pub(crate) count: usize,
269 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
270 #[cfg(not(feature = "no-std"))]
271 first_attempted_at: T,
272 #[cfg(feature = "no-std")]
273 phantom: core::marker::PhantomData<T>,
277 #[cfg(not(any(feature = "no-std", test)))]
278 type ConfiguredTime = crate::util::time::MonotonicTime;
279 #[cfg(feature = "no-std")]
280 type ConfiguredTime = crate::util::time::Eternity;
281 #[cfg(all(not(feature = "no-std"), test))]
282 type ConfiguredTime = SinceEpoch;
284 impl<T: Time> PaymentAttemptsUsingTime<T> {
285 pub(crate) fn new() -> Self {
286 PaymentAttemptsUsingTime {
288 #[cfg(not(feature = "no-std"))]
289 first_attempted_at: T::now(),
290 #[cfg(feature = "no-std")]
291 phantom: core::marker::PhantomData,
296 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
297 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
298 #[cfg(feature = "no-std")]
299 return write!(f, "attempts: {}", self.count);
300 #[cfg(not(feature = "no-std"))]
303 "attempts: {}, duration: {}s",
305 T::now().duration_since(self.first_attempted_at).as_secs()
310 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
311 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
313 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
314 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
315 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
316 #[derive(Clone, Debug, PartialEq, Eq)]
317 pub enum RetryableSendFailure {
318 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
319 /// that this error is *not* caused by [`Retry::Timeout`].
321 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
323 /// We were unable to find a route to the destination.
325 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
326 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
328 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
329 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
330 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
334 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
335 /// of several states. This enum is returned as the Err() type describing which state the payment
336 /// is in, see the description of individual enum states for more.
338 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
339 #[derive(Clone, Debug)]
340 pub enum PaymentSendFailure {
341 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
342 /// send the payment at all.
344 /// You can freely resend the payment in full (with the parameter error fixed).
346 /// Because the payment failed outright, no payment tracking is done and no
347 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
349 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
350 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
351 ParameterError(APIError),
352 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
353 /// from attempting to send the payment at all.
355 /// You can freely resend the payment in full (with the parameter error fixed).
357 /// Because the payment failed outright, no payment tracking is done and no
358 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
360 /// The results here are ordered the same as the paths in the route object which was passed to
363 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
364 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
365 PathParameterError(Vec<Result<(), APIError>>),
366 /// All paths which were attempted failed to send, with no channel state change taking place.
367 /// You can freely resend the payment in full (though you probably want to do so over different
368 /// paths than the ones selected).
370 /// Because the payment failed outright, no payment tracking is done and no
371 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
373 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
374 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
375 AllFailedResendSafe(Vec<APIError>),
376 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
377 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
379 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
380 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
381 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
383 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
384 /// some paths have irrevocably committed to the HTLC.
386 /// The results here are ordered the same as the paths in the route object that was passed to
389 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
390 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
392 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
394 /// The errors themselves, in the same order as the paths from the route.
395 results: Vec<Result<(), APIError>>,
396 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
397 /// contain a [`RouteParameters`] object for the failing paths.
398 failed_paths_retry: Option<RouteParameters>,
399 /// The payment id for the payment, which is now at least partially pending.
400 payment_id: PaymentId,
404 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
406 /// This should generally be constructed with data communicated to us from the recipient (via a
407 /// BOLT11 or BOLT12 invoice).
408 #[derive(Clone, Debug, PartialEq, Eq)]
409 pub struct RecipientOnionFields {
410 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
411 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
412 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
415 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
416 /// multi-path payments require a recipient-provided secret.
418 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
419 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
420 /// recipient will not reject it.
421 pub payment_secret: Option<PaymentSecret>,
422 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
423 /// arbitrary length. This gives recipients substantially more flexibility to receive
426 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
427 /// scheme to authenticate received payments against expected payments and invoices, this field
428 /// is not used in LDK for received payments, and can be used to store arbitrary data in
429 /// invoices which will be received with the payment.
431 /// Note that this field was added to the lightning specification more recently than
432 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
433 /// may not be supported as universally.
434 pub payment_metadata: Option<Vec<u8>>,
435 /// See [`Self::custom_tlvs`] for more info.
436 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
439 impl_writeable_tlv_based!(RecipientOnionFields, {
440 (0, payment_secret, option),
441 (1, custom_tlvs, optional_vec),
442 (2, payment_metadata, option),
445 impl RecipientOnionFields {
446 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
447 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
448 /// but do not require or provide any further data.
449 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
450 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
453 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
454 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
455 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
456 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
457 /// instead want to use [`RecipientOnionFields::secret_only`].
459 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
460 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
461 pub fn spontaneous_empty() -> Self {
462 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
465 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
466 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
467 /// respectively. TLV type numbers must be unique and within the range
468 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
470 /// This method will also error for types in the experimental range which have been
471 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
473 /// See [`Self::custom_tlvs`] for more info.
474 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
475 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
476 let mut prev_type = None;
477 for (typ, _) in custom_tlvs.iter() {
478 if *typ < 1 << 16 { return Err(()); }
479 if *typ == 5482373484 { return Err(()); } // keysend
481 Some(prev) if prev >= *typ => return Err(()),
484 prev_type = Some(*typ);
486 self.custom_tlvs = custom_tlvs;
490 /// Gets the custom TLVs that will be sent or have been received.
492 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
493 /// additional flexibility on top of payment metadata, as while other implementations may
494 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
495 /// do not have this restriction.
497 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
498 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
499 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
500 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
504 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
505 /// have to make sure that some fields match exactly across the parts. For those that aren't
506 /// required to match, if they don't match we should remove them so as to not expose data
507 /// that's dependent on the HTLC receive order to users.
509 /// Here we implement this, first checking compatibility then mutating two objects and then
510 /// dropping any remaining non-matching fields from both.
511 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
512 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
513 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
514 // For custom TLVs we should just drop non-matching ones, but not reject the payment.
519 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
520 pub(super) struct SendAlongPathArgs<'a> {
522 pub payment_hash: &'a PaymentHash,
523 pub recipient_onion: RecipientOnionFields,
524 pub total_value: u64,
526 pub payment_id: PaymentId,
527 pub keysend_preimage: &'a Option<PaymentPreimage>,
528 pub session_priv_bytes: [u8; 32],
531 pub(super) struct OutboundPayments {
532 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
533 pub(super) retry_lock: Mutex<()>,
536 impl OutboundPayments {
537 pub(super) fn new() -> Self {
539 pending_outbound_payments: Mutex::new(HashMap::new()),
540 retry_lock: Mutex::new(()),
544 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
545 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
546 retry_strategy: Retry, route_params: RouteParameters, router: &R,
547 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
548 node_signer: &NS, best_block_height: u32, logger: &L,
549 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
550 ) -> Result<(), RetryableSendFailure>
553 ES::Target: EntropySource,
554 NS::Target: NodeSigner,
556 IH: Fn() -> InFlightHtlcs,
557 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
559 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
560 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
561 best_block_height, logger, pending_events, &send_payment_along_path)
564 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
565 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
566 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
567 send_payment_along_path: F
568 ) -> Result<(), PaymentSendFailure>
570 ES::Target: EntropySource,
571 NS::Target: NodeSigner,
572 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
574 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)?;
575 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
576 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
577 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
580 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
581 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
582 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
583 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
584 node_signer: &NS, best_block_height: u32, logger: &L,
585 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
586 ) -> Result<PaymentHash, RetryableSendFailure>
589 ES::Target: EntropySource,
590 NS::Target: NodeSigner,
592 IH: Fn() -> InFlightHtlcs,
593 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
595 let preimage = payment_preimage
596 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
597 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
598 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
599 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
600 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
601 .map(|()| payment_hash)
604 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
605 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
606 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
607 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
608 ) -> Result<PaymentHash, PaymentSendFailure>
610 ES::Target: EntropySource,
611 NS::Target: NodeSigner,
612 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
614 let preimage = payment_preimage
615 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
616 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
617 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
618 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
620 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
621 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
623 Ok(()) => Ok(payment_hash),
625 self.remove_outbound_if_all_failed(payment_id, &e);
631 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
632 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
633 best_block_height: u32,
634 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
635 send_payment_along_path: SP,
639 ES::Target: EntropySource,
640 NS::Target: NodeSigner,
641 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
642 IH: Fn() -> InFlightHtlcs,
643 FH: Fn() -> Vec<ChannelDetails>,
646 let _single_thread = self.retry_lock.lock().unwrap();
648 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
649 let mut retry_id_route_params = None;
650 for (pmt_id, pmt) in outbounds.iter_mut() {
651 if pmt.is_auto_retryable_now() {
652 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
653 if pending_amt_msat < total_msat {
654 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
655 final_value_msat: *total_msat - *pending_amt_msat,
656 payment_params: params.clone(),
660 } else { debug_assert!(false); }
663 core::mem::drop(outbounds);
664 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
665 self.retry_payment_internal(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)
669 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
670 outbounds.retain(|pmt_id, pmt| {
671 let mut retain = true;
672 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
673 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
674 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
675 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
677 payment_hash: *payment_hash,
687 pub(super) fn needs_abandon(&self) -> bool {
688 let outbounds = self.pending_outbound_payments.lock().unwrap();
689 outbounds.iter().any(|(_, pmt)|
690 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
693 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
694 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
696 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
697 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
698 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
699 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
700 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
701 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
702 node_signer: &NS, best_block_height: u32, logger: &L,
703 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
704 ) -> Result<(), RetryableSendFailure>
707 ES::Target: EntropySource,
708 NS::Target: NodeSigner,
710 IH: Fn() -> InFlightHtlcs,
711 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
713 #[cfg(feature = "std")] {
714 if has_expired(&route_params) {
715 return Err(RetryableSendFailure::PaymentExpired)
719 let route = router.find_route_with_id(
720 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
721 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
722 payment_hash, payment_id,
723 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
725 let onion_session_privs = self.add_new_pending_payment(payment_hash,
726 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
727 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
728 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
730 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
731 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
732 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
733 if let Err(e) = res {
734 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);
739 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
740 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
741 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
742 node_signer: &NS, best_block_height: u32, logger: &L,
743 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
747 ES::Target: EntropySource,
748 NS::Target: NodeSigner,
750 IH: Fn() -> InFlightHtlcs,
751 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
753 #[cfg(feature = "std")] {
754 if has_expired(&route_params) {
755 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
756 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
761 let route = match router.find_route_with_id(
762 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
763 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
764 payment_hash, payment_id,
768 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
769 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
773 for path in route.paths.iter() {
774 if path.hops.len() == 0 {
775 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
776 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
781 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
782 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
783 for _ in 0..route.paths.len() {
784 onion_session_privs.push(entropy_source.get_secure_random_bytes());
787 macro_rules! abandon_with_entry {
788 ($payment: expr, $reason: expr) => {
789 $payment.get_mut().mark_abandoned($reason);
790 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
791 if $payment.get().remaining_parts() == 0 {
792 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
802 let (total_msat, recipient_onion, keysend_preimage) = {
803 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
804 match outbounds.entry(payment_id) {
805 hash_map::Entry::Occupied(mut payment) => {
806 let res = match payment.get() {
807 PendingOutboundPayment::Retryable {
808 total_msat, keysend_preimage, payment_secret, payment_metadata,
809 custom_tlvs, pending_amt_msat, ..
811 let retry_amt_msat = route.get_total_amount();
812 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
813 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);
814 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
817 (*total_msat, RecipientOnionFields {
818 payment_secret: *payment_secret,
819 payment_metadata: payment_metadata.clone(),
820 custom_tlvs: custom_tlvs.clone(),
821 }, *keysend_preimage)
823 PendingOutboundPayment::Legacy { .. } => {
824 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
827 PendingOutboundPayment::Fulfilled { .. } => {
828 log_error!(logger, "Payment already completed");
831 PendingOutboundPayment::Abandoned { .. } => {
832 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
836 if !payment.get().is_retryable_now() {
837 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
838 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
841 payment.get_mut().increment_attempts();
842 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
843 assert!(payment.get_mut().insert(*session_priv_bytes, path));
847 hash_map::Entry::Vacant(_) => {
848 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
853 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
854 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
855 &send_payment_along_path);
856 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
857 if let Err(e) = res {
858 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);
862 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
863 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
864 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
865 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
866 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
870 ES::Target: EntropySource,
871 NS::Target: NodeSigner,
873 IH: Fn() -> InFlightHtlcs,
874 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
877 PaymentSendFailure::AllFailedResendSafe(errs) => {
878 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);
879 self.retry_payment_internal(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);
881 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
882 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
883 // Some paths were sent, even if we failed to send the full MPP value our recipient may
884 // misbehave and claim the funds, at which point we have to consider the payment sent, so
885 // return `Ok()` here, ignoring any retry errors.
886 self.retry_payment_internal(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
888 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
889 // This may happen if we send a payment and some paths fail, but only due to a temporary
890 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
891 // initial HTLC-Add messages yet.
893 PaymentSendFailure::PathParameterError(results) => {
894 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
895 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
896 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
898 PaymentSendFailure::ParameterError(e) => {
899 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
900 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
902 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
906 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
907 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
908 paths: Vec<Path>, path_results: I, logger: &L,
909 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
910 ) where L::Target: Logger {
911 let mut events = pending_events.lock().unwrap();
912 debug_assert_eq!(paths.len(), path_results.len());
913 for (path, path_res) in paths.into_iter().zip(path_results) {
914 if let Err(e) = path_res {
915 if let APIError::MonitorUpdateInProgress = e { continue }
916 log_error!(logger, "Failed to send along path due to error: {:?}", e);
917 let mut failed_scid = None;
918 if let APIError::ChannelUnavailable { .. } = e {
919 let scid = path.hops[0].short_channel_id;
920 failed_scid = Some(scid);
921 route_params.payment_params.previously_failed_channels.push(scid);
923 events.push_back((events::Event::PaymentPathFailed {
924 payment_id: Some(payment_id),
926 payment_failed_permanently: false,
927 failure: events::PathFailure::InitialSend { err: e },
929 short_channel_id: failed_scid,
939 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
940 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
941 best_block_height: u32, send_payment_along_path: F
942 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
944 ES::Target: EntropySource,
945 NS::Target: NodeSigner,
946 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
948 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
950 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
952 if path.hops.len() < 2 && path.blinded_tail.is_none() {
953 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
954 err: "No need probing a path with less than two hops".to_string()
958 let route = Route { paths: vec![path], payment_params: None };
959 let onion_session_privs = self.add_new_pending_payment(payment_hash,
960 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
961 entropy_source, best_block_height)?;
963 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
964 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
966 Ok(()) => Ok((payment_hash, payment_id)),
968 self.remove_outbound_if_all_failed(payment_id, &e);
975 pub(super) fn test_set_payment_metadata(
976 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
978 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
979 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
980 *payment_metadata = new_payment_metadata;
982 _ => panic!("Need a retryable payment to update metadata on"),
987 pub(super) fn test_add_new_pending_payment<ES: Deref>(
988 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
989 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
990 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
991 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
994 pub(super) fn add_new_pending_payment<ES: Deref>(
995 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
996 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
997 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
998 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
999 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1000 for _ in 0..route.paths.len() {
1001 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1004 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1005 match pending_outbounds.entry(payment_id) {
1006 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1007 hash_map::Entry::Vacant(entry) => {
1008 let payment = entry.insert(PendingOutboundPayment::Retryable {
1010 attempts: PaymentAttempts::new(),
1012 session_privs: HashSet::new(),
1013 pending_amt_msat: 0,
1014 pending_fee_msat: Some(0),
1016 payment_secret: recipient_onion.payment_secret,
1017 payment_metadata: recipient_onion.payment_metadata,
1019 custom_tlvs: recipient_onion.custom_tlvs,
1020 starting_block_height: best_block_height,
1021 total_msat: route.get_total_amount(),
1024 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1025 assert!(payment.insert(*session_priv_bytes, path));
1028 Ok(onion_session_privs)
1033 fn pay_route_internal<NS: Deref, F>(
1034 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1035 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1036 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1037 send_payment_along_path: &F
1038 ) -> Result<(), PaymentSendFailure>
1040 NS::Target: NodeSigner,
1041 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1043 if route.paths.len() < 1 {
1044 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1046 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
1047 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1049 let mut total_value = 0;
1050 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1051 let mut path_errs = Vec::with_capacity(route.paths.len());
1052 'path_check: for path in route.paths.iter() {
1053 if path.hops.len() < 1 || path.hops.len() > 20 {
1054 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1055 continue 'path_check;
1057 if path.blinded_tail.is_some() {
1058 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1059 continue 'path_check;
1061 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1062 usize::max_value() } else { path.hops.len() - 1 };
1063 for (idx, hop) in path.hops.iter().enumerate() {
1064 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1065 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1066 continue 'path_check;
1069 total_value += path.final_value_msat();
1070 path_errs.push(Ok(()));
1072 if path_errs.iter().any(|e| e.is_err()) {
1073 return Err(PaymentSendFailure::PathParameterError(path_errs));
1075 if let Some(amt_msat) = recv_value_msat {
1076 total_value = amt_msat;
1079 let cur_height = best_block_height + 1;
1080 let mut results = Vec::new();
1081 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1082 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1083 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1084 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1085 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1089 Err(APIError::MonitorUpdateInProgress) => {
1090 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1091 // considered "in flight" and we shouldn't remove it from the
1092 // PendingOutboundPayment set.
1095 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1096 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1097 let removed = payment.remove(&session_priv_bytes, Some(path));
1098 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1100 debug_assert!(false, "This can't happen as the payment was added by callers");
1101 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1105 results.push(path_res);
1107 let mut has_ok = false;
1108 let mut has_err = false;
1109 let mut pending_amt_unsent = 0;
1110 for (res, path) in results.iter().zip(route.paths.iter()) {
1111 if res.is_ok() { has_ok = true; }
1112 if res.is_err() { has_err = true; }
1113 if let &Err(APIError::MonitorUpdateInProgress) = res {
1114 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1118 } else if res.is_err() {
1119 pending_amt_unsent += path.final_value_msat();
1122 if has_err && has_ok {
1123 Err(PaymentSendFailure::PartialFailure {
1126 failed_paths_retry: if pending_amt_unsent != 0 {
1127 if let Some(payment_params) = &route.payment_params {
1128 Some(RouteParameters {
1129 payment_params: payment_params.clone(),
1130 final_value_msat: pending_amt_unsent,
1136 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1143 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1144 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1145 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1146 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1147 send_payment_along_path: F
1148 ) -> Result<(), PaymentSendFailure>
1150 NS::Target: NodeSigner,
1151 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1153 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1154 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1155 &send_payment_along_path)
1156 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1159 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1160 // map as the payment is free to be resent.
1161 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1162 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1163 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1164 debug_assert!(removed, "We should always have a pending payment to remove here");
1168 pub(super) fn claim_htlc<L: Deref>(
1169 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1170 path: Path, from_onchain: bool,
1171 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1173 ) where L::Target: Logger {
1174 let mut session_priv_bytes = [0; 32];
1175 session_priv_bytes.copy_from_slice(&session_priv[..]);
1176 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1177 let mut pending_events = pending_events.lock().unwrap();
1178 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1179 if !payment.get().is_fulfilled() {
1180 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1181 let fee_paid_msat = payment.get().get_pending_fee_msat();
1182 pending_events.push_back((events::Event::PaymentSent {
1183 payment_id: Some(payment_id),
1188 payment.get_mut().mark_fulfilled();
1192 // We currently immediately remove HTLCs which were fulfilled on-chain.
1193 // This could potentially lead to removing a pending payment too early,
1194 // with a reorg of one block causing us to re-add the fulfilled payment on
1196 // TODO: We should have a second monitor event that informs us of payments
1197 // irrevocably fulfilled.
1198 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1199 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1200 pending_events.push_back((events::Event::PaymentPathSuccessful {
1208 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1212 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1213 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1215 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1216 let mut pending_events = pending_events.lock().unwrap();
1217 for source in sources {
1218 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1219 let mut session_priv_bytes = [0; 32];
1220 session_priv_bytes.copy_from_slice(&session_priv[..]);
1221 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1222 assert!(payment.get().is_fulfilled());
1223 if payment.get_mut().remove(&session_priv_bytes, None) {
1224 let payment_hash = payment.get().payment_hash();
1225 debug_assert!(payment_hash.is_some());
1226 pending_events.push_back((events::Event::PaymentPathSuccessful {
1237 pub(super) fn remove_stale_resolved_payments(&self,
1238 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1240 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1241 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1242 // this could race the user making a duplicate send_payment call and our idempotency
1243 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1244 // removal. This should be more than sufficient to ensure the idempotency of any
1245 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1247 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1248 let pending_events = pending_events.lock().unwrap();
1249 pending_outbound_payments.retain(|payment_id, payment| {
1250 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1251 let mut no_remaining_entries = session_privs.is_empty();
1252 if no_remaining_entries {
1253 for (ev, _) in pending_events.iter() {
1255 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1256 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1257 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1258 if payment_id == ev_payment_id {
1259 no_remaining_entries = false;
1267 if no_remaining_entries {
1268 *timer_ticks_without_htlcs += 1;
1269 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1271 *timer_ticks_without_htlcs = 0;
1278 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1279 pub(super) fn fail_htlc<L: Deref>(
1280 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1281 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1282 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1283 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1284 ) -> bool where L::Target: Logger {
1286 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1288 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1290 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1291 let mut session_priv_bytes = [0; 32];
1292 session_priv_bytes.copy_from_slice(&session_priv[..]);
1293 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1295 // If any payments already need retry, there's no need to generate a redundant
1296 // `PendingHTLCsForwardable`.
1297 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1298 let mut awaiting_retry = false;
1299 if pmt.is_auto_retryable_now() {
1300 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1301 if pending_amt_msat < total_msat {
1302 awaiting_retry = true;
1309 let mut full_failure_ev = None;
1310 let mut pending_retry_ev = false;
1311 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1312 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1313 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1316 if payment.get().is_fulfilled() {
1317 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1320 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1321 if let Some(scid) = short_channel_id {
1322 // TODO: If we decided to blame ourselves (or one of our channels) in
1323 // process_onion_failure we should close that channel as it implies our
1324 // next-hop is needlessly blaming us!
1325 payment.get_mut().insert_previously_failed_scid(scid);
1328 if payment_is_probe || !is_retryable_now || !payment_retryable {
1329 let reason = if !payment_retryable {
1330 PaymentFailureReason::RecipientRejected
1332 PaymentFailureReason::RetriesExhausted
1334 payment.get_mut().mark_abandoned(reason);
1335 is_retryable_now = false;
1337 if payment.get().remaining_parts() == 0 {
1338 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1339 if !payment_is_probe {
1340 full_failure_ev = Some(events::Event::PaymentFailed {
1341 payment_id: *payment_id,
1342 payment_hash: *payment_hash,
1351 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1354 core::mem::drop(outbounds);
1355 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1357 let path_failure = {
1358 if payment_is_probe {
1359 if !payment_retryable {
1360 events::Event::ProbeSuccessful {
1361 payment_id: *payment_id,
1362 payment_hash: payment_hash.clone(),
1366 events::Event::ProbeFailed {
1367 payment_id: *payment_id,
1368 payment_hash: payment_hash.clone(),
1374 // If we miss abandoning the payment above, we *must* generate an event here or else the
1375 // payment will sit in our outbounds forever.
1376 if attempts_remaining && !already_awaiting_retry {
1377 debug_assert!(full_failure_ev.is_none());
1378 pending_retry_ev = true;
1380 events::Event::PaymentPathFailed {
1381 payment_id: Some(*payment_id),
1382 payment_hash: payment_hash.clone(),
1383 payment_failed_permanently: !payment_retryable,
1384 failure: events::PathFailure::OnPath { network_update },
1388 error_code: onion_error_code,
1390 error_data: onion_error_data
1394 let mut pending_events = pending_events.lock().unwrap();
1395 pending_events.push_back((path_failure, None));
1396 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1400 pub(super) fn abandon_payment(
1401 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1402 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1404 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1405 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1406 payment.get_mut().mark_abandoned(reason);
1407 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1408 if payment.get().remaining_parts() == 0 {
1409 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1411 payment_hash: *payment_hash,
1421 pub fn has_pending_payments(&self) -> bool {
1422 !self.pending_outbound_payments.lock().unwrap().is_empty()
1426 pub fn clear_pending_payments(&self) {
1427 self.pending_outbound_payments.lock().unwrap().clear()
1431 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1433 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1434 probing_cookie_secret: [u8; 32]) -> bool
1436 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1437 target_payment_hash == *payment_hash
1440 /// Returns the 'probing cookie' for the given [`PaymentId`].
1441 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1442 let mut preimage = [0u8; 64];
1443 preimage[..32].copy_from_slice(&probing_cookie_secret);
1444 preimage[32..].copy_from_slice(&payment_id.0);
1445 PaymentHash(Sha256::hash(&preimage).into_inner())
1448 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1450 (0, session_privs, required),
1453 (0, session_privs, required),
1454 (1, payment_hash, option),
1455 (3, timer_ticks_without_htlcs, (default_value, 0)),
1458 (0, session_privs, required),
1459 (1, pending_fee_msat, option),
1460 (2, payment_hash, required),
1461 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1462 // never see it - `payment_params` was added here after the field was added/required.
1463 (3, payment_params, (option: ReadableArgs, 0)),
1464 (4, payment_secret, option),
1465 (5, keysend_preimage, option),
1466 (6, total_msat, required),
1467 (7, payment_metadata, option),
1468 (8, pending_amt_msat, required),
1469 (9, custom_tlvs, optional_vec),
1470 (10, starting_block_height, required),
1471 (not_written, retry_strategy, (static_value, None)),
1472 (not_written, attempts, (static_value, PaymentAttempts::new())),
1475 (0, session_privs, required),
1476 (1, reason, option),
1477 (2, payment_hash, required),
1483 use bitcoin::network::constants::Network;
1484 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1486 use crate::events::{Event, PathFailure, PaymentFailureReason};
1487 use crate::ln::PaymentHash;
1488 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1489 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1490 use crate::ln::msgs::{ErrorAction, LightningError};
1491 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1492 use crate::routing::gossip::NetworkGraph;
1493 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1494 use crate::sync::{Arc, Mutex};
1495 use crate::util::errors::APIError;
1496 use crate::util::test_utils;
1498 use alloc::collections::VecDeque;
1501 fn test_recipient_onion_fields_with_custom_tlvs() {
1502 let onion_fields = RecipientOnionFields::spontaneous_empty();
1504 let bad_type_range_tlvs = vec![
1508 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1510 let keysend_tlv = vec![
1511 (5482373484, vec![42; 32]),
1513 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1515 let good_tlvs = vec![
1516 ((1 << 16) + 1, vec![42]),
1517 ((1 << 16) + 3, vec![42; 32]),
1519 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1523 #[cfg(feature = "std")]
1524 fn fails_paying_after_expiration() {
1525 do_fails_paying_after_expiration(false);
1526 do_fails_paying_after_expiration(true);
1528 #[cfg(feature = "std")]
1529 fn do_fails_paying_after_expiration(on_retry: bool) {
1530 let outbound_payments = OutboundPayments::new();
1531 let logger = test_utils::TestLogger::new();
1532 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1533 let scorer = Mutex::new(test_utils::TestScorer::new());
1534 let router = test_utils::TestRouter::new(network_graph, &scorer);
1535 let secp_ctx = Secp256k1::new();
1536 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1538 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1539 let payment_params = PaymentParameters::from_node_id(
1540 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1542 ).with_expiry_time(past_expiry_time);
1543 let expired_route_params = RouteParameters {
1545 final_value_msat: 0,
1547 let pending_events = Mutex::new(VecDeque::new());
1549 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1550 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1551 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1552 &&keys_manager, 0).unwrap();
1553 outbound_payments.retry_payment_internal(
1554 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1555 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1557 let events = pending_events.lock().unwrap();
1558 assert_eq!(events.len(), 1);
1559 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1560 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1561 } else { panic!("Unexpected event"); }
1563 let err = outbound_payments.send_payment(
1564 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1565 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1566 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1567 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1572 fn find_route_error() {
1573 do_find_route_error(false);
1574 do_find_route_error(true);
1576 fn do_find_route_error(on_retry: bool) {
1577 let outbound_payments = OutboundPayments::new();
1578 let logger = test_utils::TestLogger::new();
1579 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1580 let scorer = Mutex::new(test_utils::TestScorer::new());
1581 let router = test_utils::TestRouter::new(network_graph, &scorer);
1582 let secp_ctx = Secp256k1::new();
1583 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1585 let payment_params = PaymentParameters::from_node_id(
1586 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1587 let route_params = RouteParameters {
1589 final_value_msat: 0,
1591 router.expect_find_route(route_params.clone(),
1592 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1594 let pending_events = Mutex::new(VecDeque::new());
1596 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1597 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1598 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1599 &&keys_manager, 0).unwrap();
1600 outbound_payments.retry_payment_internal(
1601 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1602 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1604 let events = pending_events.lock().unwrap();
1605 assert_eq!(events.len(), 1);
1606 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1608 let err = outbound_payments.send_payment(
1609 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1610 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1611 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1612 if let RetryableSendFailure::RouteNotFound = err {
1613 } else { panic!("Unexpected error"); }
1618 fn initial_send_payment_path_failed_evs() {
1619 let outbound_payments = OutboundPayments::new();
1620 let logger = test_utils::TestLogger::new();
1621 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1622 let scorer = Mutex::new(test_utils::TestScorer::new());
1623 let router = test_utils::TestRouter::new(network_graph, &scorer);
1624 let secp_ctx = Secp256k1::new();
1625 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1627 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1628 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1629 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1630 let route_params = RouteParameters {
1631 payment_params: payment_params.clone(),
1632 final_value_msat: 0,
1634 let failed_scid = 42;
1636 paths: vec![Path { hops: vec![RouteHop {
1637 pubkey: receiver_pk,
1638 node_features: NodeFeatures::empty(),
1639 short_channel_id: failed_scid,
1640 channel_features: ChannelFeatures::empty(),
1642 cltv_expiry_delta: 0,
1643 }], blinded_tail: None }],
1644 payment_params: Some(payment_params),
1646 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1647 let mut route_params_w_failed_scid = route_params.clone();
1648 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1649 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1650 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1651 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1653 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1654 // PaymentPathFailed event.
1655 let pending_events = Mutex::new(VecDeque::new());
1656 outbound_payments.send_payment(
1657 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1658 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1659 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1660 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1661 let mut events = pending_events.lock().unwrap();
1662 assert_eq!(events.len(), 2);
1663 if let Event::PaymentPathFailed {
1665 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1667 assert_eq!(short_channel_id, Some(failed_scid));
1668 } else { panic!("Unexpected event"); }
1669 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1671 core::mem::drop(events);
1673 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1674 outbound_payments.send_payment(
1675 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1676 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1677 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1678 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1679 assert_eq!(pending_events.lock().unwrap().len(), 0);
1681 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1682 outbound_payments.send_payment(
1683 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1684 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1685 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1686 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1687 let events = pending_events.lock().unwrap();
1688 assert_eq!(events.len(), 2);
1689 if let Event::PaymentPathFailed {
1691 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1693 assert_eq!(short_channel_id, None);
1694 } else { panic!("Unexpected event"); }
1695 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }