lightning/ln/
outbound_payment.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Utilities to send payments and manage outbound payment information.
11
12use bitcoin::hashes::sha256::Hash as Sha256;
13use bitcoin::hashes::Hash;
14use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
15use lightning_invoice::Bolt11Invoice;
16
17use crate::blinded_path::{IntroductionNode, NodeIdLookUp};
18use crate::events::{self, PaidBolt12Invoice, PaymentFailureReason};
19use crate::ln::channel_state::ChannelDetails;
20use crate::ln::channelmanager::{
21	EventCompletionAction, HTLCSource, PaymentCompleteUpdate, PaymentId,
22};
23use crate::ln::onion_utils;
24use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
25use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder};
26use crate::offers::invoice_request::InvoiceRequest;
27use crate::offers::nonce::Nonce;
28use crate::offers::static_invoice::StaticInvoice;
29use crate::routing::router::{
30	BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters,
31	RouteParametersConfig, Router,
32};
33use crate::sign::{EntropySource, NodeSigner, Recipient};
34use crate::types::features::Bolt12InvoiceFeatures;
35use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
36use crate::util::errors::APIError;
37use crate::util::logger::Logger;
38use crate::util::ser::ReadableArgs;
39#[cfg(feature = "std")]
40use crate::util::time::Instant;
41
42use core::fmt::{self, Display, Formatter};
43use core::ops::Deref;
44use core::sync::atomic::{AtomicBool, Ordering};
45use core::time::Duration;
46
47use crate::prelude::*;
48use crate::sync::Mutex;
49
50/// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
51/// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
52///
53/// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
54pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
55
56/// The default relative expiration to wait for a pending outbound HTLC to a often-offline
57/// payee to fulfill.
58const ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY: Duration = Duration::from_secs(60 * 60 * 24 * 7);
59
60#[cfg(test)]
61pub(crate) const TEST_ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY: Duration =
62	ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY;
63
64/// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
65/// and later, also stores information for retrying the payment.
66pub(crate) enum PendingOutboundPayment {
67	Legacy {
68		session_privs: HashSet<[u8; 32]>,
69	},
70	/// Used when we are waiting for an Offer to come back from a BIP 353 resolution
71	AwaitingOffer {
72		expiration: StaleExpiration,
73		retry_strategy: Retry,
74		route_params_config: RouteParametersConfig,
75		/// Human Readable Names-originated payments should always specify an explicit amount to
76		/// send up-front, which we track here and enforce once we receive the offer.
77		amount_msats: u64,
78		payer_note: Option<String>,
79	},
80	AwaitingInvoice {
81		expiration: StaleExpiration,
82		retry_strategy: Retry,
83		route_params_config: RouteParametersConfig,
84		retryable_invoice_request: Option<RetryableInvoiceRequest>,
85	},
86	// Represents the state after the invoice has been received, transitioning from the corresponding
87	// `AwaitingInvoice` state.
88	// Helps avoid holding the `OutboundPayments::pending_outbound_payments` lock during pathfinding.
89	InvoiceReceived {
90		payment_hash: PaymentHash,
91		retry_strategy: Retry,
92		// Currently unused, but replicated from `AwaitingInvoice` to avoid potential
93		// race conditions where this field might be missing upon reload. It may be required
94		// for future retries.
95		route_params_config: RouteParametersConfig,
96	},
97	// This state applies when we are paying an often-offline recipient and another node on the
98	// network served us a static invoice on the recipient's behalf in response to our invoice
99	// request. As a result, once a payment gets in this state it will remain here until the recipient
100	// comes back online, which may take hours or even days.
101	StaticInvoiceReceived {
102		payment_hash: PaymentHash,
103		keysend_preimage: PaymentPreimage,
104		retry_strategy: Retry,
105		route_params: RouteParameters,
106		invoice_request: InvoiceRequest,
107		static_invoice: StaticInvoice,
108		// The deadline as duration since the Unix epoch for the async recipient to come online,
109		// after which we'll fail the payment.
110		//
111		// Defaults to creation time + [`ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY`].
112		expiry_time: Duration,
113	},
114	Retryable {
115		retry_strategy: Option<Retry>,
116		attempts: PaymentAttempts,
117		payment_params: Option<PaymentParameters>,
118		session_privs: HashSet<[u8; 32]>,
119		payment_hash: PaymentHash,
120		payment_secret: Option<PaymentSecret>,
121		payment_metadata: Option<Vec<u8>>,
122		keysend_preimage: Option<PaymentPreimage>,
123		invoice_request: Option<InvoiceRequest>,
124		// Storing the BOLT 12 invoice here to allow Proof of Payment after
125		// the payment is made.
126		bolt12_invoice: Option<PaidBolt12Invoice>,
127		custom_tlvs: Vec<(u64, Vec<u8>)>,
128		pending_amt_msat: u64,
129		/// Used to track the fee paid. Present iff the payment was serialized on 0.0.103+.
130		pending_fee_msat: Option<u64>,
131		/// The total payment amount across all paths, used to verify that a retry is not overpaying.
132		total_msat: u64,
133		/// Our best known block height at the time this payment was initiated.
134		starting_block_height: u32,
135		remaining_max_total_routing_fee_msat: Option<u64>,
136	},
137	/// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
138	/// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
139	/// and add a pending payment that was already fulfilled.
140	Fulfilled {
141		session_privs: HashSet<[u8; 32]>,
142		/// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
143		payment_hash: Option<PaymentHash>,
144		timer_ticks_without_htlcs: u8,
145		/// The total payment amount across all paths, used to be able to issue `PaymentSent`.
146		total_msat: Option<u64>,
147	},
148	/// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
149	/// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
150	Abandoned {
151		session_privs: HashSet<[u8; 32]>,
152		payment_hash: PaymentHash,
153		/// Will be `None` if the payment was serialized before 0.0.115 or if downgrading to 0.0.124
154		/// or later with a reason that was added after.
155		reason: Option<PaymentFailureReason>,
156		/// The total payment amount across all paths, used to be able to issue `PaymentSent` if
157		/// an HTLC still happens to succeed after we marked the payment as abandoned.
158		total_msat: Option<u64>,
159	},
160}
161
162#[derive(Clone)]
163pub(crate) struct RetryableInvoiceRequest {
164	pub(crate) invoice_request: InvoiceRequest,
165	pub(crate) nonce: Nonce,
166	pub(super) needs_retry: bool,
167}
168
169impl_writeable_tlv_based!(RetryableInvoiceRequest, {
170	(0, invoice_request, required),
171	(1, needs_retry, (default_value, true)),
172	(2, nonce, required),
173});
174
175impl PendingOutboundPayment {
176	fn bolt12_invoice(&self) -> Option<&PaidBolt12Invoice> {
177		match self {
178			PendingOutboundPayment::Retryable { bolt12_invoice, .. } => bolt12_invoice.as_ref(),
179			_ => None,
180		}
181	}
182
183	fn increment_attempts(&mut self) {
184		if let PendingOutboundPayment::Retryable { attempts, .. } = self {
185			attempts.count += 1;
186		}
187	}
188	#[rustfmt::skip]
189	fn is_auto_retryable_now(&self) -> bool {
190		match self {
191			PendingOutboundPayment::Retryable {
192				retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
193			} => {
194				strategy.is_retryable_now(&attempts)
195			},
196			_ => false,
197		}
198	}
199	#[rustfmt::skip]
200	fn is_retryable_now(&self) -> bool {
201		match self {
202			PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
203				// We're handling retries manually, we can always retry.
204				true
205			},
206			PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
207				strategy.is_retryable_now(&attempts)
208			},
209			_ => false,
210		}
211	}
212	pub fn insert_previously_failed_scid(&mut self, scid: u64) {
213		if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
214			params.previously_failed_channels.push(scid);
215		}
216	}
217	pub fn insert_previously_failed_blinded_path(&mut self, blinded_tail: &BlindedTail) {
218		if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
219			params.insert_previously_failed_blinded_path(blinded_tail);
220		}
221	}
222	// Used for payments to BOLT 12 offers where we are either waiting for an invoice or have an
223	// invoice but have not locked in HTLCs for the payment yet.
224	fn is_pre_htlc_lock_in(&self) -> bool {
225		match self {
226			PendingOutboundPayment::AwaitingInvoice { .. }
227			| PendingOutboundPayment::InvoiceReceived { .. }
228			| PendingOutboundPayment::StaticInvoiceReceived { .. } => true,
229			_ => false,
230		}
231	}
232	pub(super) fn is_fulfilled(&self) -> bool {
233		match self {
234			PendingOutboundPayment::Fulfilled { .. } => true,
235			_ => false,
236		}
237	}
238	pub(super) fn abandoned(&self) -> bool {
239		match self {
240			PendingOutboundPayment::Abandoned { .. } => true,
241			_ => false,
242		}
243	}
244	fn get_pending_fee_msat(&self) -> Option<u64> {
245		match self {
246			PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
247			_ => None,
248		}
249	}
250
251	fn total_msat(&self) -> Option<u64> {
252		match self {
253			PendingOutboundPayment::Retryable { total_msat, .. } => Some(*total_msat),
254			PendingOutboundPayment::Fulfilled { total_msat, .. } => *total_msat,
255			PendingOutboundPayment::Abandoned { total_msat, .. } => *total_msat,
256			_ => None,
257		}
258	}
259
260	#[rustfmt::skip]
261	fn payment_hash(&self) -> Option<PaymentHash> {
262		match self {
263			PendingOutboundPayment::Legacy { .. } => None,
264			PendingOutboundPayment::AwaitingOffer { .. } => None,
265			PendingOutboundPayment::AwaitingInvoice { .. } => None,
266			PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
267			PendingOutboundPayment::StaticInvoiceReceived { payment_hash, .. } => Some(*payment_hash),
268			PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
269			PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
270			PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
271		}
272	}
273
274	#[rustfmt::skip]
275	fn mark_fulfilled(&mut self) {
276		let mut session_privs = new_hash_set();
277		core::mem::swap(&mut session_privs, match self {
278			PendingOutboundPayment::Legacy { session_privs } |
279				PendingOutboundPayment::Retryable { session_privs, .. } |
280				PendingOutboundPayment::Fulfilled { session_privs, .. } |
281				PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
282			PendingOutboundPayment::AwaitingOffer { .. } |
283				PendingOutboundPayment::AwaitingInvoice { .. } |
284				PendingOutboundPayment::InvoiceReceived { .. } |
285				PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); return; },
286		});
287		let payment_hash = self.payment_hash();
288		let total_msat = self.total_msat();
289		*self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0, total_msat };
290	}
291
292	#[rustfmt::skip]
293	fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
294		let session_privs = match self {
295			PendingOutboundPayment::Retryable { session_privs, .. } => {
296				let mut our_session_privs = new_hash_set();
297				core::mem::swap(&mut our_session_privs, session_privs);
298				our_session_privs
299			},
300			_ => new_hash_set(),
301		};
302		let total_msat = self.total_msat();
303		match self {
304			Self::Retryable { payment_hash, .. } |
305				Self::InvoiceReceived { payment_hash, .. } |
306				Self::StaticInvoiceReceived { payment_hash, .. } =>
307			{
308				*self = Self::Abandoned {
309					session_privs,
310					payment_hash: *payment_hash,
311					reason: Some(reason),
312					total_msat,
313				};
314			},
315			_ => {}
316		}
317	}
318
319	/// panics if path is None and !self.is_fulfilled
320	#[rustfmt::skip]
321	fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
322		let remove_res = match self {
323			PendingOutboundPayment::Legacy { session_privs } |
324				PendingOutboundPayment::Retryable { session_privs, .. } |
325				PendingOutboundPayment::Fulfilled { session_privs, .. } |
326				PendingOutboundPayment::Abandoned { session_privs, .. } => {
327					session_privs.remove(session_priv)
328				},
329			PendingOutboundPayment::AwaitingOffer { .. } |
330				PendingOutboundPayment::AwaitingInvoice { .. } |
331				PendingOutboundPayment::InvoiceReceived { .. } |
332				PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
333		};
334		if remove_res {
335			if let PendingOutboundPayment::Retryable {
336				ref mut pending_amt_msat, ref mut pending_fee_msat,
337				ref mut remaining_max_total_routing_fee_msat, ..
338			} = self {
339				let path = path.expect("Removing a failed payment should always come with a path");
340				*pending_amt_msat -= path.final_value_msat();
341				let path_fee_msat = path.fee_msat();
342				if let Some(fee_msat) = pending_fee_msat.as_mut() {
343					*fee_msat -= path_fee_msat;
344				}
345
346				if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
347					*max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
348				}
349			}
350		}
351		remove_res
352	}
353
354	#[rustfmt::skip]
355	pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
356		let insert_res = match self {
357			PendingOutboundPayment::Legacy { session_privs } |
358				PendingOutboundPayment::Retryable { session_privs, .. } => {
359					session_privs.insert(session_priv)
360				},
361			PendingOutboundPayment::AwaitingOffer { .. } |
362				PendingOutboundPayment::AwaitingInvoice { .. } |
363				PendingOutboundPayment::InvoiceReceived { .. } |
364				PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
365			PendingOutboundPayment::Fulfilled { .. } => false,
366			PendingOutboundPayment::Abandoned { .. } => false,
367		};
368		if insert_res {
369			if let PendingOutboundPayment::Retryable {
370				ref mut pending_amt_msat, ref mut pending_fee_msat,
371				ref mut remaining_max_total_routing_fee_msat, ..
372			} = self {
373					*pending_amt_msat += path.final_value_msat();
374					let path_fee_msat = path.fee_msat();
375					if let Some(fee_msat) = pending_fee_msat.as_mut() {
376						*fee_msat += path_fee_msat;
377					}
378
379					if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
380						*max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
381					}
382			}
383		}
384		insert_res
385	}
386
387	#[rustfmt::skip]
388	pub(super) fn remaining_parts(&self) -> usize {
389		match self {
390			PendingOutboundPayment::Legacy { session_privs } |
391				PendingOutboundPayment::Retryable { session_privs, .. } |
392				PendingOutboundPayment::Fulfilled { session_privs, .. } |
393				PendingOutboundPayment::Abandoned { session_privs, .. } => {
394					session_privs.len()
395				},
396			PendingOutboundPayment::AwaitingInvoice { .. } => 0,
397			PendingOutboundPayment::AwaitingOffer { .. } => 0,
398			PendingOutboundPayment::InvoiceReceived { .. } => 0,
399			PendingOutboundPayment::StaticInvoiceReceived { .. } => 0,
400		}
401	}
402}
403
404/// Strategies available to retry payment path failures.
405#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
406pub enum Retry {
407	/// Max number of attempts to retry payment.
408	///
409	/// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
410	/// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
411	/// were retried along a route from a single call to [`Router::find_route_with_id`].
412	Attempts(u32),
413	#[cfg(feature = "std")]
414	/// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
415	/// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
416	///
417	/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
418	Timeout(core::time::Duration),
419}
420
421#[cfg(not(feature = "std"))]
422impl_writeable_tlv_based_enum_legacy!(Retry,
423	;
424	(0, Attempts)
425);
426
427#[cfg(feature = "std")]
428impl_writeable_tlv_based_enum_legacy!(Retry,
429	;
430	(0, Attempts),
431	(2, Timeout)
432);
433
434impl Retry {
435	#[rustfmt::skip]
436	pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
437		match (self, attempts) {
438			(Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
439				max_retry_count > count
440			},
441			#[cfg(feature = "std")]
442			(Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
443				*max_duration >= Instant::now().duration_since(*first_attempted_at),
444		}
445	}
446}
447
448#[cfg(feature = "std")]
449#[rustfmt::skip]
450pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
451	if let Some(expiry_time) = route_params.payment_params.expiry_time {
452		if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
453			return elapsed > core::time::Duration::from_secs(expiry_time)
454		}
455	}
456	false
457}
458
459/// Storing minimal payment attempts information required for determining if a outbound payment can
460/// be retried.
461pub(crate) struct PaymentAttempts {
462	/// This count will be incremented only after the result of the attempt is known. When it's 0,
463	/// it means the result of the first attempt is not known yet.
464	pub(crate) count: u32,
465	/// This field is only used when retry is `Retry::Timeout` which is only build with feature std
466	#[cfg(feature = "std")]
467	first_attempted_at: Instant,
468}
469
470impl PaymentAttempts {
471	pub(crate) fn new() -> Self {
472		PaymentAttempts {
473			count: 0,
474			#[cfg(feature = "std")]
475			first_attempted_at: Instant::now(),
476		}
477	}
478}
479
480impl Display for PaymentAttempts {
481	fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
482		#[cfg(not(feature = "std"))]
483		return write!(f, "attempts: {}", self.count);
484		#[cfg(feature = "std")]
485		return write!(
486			f,
487			"attempts: {}, duration: {}s",
488			self.count,
489			Instant::now().duration_since(self.first_attempted_at).as_secs()
490		);
491	}
492}
493
494/// How long before a [`PendingOutboundPayment::AwaitingInvoice`] or
495/// [`PendingOutboundPayment::AwaitingOffer`] should be considered stale and candidate for removal
496/// in [`OutboundPayments::remove_stale_payments`].
497#[derive(Clone, Copy)]
498pub(crate) enum StaleExpiration {
499	/// Number of times [`OutboundPayments::remove_stale_payments`] is called.
500	TimerTicks(u64),
501	/// Duration since the Unix epoch.
502	AbsoluteTimeout(core::time::Duration),
503}
504
505impl_writeable_tlv_based_enum_legacy!(StaleExpiration,
506	;
507	(0, TimerTicks),
508	(2, AbsoluteTimeout)
509);
510
511/// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
512/// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
513///
514/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
515/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
516/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
517#[derive(Clone, Debug, PartialEq, Eq)]
518pub enum RetryableSendFailure {
519	/// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired or
520	/// the BOLT 12 invoice paid to via [`ChannelManager::send_payment_for_bolt12_invoice`] was
521	/// expired.
522	#[cfg_attr(feature = "std", doc = "")]
523	#[cfg_attr(
524		feature = "std",
525		doc = "Note that this error is *not* caused by [`Retry::Timeout`]."
526	)]
527	///
528	/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
529	/// [`ChannelManager::send_payment_for_bolt12_invoice`]: crate::ln::channelmanager::ChannelManager::send_payment_for_bolt12_invoice
530	PaymentExpired,
531	/// We were unable to find a route to the destination.
532	RouteNotFound,
533	/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
534	/// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
535	///
536	/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
537	/// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
538	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
539	DuplicatePayment,
540	/// The [`RecipientOnionFields::payment_metadata`], [`RecipientOnionFields::custom_tlvs`], or
541	/// [`BlindedPaymentPath`]s provided are too large and caused us to exceed the maximum onion
542	/// packet size of 1300 bytes.
543	///
544	/// [`BlindedPaymentPath`]: crate::blinded_path::payment::BlindedPaymentPath
545	OnionPacketSizeExceeded,
546}
547
548/// If a payment fails to send to a route, it can be in one of several states. This enum is returned
549/// as the Err() type describing which state the payment is in, see the description of individual
550/// enum states for more.
551#[derive(Clone, Debug, PartialEq, Eq)]
552pub(crate) enum PaymentSendFailure {
553	/// A parameter which was passed to send_payment was invalid, preventing us from attempting to
554	/// send the payment at all.
555	///
556	/// You can freely resend the payment in full (with the parameter error fixed).
557	///
558	/// Because the payment failed outright, no payment tracking is done and no
559	/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
560	///
561	/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
562	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
563	ParameterError(APIError),
564	/// A parameter in a single path which was passed to send_payment was invalid, preventing us
565	/// from attempting to send the payment at all.
566	///
567	/// You can freely resend the payment in full (with the parameter error fixed).
568	///
569	/// Because the payment failed outright, no payment tracking is done and no
570	/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
571	///
572	/// The results here are ordered the same as the paths in the route object which was passed to
573	/// send_payment.
574	///
575	/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
576	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
577	PathParameterError(Vec<Result<(), APIError>>),
578	/// All paths which were attempted failed to send, with no channel state change taking place.
579	/// You can freely resend the payment in full (though you probably want to do so over different
580	/// paths than the ones selected).
581	///
582	/// Because the payment failed outright, no payment tracking is done and no
583	/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
584	///
585	/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
586	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
587	AllFailedResendSafe(Vec<APIError>),
588	/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
589	/// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
590	///
591	/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
592	/// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
593	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
594	DuplicatePayment,
595	/// Some paths that were attempted failed to send, though some paths may have succeeded. At least
596	/// some paths have irrevocably committed to the HTLC.
597	///
598	/// The results here are ordered the same as the paths in the route object that was passed to
599	/// send_payment.
600	///
601	/// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
602	/// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
603	///
604	/// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
605	PartialFailure {
606		/// The errors themselves, in the same order as the paths from the route.
607		results: Vec<Result<(), APIError>>,
608		/// If some paths failed without irrevocably committing to the new HTLC(s), this will
609		/// contain a [`RouteParameters`] object for the failing paths.
610		failed_paths_retry: Option<RouteParameters>,
611		/// The payment id for the payment, which is now at least partially pending.
612		payment_id: PaymentId,
613	},
614}
615
616/// An error when attempting to pay a [`Bolt11Invoice`].
617///
618/// [`Bolt11Invoice`]: lightning_invoice::Bolt11Invoice
619#[derive(Debug)]
620pub enum Bolt11PaymentError {
621	/// Incorrect amount was provided to [`ChannelManager::pay_for_bolt11_invoice`].
622	/// This happens when the user-provided amount is less than an amount specified in the [`Bolt11Invoice`].
623	///
624	/// [`Bolt11Invoice`]: lightning_invoice::Bolt11Invoice
625	/// [`ChannelManager::pay_for_bolt11_invoice`]: crate::ln::channelmanager::ChannelManager::pay_for_bolt11_invoice
626	InvalidAmount,
627	/// The invoice was valid for the corresponding [`PaymentId`], but sending the payment failed.
628	SendingFailed(RetryableSendFailure),
629}
630
631/// An error when attempting to pay a [`Bolt12Invoice`].
632#[derive(Clone, Debug, PartialEq, Eq)]
633pub enum Bolt12PaymentError {
634	/// The invoice was not requested.
635	UnexpectedInvoice,
636	/// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
637	DuplicateInvoice,
638	/// The invoice was valid for the corresponding [`PaymentId`], but required unknown features.
639	UnknownRequiredFeatures,
640	/// The invoice was valid for the corresponding [`PaymentId`], but sending the payment failed.
641	SendingFailed(RetryableSendFailure),
642	/// Failed to create a blinded path back to ourselves.
643	///
644	/// We attempted to initiate payment to a [`StaticInvoice`] but failed to create a reply path for
645	/// our [`HeldHtlcAvailable`] message.
646	///
647	/// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice
648	/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
649	BlindedPathCreationFailed,
650}
651
652/// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
653/// [`Event::ProbeFailed`].
654///
655/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
656#[derive(Clone, Debug, PartialEq, Eq)]
657pub enum ProbeSendFailure {
658	/// We were unable to find a route to the destination.
659	RouteNotFound,
660	/// A parameter which was passed to [`ChannelManager::send_probe`] was invalid, preventing us from
661	/// attempting to send the probe at all.
662	///
663	/// You can freely resend the probe (with the parameter error fixed).
664	///
665	/// Because the probe failed outright, no payment tracking is done and no
666	/// [`Event::ProbeFailed`] events will be generated.
667	///
668	/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
669	/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
670	ParameterError(APIError),
671	/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
672	/// yet completed (i.e. generated an [`Event::ProbeSuccessful`] or [`Event::ProbeFailed`]).
673	///
674	/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
675	/// [`Event::ProbeSuccessful`]: crate::events::Event::ProbeSuccessful
676	/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
677	DuplicateProbe,
678}
679
680/// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
681///
682/// This should generally be constructed with data communicated to us from the recipient (via a
683/// BOLT11 or BOLT12 invoice).
684#[derive(Clone, Debug, PartialEq, Eq)]
685pub struct RecipientOnionFields {
686	/// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
687	/// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
688	/// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
689	/// attacks.
690	///
691	/// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
692	/// multi-path payments require a recipient-provided secret.
693	///
694	/// Some implementations may reject spontaneous payments with payment secrets, so you may only
695	/// want to provide a secret for a spontaneous payment if MPP is needed and you know your
696	/// recipient will not reject it.
697	pub payment_secret: Option<PaymentSecret>,
698	/// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
699	/// arbitrary length. This gives recipients substantially more flexibility to receive
700	/// additional data.
701	///
702	/// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
703	/// scheme to authenticate received payments against expected payments and invoices, this field
704	/// is not used in LDK for received payments, and can be used to store arbitrary data in
705	/// invoices which will be received with the payment.
706	///
707	/// Note that this field was added to the lightning specification more recently than
708	/// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
709	/// may not be supported as universally.
710	pub payment_metadata: Option<Vec<u8>>,
711	/// See [`Self::custom_tlvs`] for more info.
712	pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
713}
714
715impl_writeable_tlv_based!(RecipientOnionFields, {
716	(0, payment_secret, option),
717	(1, custom_tlvs, optional_vec),
718	(2, payment_metadata, option),
719});
720
721impl RecipientOnionFields {
722	/// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
723	/// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
724	/// but do not require or provide any further data.
725	#[rustfmt::skip]
726	pub fn secret_only(payment_secret: PaymentSecret) -> Self {
727		Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
728	}
729
730	/// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
731	/// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
732	/// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
733	/// a spontaneous MPP this will not work as all MPP require payment secrets; you may
734	/// instead want to use [`RecipientOnionFields::secret_only`].
735	///
736	/// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
737	/// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
738	pub fn spontaneous_empty() -> Self {
739		Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
740	}
741
742	/// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
743	/// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
744	/// respectively. TLV type numbers must be unique and within the range
745	/// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
746	///
747	/// This method will also error for types in the experimental range which have been
748	/// standardized within the protocol, which only includes 5482373484 (keysend) for now.
749	///
750	/// See [`Self::custom_tlvs`] for more info.
751	#[rustfmt::skip]
752	pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
753		custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
754		let mut prev_type = None;
755		for (typ, _) in custom_tlvs.iter() {
756			if *typ < 1 << 16 { return Err(()); }
757			if *typ == 5482373484 { return Err(()); } // keysend
758			if *typ == 77_777 { return Err(()); } // invoice requests for async payments
759			match prev_type {
760				Some(prev) if prev >= *typ => return Err(()),
761				_ => {},
762			}
763			prev_type = Some(*typ);
764		}
765		self.custom_tlvs = custom_tlvs;
766		Ok(self)
767	}
768
769	/// Gets the custom TLVs that will be sent or have been received.
770	///
771	/// Custom TLVs allow sending extra application-specific data with a payment. They provide
772	/// additional flexibility on top of payment metadata, as while other implementations may
773	/// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
774	/// do not have this restriction.
775	///
776	/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
777	/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
778	/// This is validated when setting this field using [`Self::with_custom_tlvs`].
779	#[cfg(not(c_bindings))]
780	pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
781		&self.custom_tlvs
782	}
783
784	/// Gets the custom TLVs that will be sent or have been received.
785	///
786	/// Custom TLVs allow sending extra application-specific data with a payment. They provide
787	/// additional flexibility on top of payment metadata, as while other implementations may
788	/// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
789	/// do not have this restriction.
790	///
791	/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
792	/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
793	/// This is validated when setting this field using [`Self::with_custom_tlvs`].
794	#[cfg(c_bindings)]
795	pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
796		self.custom_tlvs.clone()
797	}
798
799	/// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
800	/// have to make sure that some fields match exactly across the parts. For those that aren't
801	/// required to match, if they don't match we should remove them so as to not expose data
802	/// that's dependent on the HTLC receive order to users.
803	///
804	/// Here we implement this, first checking compatibility then mutating two objects and then
805	/// dropping any remaining non-matching fields from both.
806	#[rustfmt::skip]
807	pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
808		if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
809		if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
810
811		let tlvs = &mut self.custom_tlvs;
812		let further_tlvs = &mut further_htlc_fields.custom_tlvs;
813
814		let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
815		let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
816		if even_tlvs.ne(further_even_tlvs) { return Err(()) }
817
818		tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
819		further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
820
821		Ok(())
822	}
823}
824
825/// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
826pub(super) struct SendAlongPathArgs<'a> {
827	pub path: &'a Path,
828	pub payment_hash: &'a PaymentHash,
829	pub recipient_onion: &'a RecipientOnionFields,
830	pub total_value: u64,
831	pub cur_height: u32,
832	pub payment_id: PaymentId,
833	pub keysend_preimage: &'a Option<PaymentPreimage>,
834	pub invoice_request: Option<&'a InvoiceRequest>,
835	pub bolt12_invoice: Option<&'a PaidBolt12Invoice>,
836	pub session_priv_bytes: [u8; 32],
837	pub hold_htlc_at_next_hop: bool,
838}
839
840pub(super) struct OutboundPayments<L: Deref>
841where
842	L::Target: Logger,
843{
844	pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
845	awaiting_invoice: AtomicBool,
846	retry_lock: Mutex<()>,
847	logger: L,
848}
849
850impl<L: Deref> OutboundPayments<L>
851where
852	L::Target: Logger,
853{
854	pub(super) fn new(
855		pending_outbound_payments: HashMap<PaymentId, PendingOutboundPayment>, logger: L,
856	) -> Self {
857		let has_invoice_requests = pending_outbound_payments.values().any(|payment| {
858			matches!(
859				payment,
860				PendingOutboundPayment::AwaitingInvoice {
861					retryable_invoice_request: Some(invreq), ..
862				} if invreq.needs_retry
863			)
864		});
865
866		Self {
867			pending_outbound_payments: Mutex::new(pending_outbound_payments),
868			awaiting_invoice: AtomicBool::new(has_invoice_requests),
869			retry_lock: Mutex::new(()),
870			logger,
871		}
872	}
873
874	#[rustfmt::skip]
875	pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP>(
876		&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
877		retry_strategy: Retry, route_params: RouteParameters, router: &R,
878		first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
879		node_signer: &NS, best_block_height: u32,
880		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
881	) -> Result<(), RetryableSendFailure>
882	where
883		R::Target: Router,
884		ES::Target: EntropySource,
885		NS::Target: NodeSigner,
886		IH: Fn() -> InFlightHtlcs,
887		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
888	{
889		self.send_payment_for_non_bolt12_invoice(payment_id, payment_hash, recipient_onion, None, retry_strategy,
890			route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
891			best_block_height, pending_events, &send_payment_along_path)
892	}
893
894	#[rustfmt::skip]
895	pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP>(
896		&self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
897		payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
898		first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
899		node_signer: &NS, best_block_height: u32,
900		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
901	) -> Result<PaymentHash, RetryableSendFailure>
902	where
903		R::Target: Router,
904		ES::Target: EntropySource,
905		NS::Target: NodeSigner,
906		IH: Fn() -> InFlightHtlcs,
907		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
908	{
909		let preimage = payment_preimage
910			.unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
911		let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
912		self.send_payment_for_non_bolt12_invoice(payment_id, payment_hash, recipient_onion, Some(preimage),
913			retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
914			node_signer, best_block_height,  pending_events, send_payment_along_path)
915			.map(|()| payment_hash)
916	}
917
918	#[rustfmt::skip]
919	pub(super) fn pay_for_bolt11_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP>(
920		&self, invoice: &Bolt11Invoice, payment_id: PaymentId,
921		amount_msats: Option<u64>,
922		route_params_config: RouteParametersConfig,
923		retry_strategy: Retry,
924		router: &R,
925		first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
926		node_signer: &NS, best_block_height: u32,
927		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
928	) -> Result<(), Bolt11PaymentError>
929	where
930		R::Target: Router,
931		ES::Target: EntropySource,
932		NS::Target: NodeSigner,
933		IH: Fn() -> InFlightHtlcs,
934		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
935	{
936		let payment_hash = PaymentHash((*invoice.payment_hash()).to_byte_array());
937
938		let amount = match (invoice.amount_milli_satoshis(), amount_msats) {
939			(Some(amt), None) | (None, Some(amt)) => amt,
940			(Some(inv_amt), Some(user_amt)) if user_amt < inv_amt => return Err(Bolt11PaymentError::InvalidAmount),
941			(Some(_), Some(user_amt)) => user_amt,
942			(None, None) => return Err(Bolt11PaymentError::InvalidAmount),
943		};
944
945		let mut recipient_onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
946		recipient_onion.payment_metadata = invoice.payment_metadata().map(|v| v.clone());
947
948		let payment_params = PaymentParameters::from_bolt11_invoice(invoice)
949			.with_user_config_ignoring_fee_limit(route_params_config);
950
951		let mut route_params = RouteParameters::from_payment_params_and_value(payment_params, amount);
952
953		if let Some(max_fee_msat) = route_params_config.max_total_routing_fee_msat {
954			route_params.max_total_routing_fee_msat = Some(max_fee_msat);
955		}
956
957		self.send_payment_for_non_bolt12_invoice(payment_id, payment_hash, recipient_onion, None, retry_strategy, route_params,
958			router, first_hops, compute_inflight_htlcs,
959			entropy_source, node_signer, best_block_height,
960			pending_events, send_payment_along_path
961		).map_err(|err| Bolt11PaymentError::SendingFailed(err))
962	}
963
964	#[rustfmt::skip]
965	pub(super) fn send_payment_for_bolt12_invoice<
966		R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP
967	>(
968		&self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
969		first_hops: Vec<ChannelDetails>, features: Bolt12InvoiceFeatures, inflight_htlcs: IH,
970		entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
971		secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32,
972		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
973		send_payment_along_path: SP,
974	) -> Result<(), Bolt12PaymentError>
975	where
976		R::Target: Router,
977		ES::Target: EntropySource,
978		NS::Target: NodeSigner,
979		NL::Target: NodeIdLookUp,
980		IH: Fn() -> InFlightHtlcs,
981		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
982	{
983
984		let (payment_hash, retry_strategy, params_config, _) = self
985			.mark_invoice_received_and_get_details(invoice, payment_id)?;
986
987		if invoice.invoice_features().requires_unknown_bits_from(&features) {
988			self.abandon_payment(
989				payment_id, PaymentFailureReason::UnknownRequiredFeatures, pending_events,
990			);
991			return Err(Bolt12PaymentError::UnknownRequiredFeatures);
992		}
993
994		let mut route_params = RouteParameters::from_payment_params_and_value(
995			PaymentParameters::from_bolt12_invoice(&invoice)
996				.with_user_config_ignoring_fee_limit(params_config), invoice.amount_msats()
997		);
998		if let Some(max_fee_msat) = params_config.max_total_routing_fee_msat {
999			route_params.max_total_routing_fee_msat = Some(max_fee_msat);
1000		}
1001		let invoice = PaidBolt12Invoice::Bolt12Invoice(invoice.clone());
1002		self.send_payment_for_bolt12_invoice_internal(
1003			payment_id, payment_hash, None, None, invoice, route_params, retry_strategy, false, router,
1004			first_hops, inflight_htlcs, entropy_source, node_signer, node_id_lookup, secp_ctx,
1005			best_block_height, pending_events, send_payment_along_path
1006		)
1007	}
1008
1009	#[rustfmt::skip]
1010	fn send_payment_for_bolt12_invoice_internal<
1011		R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP
1012	>(
1013		&self, payment_id: PaymentId, payment_hash: PaymentHash,
1014		keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
1015		bolt12_invoice: PaidBolt12Invoice,
1016		mut route_params: RouteParameters, retry_strategy: Retry, hold_htlcs_at_next_hop: bool, router: &R,
1017		first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
1018		node_id_lookup: &NL, secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32,
1019		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1020		send_payment_along_path: SP,
1021	) -> Result<(), Bolt12PaymentError>
1022	where
1023		R::Target: Router,
1024		ES::Target: EntropySource,
1025		NS::Target: NodeSigner,
1026		NL::Target: NodeIdLookUp,
1027		IH: Fn() -> InFlightHtlcs,
1028		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1029	{
1030		// Advance any blinded path where the introduction node is our node.
1031		if let Ok(our_node_id) = node_signer.get_node_id(Recipient::Node) {
1032			for path in route_params.payment_params.payee.blinded_route_hints_mut().iter_mut() {
1033				let introduction_node_id = match path.introduction_node() {
1034					IntroductionNode::NodeId(pubkey) => *pubkey,
1035					IntroductionNode::DirectedShortChannelId(direction, scid) => {
1036						match node_id_lookup.next_node_id(*scid) {
1037							Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
1038							None => continue,
1039						}
1040					},
1041				};
1042				if introduction_node_id == our_node_id {
1043					let _ = path.advance_path_by_one(node_signer, node_id_lookup, secp_ctx);
1044				}
1045			}
1046		}
1047
1048		let recipient_onion = RecipientOnionFields {
1049			payment_secret: None,
1050			payment_metadata: None,
1051			custom_tlvs: vec![],
1052		};
1053		let route = match self.find_initial_route(
1054			payment_id, payment_hash, &recipient_onion, keysend_preimage, invoice_request,
1055			&mut route_params, router, &first_hops, &inflight_htlcs, node_signer, best_block_height,
1056		) {
1057			Ok(route) => route,
1058			Err(e) => {
1059				let reason = match e {
1060					RetryableSendFailure::PaymentExpired => PaymentFailureReason::PaymentExpired,
1061					RetryableSendFailure::RouteNotFound => PaymentFailureReason::RouteNotFound,
1062					RetryableSendFailure::DuplicatePayment => PaymentFailureReason::UnexpectedError,
1063					RetryableSendFailure::OnionPacketSizeExceeded => PaymentFailureReason::UnexpectedError,
1064				};
1065				self.abandon_payment(payment_id, reason, pending_events);
1066				return Err(Bolt12PaymentError::SendingFailed(e));
1067			},
1068		};
1069
1070		let payment_params = Some(route_params.payment_params.clone());
1071		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1072		let onion_session_privs = match outbounds.entry(payment_id) {
1073			hash_map::Entry::Occupied(entry) => match entry.get() {
1074				PendingOutboundPayment::InvoiceReceived { .. } => {
1075					let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
1076						payment_hash, recipient_onion.clone(), keysend_preimage, None, Some(bolt12_invoice.clone()), &route,
1077						Some(retry_strategy), payment_params, entropy_source, best_block_height,
1078					);
1079					*entry.into_mut() = retryable_payment;
1080					onion_session_privs
1081				},
1082				PendingOutboundPayment::StaticInvoiceReceived { .. } => {
1083					let invreq = if let PendingOutboundPayment::StaticInvoiceReceived { invoice_request, .. } = entry.remove() {
1084						invoice_request
1085					} else { unreachable!() };
1086					let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
1087						payment_hash, recipient_onion.clone(), keysend_preimage, Some(invreq), Some(bolt12_invoice.clone()), &route,
1088						Some(retry_strategy), payment_params, entropy_source, best_block_height
1089					);
1090					outbounds.insert(payment_id, retryable_payment);
1091					onion_session_privs
1092				},
1093				_ => return Err(Bolt12PaymentError::DuplicateInvoice),
1094			},
1095			hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
1096		};
1097		core::mem::drop(outbounds);
1098
1099		let result = self.pay_route_internal(
1100			&route, payment_hash, &recipient_onion, keysend_preimage, invoice_request, Some(&bolt12_invoice), payment_id,
1101			Some(route_params.final_value_msat), &onion_session_privs, hold_htlcs_at_next_hop, node_signer,
1102			best_block_height, &send_payment_along_path
1103		);
1104		log_info!(
1105			self.logger, "Sending payment with id {} and hash {} returned {:?}", payment_id,
1106			payment_hash, result
1107		);
1108		if let Err(e) = result {
1109			self.handle_pay_route_err(
1110				e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
1111				&inflight_htlcs, entropy_source, node_signer, best_block_height,  pending_events,
1112				&send_payment_along_path
1113			);
1114		}
1115		Ok(())
1116	}
1117
1118	pub(super) fn static_invoice_received<ES: Deref>(
1119		&self, invoice: &StaticInvoice, payment_id: PaymentId, features: Bolt12InvoiceFeatures,
1120		best_block_height: u32, duration_since_epoch: Duration, entropy_source: ES,
1121		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1122	) -> Result<(), Bolt12PaymentError>
1123	where
1124		ES::Target: EntropySource,
1125	{
1126		macro_rules! abandon_with_entry {
1127			($payment: expr, $reason: expr) => {
1128				assert!(
1129					matches!($payment.get(), PendingOutboundPayment::AwaitingInvoice { .. }),
1130					"Generating PaymentFailed for unexpected outbound payment type can result in funds loss"
1131				);
1132				pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1133					payment_id,
1134					payment_hash: None,
1135					reason: Some($reason),
1136				}, None));
1137				$payment.remove();
1138			}
1139		}
1140
1141		match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1142			hash_map::Entry::Occupied(mut entry) => match entry.get_mut() {
1143				PendingOutboundPayment::AwaitingInvoice {
1144					retry_strategy,
1145					retryable_invoice_request,
1146					route_params_config,
1147					..
1148				} => {
1149					let invreq = &retryable_invoice_request
1150						.as_ref()
1151						.ok_or(Bolt12PaymentError::UnexpectedInvoice)?
1152						.invoice_request;
1153					if !invoice.is_from_same_offer(invreq) {
1154						return Err(Bolt12PaymentError::UnexpectedInvoice);
1155					}
1156					if invoice.invoice_features().requires_unknown_bits_from(&features) {
1157						abandon_with_entry!(entry, PaymentFailureReason::UnknownRequiredFeatures);
1158						return Err(Bolt12PaymentError::UnknownRequiredFeatures);
1159					}
1160					if duration_since_epoch
1161						> invoice.created_at().saturating_add(invoice.relative_expiry())
1162					{
1163						abandon_with_entry!(entry, PaymentFailureReason::PaymentExpired);
1164						return Err(Bolt12PaymentError::SendingFailed(
1165							RetryableSendFailure::PaymentExpired,
1166						));
1167					}
1168
1169					let amount_msat = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
1170						invreq,
1171					) {
1172						Ok(amt) => amt,
1173						Err(_) => {
1174							// We check this during invoice request parsing, when constructing the invreq's
1175							// contents from its TLV stream.
1176							debug_assert!(false, "LDK requires an msat amount in either the invreq or the invreq's underlying offer");
1177							abandon_with_entry!(entry, PaymentFailureReason::UnexpectedError);
1178							return Err(Bolt12PaymentError::UnknownRequiredFeatures);
1179						},
1180					};
1181					let keysend_preimage =
1182						PaymentPreimage(entropy_source.get_secure_random_bytes());
1183					let payment_hash =
1184						PaymentHash(Sha256::hash(&keysend_preimage.0).to_byte_array());
1185					let pay_params = PaymentParameters::from_static_invoice(invoice)
1186						.with_user_config_ignoring_fee_limit(*route_params_config);
1187					let mut route_params =
1188						RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
1189					route_params.max_total_routing_fee_msat =
1190						route_params_config.max_total_routing_fee_msat;
1191
1192					if let Err(()) = onion_utils::set_max_path_length(
1193						&mut route_params,
1194						&RecipientOnionFields::spontaneous_empty(),
1195						Some(keysend_preimage),
1196						Some(invreq),
1197						best_block_height,
1198					) {
1199						abandon_with_entry!(entry, PaymentFailureReason::RouteNotFound);
1200						return Err(Bolt12PaymentError::SendingFailed(
1201							RetryableSendFailure::OnionPacketSizeExceeded,
1202						));
1203					}
1204					let absolute_expiry =
1205						duration_since_epoch.saturating_add(ASYNC_PAYMENT_TIMEOUT_RELATIVE_EXPIRY);
1206
1207					*entry.into_mut() = PendingOutboundPayment::StaticInvoiceReceived {
1208						payment_hash,
1209						keysend_preimage,
1210						retry_strategy: *retry_strategy,
1211						route_params,
1212						invoice_request: retryable_invoice_request
1213							.take()
1214							.ok_or(Bolt12PaymentError::UnexpectedInvoice)?
1215							.invoice_request,
1216						static_invoice: invoice.clone(),
1217						expiry_time: absolute_expiry,
1218					};
1219					return Ok(());
1220				},
1221				_ => return Err(Bolt12PaymentError::DuplicateInvoice),
1222			},
1223			hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
1224		};
1225	}
1226
1227	pub(super) fn send_payment_for_static_invoice<
1228		R: Deref,
1229		ES: Deref,
1230		NS: Deref,
1231		NL: Deref,
1232		IH,
1233		SP,
1234	>(
1235		&self, payment_id: PaymentId, hold_htlcs_at_next_hop: bool, router: &R,
1236		first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
1237		node_id_lookup: &NL, secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32,
1238		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1239		send_payment_along_path: SP,
1240	) -> Result<(), Bolt12PaymentError>
1241	where
1242		R::Target: Router,
1243		ES::Target: EntropySource,
1244		NS::Target: NodeSigner,
1245		NL::Target: NodeIdLookUp,
1246		IH: Fn() -> InFlightHtlcs,
1247		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1248	{
1249		let (
1250			payment_hash,
1251			keysend_preimage,
1252			route_params,
1253			mut retry_strategy,
1254			invoice_request,
1255			invoice,
1256		) = match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1257			hash_map::Entry::Occupied(entry) => match entry.get() {
1258				PendingOutboundPayment::StaticInvoiceReceived {
1259					payment_hash,
1260					route_params,
1261					retry_strategy,
1262					keysend_preimage,
1263					invoice_request,
1264					static_invoice,
1265					..
1266				} => (
1267					*payment_hash,
1268					*keysend_preimage,
1269					route_params.clone(),
1270					*retry_strategy,
1271					invoice_request.clone(),
1272					static_invoice.clone(),
1273				),
1274				_ => return Err(Bolt12PaymentError::DuplicateInvoice),
1275			},
1276			hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
1277		};
1278
1279		// If we expect the HTLCs for this payment to be held at our next-hop counterparty, don't
1280		// retry the payment. In future iterations of this feature, we will send this payment via
1281		// trampoline and the counterparty will retry on our behalf.
1282		if hold_htlcs_at_next_hop {
1283			retry_strategy = Retry::Attempts(0);
1284		}
1285
1286		let invoice = PaidBolt12Invoice::StaticInvoice(invoice);
1287		self.send_payment_for_bolt12_invoice_internal(
1288			payment_id,
1289			payment_hash,
1290			Some(keysend_preimage),
1291			Some(&invoice_request),
1292			invoice,
1293			route_params,
1294			retry_strategy,
1295			hold_htlcs_at_next_hop,
1296			router,
1297			first_hops,
1298			inflight_htlcs,
1299			entropy_source,
1300			node_signer,
1301			node_id_lookup,
1302			secp_ctx,
1303			best_block_height,
1304			pending_events,
1305			send_payment_along_path,
1306		)
1307	}
1308
1309	// Returns whether the data changed and needs to be repersisted.
1310	pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH>(
1311		&self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES,
1312		node_signer: &NS, best_block_height: u32,
1313		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1314		send_payment_along_path: SP,
1315	) -> bool
1316	where
1317		R::Target: Router,
1318		ES::Target: EntropySource,
1319		NS::Target: NodeSigner,
1320		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1321		IH: Fn() -> InFlightHtlcs,
1322		FH: Fn() -> Vec<ChannelDetails>,
1323	{
1324		let _single_thread = self.retry_lock.lock().unwrap();
1325		let mut should_persist = false;
1326		loop {
1327			let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1328			let mut retry_id_route_params = None;
1329			for (pmt_id, pmt) in outbounds.iter_mut() {
1330				if pmt.is_auto_retryable_now() {
1331					if let PendingOutboundPayment::Retryable {
1332						pending_amt_msat,
1333						total_msat,
1334						payment_params: Some(params),
1335						payment_hash,
1336						remaining_max_total_routing_fee_msat,
1337						..
1338					} = pmt
1339					{
1340						if pending_amt_msat < total_msat {
1341							retry_id_route_params = Some((
1342								*payment_hash,
1343								*pmt_id,
1344								RouteParameters {
1345									final_value_msat: *total_msat - *pending_amt_msat,
1346									payment_params: params.clone(),
1347									max_total_routing_fee_msat:
1348										*remaining_max_total_routing_fee_msat,
1349								},
1350							));
1351							break;
1352						}
1353					} else {
1354						debug_assert!(false);
1355					}
1356				}
1357			}
1358			core::mem::drop(outbounds);
1359			if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
1360				self.find_route_and_send_payment(
1361					payment_hash,
1362					payment_id,
1363					route_params,
1364					router,
1365					first_hops(),
1366					&inflight_htlcs,
1367					entropy_source,
1368					node_signer,
1369					best_block_height,
1370					pending_events,
1371					&send_payment_along_path,
1372				);
1373				should_persist = true;
1374			} else {
1375				break;
1376			}
1377		}
1378
1379		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1380		outbounds.retain(|pmt_id, pmt| {
1381			let mut retain = true;
1382			if !pmt.is_auto_retryable_now()
1383				&& pmt.remaining_parts() == 0
1384				&& !pmt.is_pre_htlc_lock_in()
1385			{
1386				pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
1387				if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
1388					pending_events.lock().unwrap().push_back((
1389						events::Event::PaymentFailed {
1390							payment_id: *pmt_id,
1391							payment_hash: Some(*payment_hash),
1392							reason: *reason,
1393						},
1394						None,
1395					));
1396					retain = false;
1397					should_persist = true;
1398				}
1399			}
1400			retain
1401		});
1402		should_persist
1403	}
1404
1405	pub(super) fn needs_abandon_or_retry(&self) -> bool {
1406		let outbounds = self.pending_outbound_payments.lock().unwrap();
1407		outbounds.iter().any(|(_, pmt)| {
1408			pmt.is_auto_retryable_now()
1409				|| !pmt.is_auto_retryable_now()
1410					&& pmt.remaining_parts() == 0
1411					&& !pmt.is_fulfilled()
1412					&& !pmt.is_pre_htlc_lock_in()
1413		})
1414	}
1415
1416	#[rustfmt::skip]
1417	fn find_initial_route<R: Deref, NS: Deref, IH>(
1418		&self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
1419		keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
1420		route_params: &mut RouteParameters, router: &R, first_hops: &Vec<ChannelDetails>,
1421		inflight_htlcs: &IH, node_signer: &NS, best_block_height: u32,
1422	) -> Result<Route, RetryableSendFailure>
1423	where
1424		R::Target: Router,
1425		NS::Target: NodeSigner,
1426		L::Target: Logger,
1427		IH: Fn() -> InFlightHtlcs,
1428	{
1429		#[cfg(feature = "std")] {
1430			if has_expired(&route_params) {
1431				log_error!(self.logger, "Payment with id {} and hash {} had expired before we started paying",
1432					payment_id, payment_hash);
1433				return Err(RetryableSendFailure::PaymentExpired)
1434			}
1435		}
1436
1437		onion_utils::set_max_path_length(
1438			route_params, recipient_onion, keysend_preimage, invoice_request, best_block_height
1439		)
1440			.map_err(|()| {
1441				log_error!(self.logger, "Can't construct an onion packet without exceeding 1300-byte onion \
1442					hop_data length for payment with id {} and hash {}", payment_id, payment_hash);
1443				RetryableSendFailure::OnionPacketSizeExceeded
1444			})?;
1445
1446		let mut route = router.find_route_with_id(
1447			&node_signer.get_node_id(Recipient::Node).unwrap(), route_params,
1448			Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
1449			payment_hash, payment_id,
1450		).map_err(|_| {
1451			log_error!(self.logger, "Failed to find route for payment with id {} and hash {}",
1452				payment_id, payment_hash);
1453			RetryableSendFailure::RouteNotFound
1454		})?;
1455
1456		if route.route_params.as_ref() != Some(route_params) {
1457			debug_assert!(false,
1458				"Routers are expected to return a Route which includes the requested RouteParameters. Got {:?}, expected {:?}",
1459				route.route_params, route_params);
1460			route.route_params = Some(route_params.clone());
1461		}
1462
1463		Ok(route)
1464	}
1465
1466	/// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
1467	/// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
1468	///
1469	/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
1470	/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
1471	#[rustfmt::skip]
1472	fn send_payment_for_non_bolt12_invoice<R: Deref, NS: Deref, ES: Deref, IH, SP>(
1473		&self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1474		keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, mut route_params: RouteParameters,
1475		router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
1476		node_signer: &NS, best_block_height: u32,
1477		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
1478	) -> Result<(), RetryableSendFailure>
1479	where
1480		R::Target: Router,
1481		ES::Target: EntropySource,
1482		NS::Target: NodeSigner,
1483		L::Target: Logger,
1484		IH: Fn() -> InFlightHtlcs,
1485		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1486	{
1487		let route = self.find_initial_route(
1488			payment_id, payment_hash, &recipient_onion, keysend_preimage, None, &mut route_params, router,
1489			&first_hops, &inflight_htlcs, node_signer, best_block_height,
1490		)?;
1491
1492		let onion_session_privs = self.add_new_pending_payment(payment_hash,
1493			recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
1494			Some(route_params.payment_params.clone()), entropy_source, best_block_height, None)
1495			.map_err(|_| {
1496				log_error!(self.logger, "Payment with id {} is already pending. New payment had payment hash {}",
1497					payment_id, payment_hash);
1498				RetryableSendFailure::DuplicatePayment
1499			})?;
1500
1501		let res = self.pay_route_internal(&route, payment_hash, &recipient_onion,
1502			keysend_preimage, None, None, payment_id, None, &onion_session_privs, false, node_signer,
1503			best_block_height, &send_payment_along_path);
1504		log_info!(self.logger, "Sending payment with id {} and hash {} returned {:?}",
1505			payment_id, payment_hash, res);
1506		if let Err(e) = res {
1507			self.handle_pay_route_err(
1508				e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
1509				&inflight_htlcs, entropy_source, node_signer, best_block_height, pending_events,
1510				&send_payment_along_path
1511			);
1512		}
1513		Ok(())
1514	}
1515
1516	#[rustfmt::skip]
1517	fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP>(
1518		&self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
1519		router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
1520		node_signer: &NS, best_block_height: u32,
1521		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1522	)
1523	where
1524		R::Target: Router,
1525		ES::Target: EntropySource,
1526		NS::Target: NodeSigner,
1527		L::Target: Logger,
1528		IH: Fn() -> InFlightHtlcs,
1529		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1530	{
1531		#[cfg(feature = "std")] {
1532			if has_expired(&route_params) {
1533				log_error!(self.logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
1534				self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
1535				return
1536			}
1537		}
1538
1539		let mut route = match router.find_route_with_id(
1540			&node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
1541			Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
1542			payment_hash, payment_id,
1543		) {
1544			Ok(route) => route,
1545			Err(e) => {
1546				log_error!(self.logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
1547				self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
1548				return
1549			}
1550		};
1551
1552		if route.route_params.as_ref() != Some(&route_params) {
1553			debug_assert!(false,
1554				"Routers are expected to return a Route which includes the requested RouteParameters");
1555			route.route_params = Some(route_params.clone());
1556		}
1557
1558		for path in route.paths.iter() {
1559			if path.hops.len() == 0 {
1560				log_error!(self.logger, "Unusable path in route (path.hops.len() must be at least 1");
1561				self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1562				return
1563			}
1564		}
1565
1566		macro_rules! abandon_with_entry {
1567			($payment: expr, $reason: expr) => {
1568				$payment.get_mut().mark_abandoned($reason);
1569				if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
1570					if $payment.get().remaining_parts() == 0 {
1571						pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1572							payment_id,
1573							payment_hash: Some(payment_hash),
1574							reason: *reason,
1575						}, None));
1576						$payment.remove();
1577					}
1578				}
1579			}
1580		}
1581		let (total_msat, recipient_onion, keysend_preimage, onion_session_privs, invoice_request, bolt12_invoice) = {
1582			let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1583			match outbounds.entry(payment_id) {
1584				hash_map::Entry::Occupied(mut payment) => {
1585					match payment.get() {
1586						PendingOutboundPayment::Retryable {
1587							total_msat, keysend_preimage, payment_secret, payment_metadata,
1588							custom_tlvs, pending_amt_msat, invoice_request, ..
1589						} => {
1590							const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1591							let retry_amt_msat = route.get_total_amount();
1592							if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1593								log_error!(self.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);
1594								abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1595								return
1596							}
1597
1598							if !payment.get().is_retryable_now() {
1599								log_error!(self.logger, "Retries exhausted for payment id {}", &payment_id);
1600								abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1601								return
1602							}
1603
1604							let total_msat = *total_msat;
1605							let recipient_onion = RecipientOnionFields {
1606								payment_secret: *payment_secret,
1607								payment_metadata: payment_metadata.clone(),
1608								custom_tlvs: custom_tlvs.clone(),
1609							};
1610							let keysend_preimage = *keysend_preimage;
1611							let invoice_request = invoice_request.clone();
1612
1613							let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1614							for _ in 0..route.paths.len() {
1615								onion_session_privs.push(entropy_source.get_secure_random_bytes());
1616							}
1617
1618							for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1619								assert!(payment.get_mut().insert(*session_priv_bytes, path));
1620							}
1621
1622							payment.get_mut().increment_attempts();
1623							let bolt12_invoice = payment.get().bolt12_invoice();
1624
1625							(total_msat, recipient_onion, keysend_preimage, onion_session_privs, invoice_request, bolt12_invoice.cloned())
1626						},
1627						PendingOutboundPayment::Legacy { .. } => {
1628							log_error!(self.logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1629							return
1630						},
1631						PendingOutboundPayment::AwaitingInvoice { .. }
1632							| PendingOutboundPayment::AwaitingOffer { .. } =>
1633						{
1634							log_error!(self.logger, "Payment not yet sent");
1635							debug_assert!(false);
1636							return
1637						},
1638						PendingOutboundPayment::InvoiceReceived { .. } => {
1639							log_error!(self.logger, "Payment already initiating");
1640							debug_assert!(false);
1641							return
1642						},
1643						PendingOutboundPayment::StaticInvoiceReceived { .. } => {
1644							log_error!(self.logger, "Payment already initiating");
1645							debug_assert!(false);
1646							return
1647						},
1648						PendingOutboundPayment::Fulfilled { .. } => {
1649							log_error!(self.logger, "Payment already completed");
1650							return
1651						},
1652						PendingOutboundPayment::Abandoned { .. } => {
1653							log_error!(self.logger, "Payment already abandoned (with some HTLCs still pending)");
1654							return
1655						},
1656					}
1657				},
1658				hash_map::Entry::Vacant(_) => {
1659					log_error!(self.logger, "Payment with ID {} not found", &payment_id);
1660					return
1661				}
1662			}
1663		};
1664		let res = self.pay_route_internal(&route, payment_hash, &recipient_onion, keysend_preimage,
1665			invoice_request.as_ref(), bolt12_invoice.as_ref(), payment_id, Some(total_msat),
1666			&onion_session_privs, false, node_signer, best_block_height, &send_payment_along_path);
1667		log_info!(self.logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1668		if let Err(e) = res {
1669			self.handle_pay_route_err(
1670				e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
1671				inflight_htlcs, entropy_source, node_signer, best_block_height, pending_events,
1672				send_payment_along_path
1673			);
1674		}
1675	}
1676
1677	#[rustfmt::skip]
1678	fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP>(
1679		&self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1680		mut route_params: RouteParameters, onion_session_privs: Vec<[u8; 32]>, router: &R,
1681		first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS,
1682		best_block_height: u32,
1683		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1684		send_payment_along_path: &SP,
1685	)
1686	where
1687		R::Target: Router,
1688		ES::Target: EntropySource,
1689		NS::Target: NodeSigner,
1690		IH: Fn() -> InFlightHtlcs,
1691		SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1692	{
1693		match err {
1694			PaymentSendFailure::AllFailedResendSafe(errs) => {
1695				self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1696				Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, errs.into_iter().map(|e| Err(e)), &self.logger, pending_events);
1697				self.find_route_and_send_payment(payment_hash, payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, pending_events, send_payment_along_path);
1698			},
1699			PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1700				debug_assert_eq!(results.len(), route.paths.len());
1701				debug_assert_eq!(results.len(), onion_session_privs.len());
1702				let failed_paths = results.iter().zip(route.paths.iter().zip(onion_session_privs.iter()))
1703					.filter_map(|(path_res, (path, session_priv))| {
1704						match path_res {
1705							// While a MonitorUpdateInProgress is an Err(_), the payment is still
1706							// considered "in flight" and we shouldn't remove it from the
1707							// PendingOutboundPayment set.
1708							Ok(_) | Err(APIError::MonitorUpdateInProgress) => None,
1709							_ => Some((path, session_priv))
1710						}
1711					});
1712				self.remove_session_privs(payment_id, failed_paths);
1713				Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), &self.logger, pending_events);
1714				// Some paths were sent, even if we failed to send the full MPP value our recipient may
1715				// misbehave and claim the funds, at which point we have to consider the payment sent, so
1716				// return `Ok()` here, ignoring any retry errors.
1717				self.find_route_and_send_payment(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height,  pending_events, send_payment_along_path);
1718			},
1719			PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1720				// This may happen if we send a payment and some paths fail, but only due to a temporary
1721				// monitor failure or the like, implying they're really in-flight, but we haven't sent the
1722				// initial HTLC-Add messages yet.
1723			},
1724			PaymentSendFailure::PathParameterError(results) => {
1725				log_error!(self.logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1726				self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1727				Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), &self.logger, pending_events);
1728				self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1729			},
1730			PaymentSendFailure::ParameterError(e) => {
1731				log_error!(self.logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1732				self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1733				self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1734			},
1735			PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1736		}
1737	}
1738
1739	fn push_path_failed_evs_and_scids<
1740		I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>,
1741	>(
1742		payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1743		paths: Vec<Path>, path_results: I, logger: &L,
1744		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1745	) {
1746		let mut events = pending_events.lock().unwrap();
1747		debug_assert_eq!(paths.len(), path_results.len());
1748		for (path, path_res) in paths.into_iter().zip(path_results) {
1749			if let Err(e) = path_res {
1750				if let APIError::MonitorUpdateInProgress = e {
1751					continue;
1752				}
1753				log_error!(logger, "Failed to send along path due to error: {:?}", e);
1754				let mut failed_scid = None;
1755				if let APIError::ChannelUnavailable { .. } = e {
1756					let scid = path.hops[0].short_channel_id;
1757					failed_scid = Some(scid);
1758					route_params.payment_params.previously_failed_channels.push(scid);
1759				}
1760				let event = events::Event::PaymentPathFailed {
1761					payment_id: Some(payment_id),
1762					payment_hash,
1763					payment_failed_permanently: false,
1764					failure: events::PathFailure::InitialSend { err: e },
1765					path,
1766					short_channel_id: failed_scid,
1767					#[cfg(any(test, feature = "_test_utils"))]
1768					error_code: None,
1769					#[cfg(any(test, feature = "_test_utils"))]
1770					error_data: None,
1771					hold_times: Vec::new(),
1772				};
1773				events.push_back((event, None));
1774			}
1775		}
1776	}
1777
1778	// If a payment fails after adding the pending payment but before any HTLCs are locked into
1779	// channels, we need to clear the session_privs in order for abandoning the payment to succeed.
1780	#[rustfmt::skip]
1781	fn remove_session_privs<'a, I: Iterator<Item = (&'a Path, &'a [u8; 32])>>(
1782		&self, payment_id: PaymentId, path_session_priv: I
1783	) {
1784		if let Some(payment) = self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id) {
1785			for (path, session_priv_bytes) in path_session_priv {
1786				let removed = payment.remove(session_priv_bytes, Some(path));
1787				debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1788			}
1789		} else {
1790			debug_assert!(false, "This can't happen as the payment was added by callers");
1791		}
1792	}
1793
1794	#[rustfmt::skip]
1795	pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1796		&self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1797		best_block_height: u32, send_payment_along_path: F
1798	) -> Result<(PaymentHash, PaymentId), ProbeSendFailure>
1799	where
1800		ES::Target: EntropySource,
1801		NS::Target: NodeSigner,
1802		F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1803	{
1804		let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1805		let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1806
1807		let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1808
1809		if path.hops.len() < 2 && path.blinded_tail.is_none() {
1810			return Err(ProbeSendFailure::ParameterError(APIError::APIMisuseError {
1811				err: "No need probing a path with less than two hops".to_string()
1812			}))
1813		}
1814
1815		let route = Route { paths: vec![path], route_params: None };
1816		let onion_session_privs = self.add_new_pending_payment(payment_hash,
1817			RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1818			entropy_source, best_block_height, None
1819		).map_err(|e| {
1820			debug_assert!(matches!(e, PaymentSendFailure::DuplicatePayment));
1821			ProbeSendFailure::DuplicateProbe
1822		})?;
1823
1824		let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1825		match self.pay_route_internal(&route, payment_hash, &recipient_onion_fields,
1826			None, None, None, payment_id, None, &onion_session_privs, false, node_signer,
1827			best_block_height, &send_payment_along_path
1828		) {
1829			Ok(()) => Ok((payment_hash, payment_id)),
1830			Err(e) => {
1831				self.remove_outbound_if_all_failed(payment_id, &e);
1832				match e {
1833					PaymentSendFailure::DuplicatePayment => Err(ProbeSendFailure::DuplicateProbe),
1834					PaymentSendFailure::ParameterError(err) => Err(ProbeSendFailure::ParameterError(err)),
1835					PaymentSendFailure::PartialFailure { results, .. }
1836					| PaymentSendFailure::PathParameterError(results) => {
1837						debug_assert_eq!(results.len(), 1);
1838						let err = results.into_iter()
1839							.find(|res| res.is_err())
1840							.map(|err| err.unwrap_err())
1841							.unwrap_or(APIError::APIMisuseError { err: "Unexpected error".to_owned() });
1842						Err(ProbeSendFailure::ParameterError(err))
1843					},
1844					PaymentSendFailure::AllFailedResendSafe(mut errors) => {
1845						debug_assert_eq!(errors.len(), 1);
1846						let err = errors
1847							.pop()
1848							.unwrap_or(APIError::APIMisuseError { err: "Unexpected error".to_owned() });
1849						Err(ProbeSendFailure::ParameterError(err))
1850					}
1851				}
1852			}
1853		}
1854	}
1855
1856	#[cfg(test)]
1857	pub(super) fn test_set_payment_metadata(
1858		&self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>,
1859	) {
1860		match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1861			PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1862				*payment_metadata = new_payment_metadata;
1863			},
1864			_ => panic!("Need a retryable payment to update metadata on"),
1865		}
1866	}
1867
1868	#[cfg(any(test, feature = "_externalize_tests"))]
1869	#[rustfmt::skip]
1870	pub(super) fn test_add_new_pending_payment<ES: Deref>(
1871		&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1872		route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1873	) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1874		self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height, None)
1875	}
1876
1877	#[rustfmt::skip]
1878	pub(super) fn add_new_pending_payment<ES: Deref>(
1879		&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1880		keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1881		payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32,
1882		bolt12_invoice: Option<PaidBolt12Invoice>
1883	) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1884		let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1885		match pending_outbounds.entry(payment_id) {
1886			hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1887			hash_map::Entry::Vacant(entry) => {
1888				let (payment, onion_session_privs) = Self::create_pending_payment(
1889					payment_hash, recipient_onion, keysend_preimage, None, bolt12_invoice, route, retry_strategy,
1890					payment_params, entropy_source, best_block_height
1891				);
1892				entry.insert(payment);
1893				Ok(onion_session_privs)
1894			},
1895		}
1896	}
1897
1898	#[rustfmt::skip]
1899	fn create_pending_payment<ES: Deref>(
1900		payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1901		keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<InvoiceRequest>,
1902		bolt12_invoice: Option<PaidBolt12Invoice>, route: &Route, retry_strategy: Option<Retry>,
1903		payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1904	) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1905	where
1906		ES::Target: EntropySource,
1907	{
1908		let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1909		for _ in 0..route.paths.len() {
1910			onion_session_privs.push(entropy_source.get_secure_random_bytes());
1911		}
1912
1913		let mut payment = PendingOutboundPayment::Retryable {
1914			retry_strategy,
1915			attempts: PaymentAttempts::new(),
1916			payment_params,
1917			session_privs: new_hash_set(),
1918			pending_amt_msat: 0,
1919			pending_fee_msat: Some(0),
1920			payment_hash,
1921			payment_secret: recipient_onion.payment_secret,
1922			payment_metadata: recipient_onion.payment_metadata,
1923			keysend_preimage,
1924			invoice_request,
1925			bolt12_invoice,
1926			custom_tlvs: recipient_onion.custom_tlvs,
1927			starting_block_height: best_block_height,
1928			total_msat: route.get_total_amount(),
1929			remaining_max_total_routing_fee_msat:
1930				route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1931		};
1932
1933		for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1934			assert!(payment.insert(*session_priv_bytes, path));
1935		}
1936
1937		(payment, onion_session_privs)
1938	}
1939
1940	#[cfg(feature = "dnssec")]
1941	pub(super) fn add_new_awaiting_offer(
1942		&self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1943		route_params_config: RouteParametersConfig, amount_msats: u64, payer_note: Option<String>,
1944	) -> Result<(), ()> {
1945		let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1946		match pending_outbounds.entry(payment_id) {
1947			hash_map::Entry::Occupied(_) => Err(()),
1948			hash_map::Entry::Vacant(entry) => {
1949				entry.insert(PendingOutboundPayment::AwaitingOffer {
1950					expiration,
1951					retry_strategy,
1952					route_params_config,
1953					amount_msats,
1954					payer_note,
1955				});
1956
1957				Ok(())
1958			},
1959		}
1960	}
1961
1962	#[cfg(feature = "dnssec")]
1963	#[rustfmt::skip]
1964	pub(super) fn params_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result<(u64, Option<String>), ()> {
1965		match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1966			hash_map::Entry::Occupied(entry) => match entry.get() {
1967				PendingOutboundPayment::AwaitingOffer { amount_msats, payer_note, .. } => Ok((*amount_msats, payer_note.clone())),
1968				_ => Err(()),
1969			},
1970			_ => Err(()),
1971		}
1972	}
1973
1974	#[cfg(feature = "dnssec")]
1975	#[rustfmt::skip]
1976	pub(super) fn received_offer(
1977		&self, payment_id: PaymentId, retryable_invoice_request: Option<RetryableInvoiceRequest>,
1978	) -> Result<(), ()> {
1979		match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1980			hash_map::Entry::Occupied(entry) => match entry.get() {
1981				PendingOutboundPayment::AwaitingOffer {
1982					expiration, retry_strategy, route_params_config, ..
1983				} => {
1984					let mut new_val = PendingOutboundPayment::AwaitingInvoice {
1985						expiration: *expiration,
1986						retry_strategy: *retry_strategy,
1987						route_params_config: *route_params_config,
1988						retryable_invoice_request,
1989					};
1990					core::mem::swap(&mut new_val, entry.into_mut());
1991					Ok(())
1992				},
1993				_ => Err(()),
1994			},
1995			hash_map::Entry::Vacant(_) => Err(()),
1996		}
1997	}
1998
1999	pub(super) fn add_new_awaiting_invoice(
2000		&self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
2001		route_params_config: RouteParametersConfig,
2002		retryable_invoice_request: Option<RetryableInvoiceRequest>,
2003	) -> Result<(), ()> {
2004		let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
2005		match pending_outbounds.entry(payment_id) {
2006			hash_map::Entry::Occupied(_) => Err(()),
2007			hash_map::Entry::Vacant(entry) => {
2008				if retryable_invoice_request.is_some() {
2009					self.awaiting_invoice.store(true, Ordering::Release);
2010				}
2011				entry.insert(PendingOutboundPayment::AwaitingInvoice {
2012					expiration,
2013					retry_strategy,
2014					route_params_config,
2015					retryable_invoice_request,
2016				});
2017
2018				Ok(())
2019			},
2020		}
2021	}
2022
2023	#[rustfmt::skip]
2024	pub(super) fn mark_invoice_received(
2025		&self, invoice: &Bolt12Invoice, payment_id: PaymentId
2026	) -> Result<(), Bolt12PaymentError> {
2027		self.mark_invoice_received_and_get_details(invoice, payment_id)
2028			.and_then(|(_, _, _, is_newly_marked)| {
2029				is_newly_marked
2030					.then_some(())
2031					.ok_or(Bolt12PaymentError::DuplicateInvoice)
2032			})
2033	}
2034
2035	#[rustfmt::skip]
2036	fn mark_invoice_received_and_get_details(
2037		&self, invoice: &Bolt12Invoice, payment_id: PaymentId
2038	) -> Result<(PaymentHash, Retry, RouteParametersConfig, bool), Bolt12PaymentError> {
2039		match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
2040			hash_map::Entry::Occupied(entry) => match entry.get() {
2041				PendingOutboundPayment::AwaitingInvoice {
2042					retry_strategy: retry, route_params_config, ..
2043				} => {
2044					let payment_hash = invoice.payment_hash();
2045					let retry = *retry;
2046					let config = *route_params_config;
2047					*entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
2048						payment_hash,
2049						retry_strategy: retry,
2050						route_params_config: config,
2051					};
2052
2053					Ok((payment_hash, retry, config, true))
2054				},
2055				// When manual invoice handling is enabled, the corresponding `PendingOutboundPayment` entry
2056				// is already updated at the time the invoice is received. This ensures that `InvoiceReceived`
2057				// event generation remains idempotent, even if the same invoice is received again before the
2058				// event is handled by the user.
2059				PendingOutboundPayment::InvoiceReceived {
2060					retry_strategy, route_params_config, ..
2061				} => {
2062					Ok((invoice.payment_hash(), *retry_strategy, *route_params_config, false))
2063				},
2064				_ => Err(Bolt12PaymentError::DuplicateInvoice),
2065			},
2066			hash_map::Entry::Vacant(_) => Err(Bolt12PaymentError::UnexpectedInvoice),
2067		}
2068	}
2069
2070	#[rustfmt::skip]
2071	fn pay_route_internal<NS: Deref, F>(
2072		&self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
2073		keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>, bolt12_invoice: Option<&PaidBolt12Invoice>,
2074		payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: &Vec<[u8; 32]>,
2075		hold_htlcs_at_next_hop: bool, node_signer: &NS, best_block_height: u32, send_payment_along_path: &F
2076	) -> Result<(), PaymentSendFailure>
2077	where
2078		NS::Target: NodeSigner,
2079		F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
2080	{
2081		if route.paths.len() < 1 {
2082			return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
2083		}
2084		if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
2085			&& !route.paths.iter().any(|p| p.blinded_tail.is_some())
2086		{
2087			return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
2088		}
2089		let mut total_value = 0;
2090		let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
2091		let mut path_errs = Vec::with_capacity(route.paths.len());
2092		'path_check: for path in route.paths.iter() {
2093			if path.hops.len() < 1 || path.hops.len() > 20 {
2094				path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
2095				continue 'path_check;
2096			}
2097			let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
2098				usize::max_value() } else { path.hops.len() - 1 };
2099			for (idx, hop) in path.hops.iter().enumerate() {
2100				if idx != dest_hop_idx && hop.pubkey == our_node_id {
2101					path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
2102					continue 'path_check;
2103				}
2104			}
2105			for (i, hop) in path.hops.iter().enumerate() {
2106				// Check for duplicate channel_id in the remaining hops of the path
2107				if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
2108					path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
2109					continue 'path_check;
2110				}
2111			}
2112			total_value += path.final_value_msat();
2113			path_errs.push(Ok(()));
2114		}
2115		if path_errs.iter().any(|e| e.is_err()) {
2116			return Err(PaymentSendFailure::PathParameterError(path_errs));
2117		}
2118		if let Some(amt_msat) = recv_value_msat {
2119			total_value = amt_msat;
2120		}
2121
2122		let cur_height = best_block_height + 1;
2123		let mut results = Vec::new();
2124		debug_assert_eq!(route.paths.len(), onion_session_privs.len());
2125		for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
2126			let path_res = send_payment_along_path(SendAlongPathArgs {
2127				path: &path, payment_hash: &payment_hash, recipient_onion, total_value,
2128				cur_height, payment_id, keysend_preimage: &keysend_preimage, invoice_request,
2129				bolt12_invoice, hold_htlc_at_next_hop: hold_htlcs_at_next_hop,
2130				session_priv_bytes: *session_priv_bytes
2131			});
2132			results.push(path_res);
2133		}
2134		let mut has_ok = false;
2135		let mut has_err = false;
2136		let mut has_unsent = false;
2137		let mut total_ok_fees_msat = 0;
2138		let mut total_ok_amt_sent_msat = 0;
2139		for (res, path) in results.iter().zip(route.paths.iter()) {
2140			if res.is_ok() {
2141				has_ok = true;
2142				total_ok_fees_msat += path.fee_msat();
2143				total_ok_amt_sent_msat += path.final_value_msat();
2144			}
2145			if res.is_err() { has_err = true; }
2146			if let &Err(APIError::MonitorUpdateInProgress) = res {
2147				// MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
2148				// PartialFailure.
2149				has_err = true;
2150				has_ok = true;
2151				total_ok_fees_msat += path.fee_msat();
2152				total_ok_amt_sent_msat += path.final_value_msat();
2153			} else if res.is_err() {
2154				has_unsent = true;
2155			}
2156		}
2157		if has_err && has_ok {
2158			Err(PaymentSendFailure::PartialFailure {
2159				results,
2160				payment_id,
2161				failed_paths_retry: if has_unsent {
2162					if let Some(route_params) = &route.route_params {
2163						let mut route_params = route_params.clone();
2164						// We calculate the leftover fee budget we're allowed to spend by
2165						// subtracting the used fee from the total fee budget.
2166						route_params.max_total_routing_fee_msat = route_params
2167							.max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
2168
2169						// We calculate the remaining target amount by subtracting the succeded
2170						// path values.
2171						route_params.final_value_msat = route_params.final_value_msat
2172							.saturating_sub(total_ok_amt_sent_msat);
2173						Some(route_params)
2174					} else { None }
2175				} else { None },
2176			})
2177		} else if has_err {
2178			Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
2179		} else {
2180			Ok(())
2181		}
2182	}
2183
2184	#[cfg(any(test, feature = "_externalize_tests"))]
2185	#[rustfmt::skip]
2186	pub(super) fn test_send_payment_internal<NS: Deref, F>(
2187		&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
2188		keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
2189		onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
2190		send_payment_along_path: F
2191	) -> Result<(), PaymentSendFailure>
2192	where
2193		NS::Target: NodeSigner,
2194		F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
2195	{
2196		self.pay_route_internal(route, payment_hash, &recipient_onion,
2197			keysend_preimage, None, None, payment_id, recv_value_msat, &onion_session_privs,
2198			false, node_signer, best_block_height, &send_payment_along_path)
2199			.map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
2200	}
2201
2202	// If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
2203	// map as the payment is free to be resent.
2204	#[rustfmt::skip]
2205	fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
2206		match err {
2207			PaymentSendFailure::AllFailedResendSafe(_)
2208				| PaymentSendFailure::ParameterError(_)
2209				| PaymentSendFailure::PathParameterError(_) =>
2210			{
2211				let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
2212				debug_assert!(removed, "We should always have a pending payment to remove here");
2213			},
2214			PaymentSendFailure::DuplicatePayment | PaymentSendFailure::PartialFailure { .. }  => {}
2215		}
2216	}
2217
2218	#[rustfmt::skip]
2219	pub(super) fn claim_htlc(
2220		&self, payment_id: PaymentId, payment_preimage: PaymentPreimage, bolt12_invoice: Option<PaidBolt12Invoice>,
2221		session_priv: SecretKey, path: Path, from_onchain: bool, ev_completion_action: &mut Option<EventCompletionAction>,
2222		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
2223	) {
2224		let mut session_priv_bytes = [0; 32];
2225		session_priv_bytes.copy_from_slice(&session_priv[..]);
2226		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2227		let mut pending_events = pending_events.lock().unwrap();
2228		if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
2229			if !payment.get().is_fulfilled() {
2230				let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
2231				log_info!(self.logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
2232				let fee_paid_msat = payment.get().get_pending_fee_msat();
2233				let amount_msat = payment.get().total_msat();
2234				pending_events.push_back((events::Event::PaymentSent {
2235					payment_id: Some(payment_id),
2236					payment_preimage,
2237					payment_hash,
2238					amount_msat,
2239					fee_paid_msat,
2240					bolt12_invoice: bolt12_invoice,
2241				}, ev_completion_action.take()));
2242				payment.get_mut().mark_fulfilled();
2243			}
2244
2245			if from_onchain {
2246				// We currently immediately remove HTLCs which were fulfilled on-chain.
2247				// This could potentially lead to removing a pending payment too early,
2248				// with a reorg of one block causing us to re-add the fulfilled payment on
2249				// restart.
2250				if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
2251					let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
2252					pending_events.push_back((events::Event::PaymentPathSuccessful {
2253						payment_id,
2254						payment_hash,
2255						path,
2256						hold_times: Vec::new(),
2257					}, ev_completion_action.take()));
2258				}
2259			}
2260		} else {
2261			log_trace!(self.logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
2262		}
2263	}
2264
2265	#[rustfmt::skip]
2266	pub(super) fn finalize_claims<I: Iterator<Item = (HTLCSource, Vec<u32>)>>(&self, sources: I,
2267		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
2268	{
2269		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2270		let mut pending_events = pending_events.lock().unwrap();
2271		for (source, hold_times) in sources {
2272			if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
2273				let mut session_priv_bytes = [0; 32];
2274				session_priv_bytes.copy_from_slice(&session_priv[..]);
2275				if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
2276					assert!(payment.get().is_fulfilled());
2277					if payment.get_mut().remove(&session_priv_bytes, None) {
2278						let payment_hash = payment.get().payment_hash();
2279						debug_assert!(payment_hash.is_some());
2280						pending_events.push_back((events::Event::PaymentPathSuccessful {
2281							payment_id,
2282							payment_hash,
2283							path,
2284							hold_times
2285						}, None));
2286					}
2287				}
2288			}
2289		}
2290	}
2291
2292	#[rustfmt::skip]
2293	pub(super) fn remove_stale_payments(
2294		&self, duration_since_epoch: Duration,
2295		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
2296	{
2297		let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
2298		let mut pending_events = pending_events.lock().unwrap();
2299		pending_outbound_payments.retain(|payment_id, payment| match payment {
2300			// If an outbound payment was completed, and no pending HTLCs remain, we should remove it
2301			// from the map. However, if we did that immediately when the last payment HTLC is claimed,
2302			// this could race the user making a duplicate send_payment call and our idempotency
2303			// guarantees would be violated. Instead, we wait a few timer ticks to do the actual
2304			// removal. This should be more than sufficient to ensure the idempotency of any
2305			// `send_payment` calls that were made at the same time the `PaymentSent` event was being
2306			// processed.
2307			PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
2308				let mut no_remaining_entries = session_privs.is_empty();
2309				if no_remaining_entries {
2310					for (ev, _) in pending_events.iter() {
2311						match ev {
2312							events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
2313								events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
2314								events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
2315									if payment_id == ev_payment_id {
2316										no_remaining_entries = false;
2317										break;
2318									}
2319								},
2320							_ => {},
2321						}
2322					}
2323				}
2324				if no_remaining_entries {
2325					*timer_ticks_without_htlcs += 1;
2326					*timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
2327				} else {
2328					*timer_ticks_without_htlcs = 0;
2329					true
2330				}
2331			},
2332			PendingOutboundPayment::AwaitingInvoice { expiration, .. }
2333				| PendingOutboundPayment::AwaitingOffer { expiration, .. } =>
2334			{
2335				let is_stale = match expiration {
2336					StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
2337						*absolute_expiry <= duration_since_epoch
2338					},
2339					StaleExpiration::TimerTicks(timer_ticks_remaining) => {
2340						if *timer_ticks_remaining > 0 {
2341							*timer_ticks_remaining -= 1;
2342							false
2343						} else {
2344							true
2345						}
2346					},
2347				};
2348				if is_stale {
2349					let event = events::Event::PaymentFailed {
2350						payment_id: *payment_id,
2351						payment_hash: None,
2352						reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2353					};
2354					pending_events.push_back((event, None));
2355					false
2356				} else {
2357					true
2358				}
2359			},
2360			PendingOutboundPayment::StaticInvoiceReceived { route_params, payment_hash, expiry_time, .. } => {
2361				let is_stale = *expiry_time < duration_since_epoch;
2362				let is_static_invoice_stale =
2363					route_params.payment_params.expiry_time.unwrap_or(u64::MAX) <
2364					duration_since_epoch.as_secs();
2365				if is_stale || is_static_invoice_stale {
2366					let fail_ev = events::Event::PaymentFailed {
2367						payment_id: *payment_id,
2368						payment_hash: Some(*payment_hash),
2369						reason: Some(PaymentFailureReason::PaymentExpired)
2370					};
2371					pending_events.push_back((fail_ev, None));
2372					false
2373				} else {
2374					true
2375				}
2376			},
2377			_ => true,
2378		});
2379	}
2380
2381	pub(super) fn fail_htlc(
2382		&self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
2383		path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
2384		probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
2385		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
2386		completion_action: &mut Option<PaymentCompleteUpdate>,
2387	) {
2388		#[cfg(any(test, feature = "_test_utils"))]
2389		let DecodedOnionFailure {
2390			network_update,
2391			short_channel_id,
2392			payment_failed_permanently,
2393			onion_error_code,
2394			onion_error_data,
2395			failed_within_blinded_path,
2396			hold_times,
2397			..
2398		} = onion_error.decode_onion_failure(secp_ctx, &self.logger, &source);
2399		#[cfg(not(any(test, feature = "_test_utils")))]
2400		let DecodedOnionFailure {
2401			network_update,
2402			short_channel_id,
2403			payment_failed_permanently,
2404			failed_within_blinded_path,
2405			hold_times,
2406			..
2407		} = onion_error.decode_onion_failure(secp_ctx, &self.logger, &source);
2408
2409		let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
2410		let mut session_priv_bytes = [0; 32];
2411		session_priv_bytes.copy_from_slice(&session_priv[..]);
2412		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2413
2414		let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
2415			let mut awaiting_retry = false;
2416			if pmt.is_auto_retryable_now() {
2417				if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt
2418				{
2419					if pending_amt_msat < total_msat {
2420						awaiting_retry = true;
2421					}
2422				}
2423			}
2424			awaiting_retry
2425		});
2426
2427		let mut full_failure_ev = None;
2428		let attempts_remaining =
2429			if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
2430				if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
2431					log_trace!(
2432						self.logger,
2433						"Received duplicative fail for HTLC with payment_hash {}",
2434						&payment_hash
2435					);
2436					return;
2437				}
2438				if payment.get().is_fulfilled() {
2439					log_trace!(
2440						self.logger,
2441						"Received failure of HTLC with payment_hash {} after payment completion",
2442						&payment_hash
2443					);
2444					return;
2445				}
2446				let mut is_retryable_now = payment.get().is_auto_retryable_now();
2447				if let Some(scid) = short_channel_id {
2448					// TODO: If we decided to blame ourselves (or one of our channels) in
2449					// process_onion_failure we should close that channel as it implies our
2450					// next-hop is needlessly blaming us!
2451					payment.get_mut().insert_previously_failed_scid(scid);
2452				}
2453				if failed_within_blinded_path {
2454					debug_assert!(short_channel_id.is_none());
2455					if let Some(bt) = &path.blinded_tail {
2456						payment.get_mut().insert_previously_failed_blinded_path(&bt);
2457					} else {
2458						debug_assert!(false);
2459					}
2460				}
2461
2462				if payment_is_probe || !is_retryable_now || payment_failed_permanently {
2463					let reason = if payment_failed_permanently {
2464						PaymentFailureReason::RecipientRejected
2465					} else {
2466						PaymentFailureReason::RetriesExhausted
2467					};
2468					payment.get_mut().mark_abandoned(reason);
2469					is_retryable_now = false;
2470				}
2471				if payment.get().remaining_parts() == 0 {
2472					if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } =
2473						payment.get()
2474					{
2475						if !payment_is_probe {
2476							full_failure_ev = Some(events::Event::PaymentFailed {
2477								payment_id: *payment_id,
2478								payment_hash: Some(*payment_hash),
2479								reason: *reason,
2480							});
2481						}
2482						payment.remove();
2483					}
2484				}
2485				is_retryable_now
2486			} else {
2487				log_trace!(
2488					self.logger,
2489					"Received duplicative fail for HTLC with payment_hash {}",
2490					&payment_hash
2491				);
2492				return;
2493			};
2494		core::mem::drop(outbounds);
2495		log_trace!(
2496			self.logger,
2497			"Failing outbound payment HTLC with payment_hash {}",
2498			&payment_hash
2499		);
2500
2501		let path_failure = {
2502			if payment_is_probe {
2503				if payment_failed_permanently {
2504					events::Event::ProbeSuccessful {
2505						payment_id: *payment_id,
2506						payment_hash: payment_hash.clone(),
2507						path: path.clone(),
2508					}
2509				} else {
2510					events::Event::ProbeFailed {
2511						payment_id: *payment_id,
2512						payment_hash: payment_hash.clone(),
2513						path: path.clone(),
2514						short_channel_id,
2515					}
2516				}
2517			} else {
2518				// If we miss abandoning the payment above, we *must* generate an event here or else the
2519				// payment will sit in our outbounds forever.
2520				if attempts_remaining && !already_awaiting_retry {
2521					debug_assert!(full_failure_ev.is_none());
2522				}
2523				events::Event::PaymentPathFailed {
2524					payment_id: Some(*payment_id),
2525					payment_hash: payment_hash.clone(),
2526					payment_failed_permanently,
2527					failure: events::PathFailure::OnPath { network_update },
2528					path: path.clone(),
2529					short_channel_id,
2530					#[cfg(any(test, feature = "_test_utils"))]
2531					error_code: onion_error_code.map(|f| f.failure_code()),
2532					#[cfg(any(test, feature = "_test_utils"))]
2533					error_data: onion_error_data,
2534					hold_times,
2535				}
2536			}
2537		};
2538		let mut pending_events = pending_events.lock().unwrap();
2539		let completion_action = completion_action
2540			.take()
2541			.map(|act| EventCompletionAction::ReleasePaymentCompleteChannelMonitorUpdate(act));
2542		if let Some(ev) = full_failure_ev {
2543			pending_events.push_back((path_failure, None));
2544			pending_events.push_back((ev, completion_action));
2545		} else {
2546			pending_events.push_back((path_failure, completion_action));
2547		}
2548	}
2549
2550	#[rustfmt::skip]
2551	pub(super) fn abandon_payment(
2552		&self, payment_id: PaymentId, reason: PaymentFailureReason,
2553		pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
2554	) {
2555		let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2556		if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
2557			payment.get_mut().mark_abandoned(reason);
2558			match payment.get() {
2559				PendingOutboundPayment::Abandoned { payment_hash, reason, .. } => {
2560					if payment.get().remaining_parts() == 0 {
2561						pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
2562							payment_id,
2563							payment_hash: Some(*payment_hash),
2564							reason: *reason,
2565						}, None));
2566						payment.remove();
2567					}
2568				},
2569				PendingOutboundPayment::AwaitingInvoice { .. }
2570					| PendingOutboundPayment::AwaitingOffer { .. } =>
2571				{
2572					pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
2573						payment_id,
2574						payment_hash: None,
2575						reason: Some(reason),
2576					}, None));
2577					payment.remove();
2578				},
2579				_ => {},
2580			}
2581		}
2582	}
2583
2584	#[cfg(test)]
2585	pub fn has_pending_payments(&self) -> bool {
2586		!self.pending_outbound_payments.lock().unwrap().is_empty()
2587	}
2588
2589	#[cfg(test)]
2590	pub fn clear_pending_payments(&self) {
2591		self.pending_outbound_payments.lock().unwrap().clear()
2592	}
2593
2594	#[rustfmt::skip]
2595	pub fn release_invoice_requests_awaiting_invoice(&self) -> Vec<(PaymentId, RetryableInvoiceRequest)> {
2596		if !self.awaiting_invoice.load(Ordering::Acquire) {
2597			return vec![];
2598		}
2599
2600		let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
2601		let invoice_requests = pending_outbound_payments
2602			.iter_mut()
2603			.filter_map(|(payment_id, payment)| {
2604				if let PendingOutboundPayment::AwaitingInvoice {
2605					retryable_invoice_request: Some(invreq), ..
2606				} = payment {
2607					if invreq.needs_retry {
2608						invreq.needs_retry = false;
2609						Some((*payment_id, invreq.clone()))
2610					} else { None }
2611				} else {
2612					None
2613				}
2614			})
2615			.collect();
2616
2617		self.awaiting_invoice.store(false, Ordering::Release);
2618		invoice_requests
2619	}
2620
2621	pub(super) fn insert_from_monitor_on_startup(
2622		&self, payment_id: PaymentId, payment_hash: PaymentHash, session_priv_bytes: [u8; 32],
2623		path: &Path, best_block_height: u32,
2624	) {
2625		let path_amt = path.final_value_msat();
2626		let path_fee = path.fee_msat();
2627
2628		macro_rules! new_retryable {
2629			() => {
2630				PendingOutboundPayment::Retryable {
2631					retry_strategy: None,
2632					attempts: PaymentAttempts::new(),
2633					payment_params: None,
2634					session_privs: hash_set_from_iter([session_priv_bytes]),
2635					payment_hash,
2636					payment_secret: None, // only used for retries, and we'll never retry on startup
2637					payment_metadata: None, // only used for retries, and we'll never retry on startup
2638					keysend_preimage: None, // only used for retries, and we'll never retry on startup
2639					invoice_request: None, // only used for retries, and we'll never retry on startup
2640					bolt12_invoice: None, // only used for retries, and we'll never retry on startup!
2641					custom_tlvs: Vec::new(), // only used for retries, and we'll never retry on startup
2642					pending_amt_msat: path_amt,
2643					pending_fee_msat: Some(path_fee),
2644					total_msat: path_amt,
2645					starting_block_height: best_block_height,
2646					remaining_max_total_routing_fee_msat: None, // only used for retries, and we'll never retry on startup
2647				}
2648			}
2649		}
2650
2651		match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
2652			hash_map::Entry::Occupied(mut entry) => {
2653				let newly_added = match entry.get() {
2654					PendingOutboundPayment::AwaitingOffer { .. }
2655					| PendingOutboundPayment::AwaitingInvoice { .. }
2656					| PendingOutboundPayment::InvoiceReceived { .. }
2657					| PendingOutboundPayment::StaticInvoiceReceived { .. } => {
2658						// If we've reached this point, it means we initiated a payment to a BOLT 12 invoice and
2659						// locked the htlc(s) into the `ChannelMonitor`(s), but failed to persist the
2660						// `ChannelManager` after transitioning from this state to `Retryable` prior to shutdown.
2661						// Therefore, we need to move this payment to `Retryable` now to avoid double-paying if
2662						// the recipient sends a duplicate invoice or release_held_htlc onion message.
2663						*entry.get_mut() = new_retryable!();
2664						true
2665					},
2666					PendingOutboundPayment::Legacy { .. }
2667					| PendingOutboundPayment::Retryable { .. }
2668					| PendingOutboundPayment::Fulfilled { .. }
2669					| PendingOutboundPayment::Abandoned { .. } => {
2670						entry.get_mut().insert(session_priv_bytes, &path)
2671					},
2672				};
2673				log_info!(self.logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
2674					if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), payment_hash);
2675			},
2676			hash_map::Entry::Vacant(entry) => {
2677				entry.insert(new_retryable!());
2678				log_info!(self.logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
2679					path_amt, payment_hash,  log_bytes!(session_priv_bytes));
2680			},
2681		}
2682	}
2683}
2684
2685/// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
2686/// payment probe.
2687pub(super) fn payment_is_probe(
2688	payment_hash: &PaymentHash, payment_id: &PaymentId, probing_cookie_secret: [u8; 32],
2689) -> bool {
2690	let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
2691	target_payment_hash == *payment_hash
2692}
2693
2694/// Returns the 'probing cookie' for the given [`PaymentId`].
2695fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
2696	let mut preimage = [0u8; 64];
2697	preimage[..32].copy_from_slice(&probing_cookie_secret);
2698	preimage[32..].copy_from_slice(&payment_id.0);
2699	PaymentHash(Sha256::hash(&preimage).to_byte_array())
2700}
2701
2702impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
2703	(0, Legacy) => {
2704		(0, session_privs, required),
2705	},
2706	(1, Fulfilled) => {
2707		(0, session_privs, required),
2708		(1, payment_hash, option),
2709		(3, timer_ticks_without_htlcs, (default_value, 0)),
2710		(5, total_msat, option),
2711	},
2712	(2, Retryable) => {
2713		(0, session_privs, required),
2714		(1, pending_fee_msat, option),
2715		(2, payment_hash, required),
2716		// Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
2717		// never see it - `payment_params` was added here after the field was added/required.
2718		(3, payment_params, (option: ReadableArgs, 0)),
2719		(4, payment_secret, option),
2720		(5, keysend_preimage, option),
2721		(6, total_msat, required),
2722		(7, payment_metadata, option),
2723		(8, pending_amt_msat, required),
2724		(9, custom_tlvs, optional_vec),
2725		(10, starting_block_height, required),
2726		(11, remaining_max_total_routing_fee_msat, option),
2727		(13, invoice_request, option),
2728		(15, bolt12_invoice, option),
2729		(not_written, retry_strategy, (static_value, None)),
2730		(not_written, attempts, (static_value, PaymentAttempts::new())),
2731	},
2732	(3, Abandoned) => {
2733		(0, session_privs, required),
2734		(1, reason, upgradable_option),
2735		(2, payment_hash, required),
2736		(3, total_msat, option),
2737	},
2738	(5, AwaitingInvoice) => {
2739		(0, expiration, required),
2740		(2, retry_strategy, required),
2741		(4, _max_total_routing_fee_msat, (legacy, u64,
2742			|us: &PendingOutboundPayment| match us {
2743				PendingOutboundPayment::AwaitingInvoice { route_params_config, .. } => route_params_config.max_total_routing_fee_msat,
2744				_ => None,
2745			}
2746		)),
2747		(5, retryable_invoice_request, option),
2748		(7, route_params_config, (default_value, (
2749			_max_total_routing_fee_msat.map_or(
2750				RouteParametersConfig::default(),
2751				|fee_msat| RouteParametersConfig::default().with_max_total_routing_fee_msat(fee_msat)
2752			)
2753		))),
2754	},
2755	(7, InvoiceReceived) => {
2756		(0, payment_hash, required),
2757		(2, retry_strategy, required),
2758		(4, _max_total_routing_fee_msat, (legacy, u64,
2759			|us: &PendingOutboundPayment| match us {
2760				PendingOutboundPayment::InvoiceReceived { route_params_config, .. } => route_params_config.max_total_routing_fee_msat,
2761				_ => None,
2762			}
2763		)),
2764		(5, route_params_config, (default_value, (
2765			_max_total_routing_fee_msat.map_or(
2766				RouteParametersConfig::default(),
2767				|fee_msat| RouteParametersConfig::default().with_max_total_routing_fee_msat(fee_msat)
2768			)
2769		))),
2770	},
2771	// Added in 0.1. Prior versions will drop these outbounds on downgrade, which is safe because no
2772	// HTLCs are in-flight.
2773	(9, StaticInvoiceReceived) => {
2774		(0, payment_hash, required),
2775		(2, keysend_preimage, required),
2776		(4, retry_strategy, required),
2777		(6, route_params, required),
2778		(8, invoice_request, required),
2779		(10, static_invoice, required),
2780		// Added in 0.2. Prior versions would have this TLV type defaulted to 0, which is safe because
2781		// the type is not used.
2782		(11, expiry_time, (default_value, Duration::from_secs(0))),
2783	},
2784	// Added in 0.1. Prior versions will drop these outbounds on downgrade, which is safe because
2785	// no HTLCs are in-flight.
2786	(11, AwaitingOffer) => {
2787		(0, expiration, required),
2788		(2, retry_strategy, required),
2789		(4, _max_total_routing_fee_msat, (legacy, u64,
2790			|us: &PendingOutboundPayment| match us {
2791				PendingOutboundPayment::AwaitingOffer { route_params_config, .. } => route_params_config.max_total_routing_fee_msat,
2792				_ => None,
2793			}
2794		)),
2795		(5, route_params_config, (default_value, (
2796			_max_total_routing_fee_msat.map_or(
2797				RouteParametersConfig::default(),
2798				|fee_msat| RouteParametersConfig::default().with_max_total_routing_fee_msat(fee_msat)
2799			)
2800		))),
2801		(6, amount_msats, required),
2802		(7, payer_note, option),
2803	},
2804);
2805
2806#[cfg(test)]
2807mod tests {
2808	use bitcoin::network::Network;
2809	use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
2810
2811	use core::time::Duration;
2812
2813	use crate::blinded_path::EmptyNodeIdLookUp;
2814	use crate::events::{Event, PathFailure, PaymentFailureReason};
2815	use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
2816	use crate::ln::inbound_payment::ExpandedKey;
2817	use crate::ln::outbound_payment::{
2818		Bolt12PaymentError, OutboundPayments, PendingOutboundPayment, Retry, RetryableSendFailure,
2819		StaleExpiration,
2820	};
2821	#[cfg(feature = "std")]
2822	use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
2823	use crate::offers::invoice_request::InvoiceRequest;
2824	use crate::offers::nonce::Nonce;
2825	use crate::offers::offer::OfferBuilder;
2826	use crate::offers::test_utils::*;
2827	use crate::routing::gossip::NetworkGraph;
2828	use crate::routing::router::{
2829		InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters,
2830		RouteParametersConfig,
2831	};
2832	use crate::sync::{Arc, Mutex, RwLock};
2833	use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
2834	use crate::types::payment::{PaymentHash, PaymentPreimage};
2835	use crate::util::errors::APIError;
2836	use crate::util::hash_tables::new_hash_map;
2837	use crate::util::test_utils;
2838
2839	use alloc::collections::VecDeque;
2840
2841	#[test]
2842	#[rustfmt::skip]
2843	fn test_recipient_onion_fields_with_custom_tlvs() {
2844		let onion_fields = RecipientOnionFields::spontaneous_empty();
2845
2846		let bad_type_range_tlvs = vec![
2847			(0, vec![42]),
2848			(1, vec![42; 32]),
2849		];
2850		assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
2851
2852		let keysend_tlv = vec![
2853			(5482373484, vec![42; 32]),
2854		];
2855		assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
2856
2857		let good_tlvs = vec![
2858			((1 << 16) + 1, vec![42]),
2859			((1 << 16) + 3, vec![42; 32]),
2860		];
2861		assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
2862	}
2863
2864	#[test]
2865	#[cfg(feature = "std")]
2866	fn fails_paying_after_expiration() {
2867		do_fails_paying_after_expiration(false);
2868		do_fails_paying_after_expiration(true);
2869	}
2870	#[cfg(feature = "std")]
2871	#[rustfmt::skip]
2872	fn do_fails_paying_after_expiration(on_retry: bool) {
2873		let logger = test_utils::TestLogger::new();
2874		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
2875		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2876		let scorer = RwLock::new(test_utils::TestScorer::new());
2877		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2878		let secp_ctx = Secp256k1::new();
2879		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2880
2881		let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
2882		let payment_params = PaymentParameters::from_node_id(
2883				PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
2884				0
2885			).with_expiry_time(past_expiry_time);
2886		let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
2887		let pending_events = Mutex::new(VecDeque::new());
2888		if on_retry {
2889			outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
2890				PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
2891				Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
2892				&&keys_manager, 0, None).unwrap();
2893			outbound_payments.find_route_and_send_payment(
2894				PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
2895				&|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &pending_events,
2896				&|_| Ok(()));
2897			let events = pending_events.lock().unwrap();
2898			assert_eq!(events.len(), 1);
2899			if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
2900				assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
2901			} else { panic!("Unexpected event"); }
2902		} else {
2903			let err = outbound_payments.send_payment(
2904				PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2905				Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
2906				&&keys_manager, &&keys_manager, 0, &pending_events, |_| Ok(())).unwrap_err();
2907			if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
2908		}
2909	}
2910
2911	#[test]
2912	fn find_route_error() {
2913		do_find_route_error(false);
2914		do_find_route_error(true);
2915	}
2916	#[rustfmt::skip]
2917	fn do_find_route_error(on_retry: bool) {
2918		let logger = test_utils::TestLogger::new();
2919		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
2920		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2921		let scorer = RwLock::new(test_utils::TestScorer::new());
2922		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2923		let secp_ctx = Secp256k1::new();
2924		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2925
2926		let payment_params = PaymentParameters::from_node_id(
2927			PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
2928		let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
2929		router.expect_find_route(route_params.clone(), Err(""));
2930
2931		let pending_events = Mutex::new(VecDeque::new());
2932		if on_retry {
2933			outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
2934				PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
2935				Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
2936				&&keys_manager, 0, None).unwrap();
2937			outbound_payments.find_route_and_send_payment(
2938				PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
2939				&|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &pending_events,
2940				&|_| Ok(()));
2941			let events = pending_events.lock().unwrap();
2942			assert_eq!(events.len(), 1);
2943			if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
2944		} else {
2945			let err = outbound_payments.send_payment(
2946				PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2947				Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
2948				&&keys_manager, &&keys_manager, 0, &pending_events, |_| Ok(())).unwrap_err();
2949			if let RetryableSendFailure::RouteNotFound = err {
2950			} else { panic!("Unexpected error"); }
2951		}
2952	}
2953
2954	#[test]
2955	#[rustfmt::skip]
2956	fn initial_send_payment_path_failed_evs() {
2957		let logger = test_utils::TestLogger::new();
2958		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
2959		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2960		let scorer = RwLock::new(test_utils::TestScorer::new());
2961		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2962		let secp_ctx = Secp256k1::new();
2963		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2964
2965		let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2966		let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
2967		let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
2968		let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
2969		let failed_scid = 42;
2970		let route = Route {
2971			paths: vec![Path { hops: vec![RouteHop {
2972				pubkey: receiver_pk,
2973				node_features: NodeFeatures::empty(),
2974				short_channel_id: failed_scid,
2975				channel_features: ChannelFeatures::empty(),
2976				fee_msat: 0,
2977				cltv_expiry_delta: 0,
2978				maybe_announced_channel: true,
2979			}], blinded_tail: None }],
2980			route_params: Some(route_params.clone()),
2981		};
2982		router.expect_find_route(route_params.clone(), Ok(route.clone()));
2983		let mut route_params_w_failed_scid = route_params.clone();
2984		route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
2985		let mut route_w_failed_scid = route.clone();
2986		route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
2987		router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
2988		router.expect_find_route(route_params.clone(), Ok(route.clone()));
2989		router.expect_find_route(route_params.clone(), Ok(route.clone()));
2990
2991		// Ensure that a ChannelUnavailable error will result in blaming an scid in the
2992		// PaymentPathFailed event.
2993		let pending_events = Mutex::new(VecDeque::new());
2994		outbound_payments.send_payment(
2995			PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2996			Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2997			&&keys_manager, &&keys_manager, 0, &pending_events,
2998			|_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2999		let mut events = pending_events.lock().unwrap();
3000		assert_eq!(events.len(), 2);
3001		if let Event::PaymentPathFailed {
3002			short_channel_id,
3003			failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
3004		{
3005			assert_eq!(short_channel_id, Some(failed_scid));
3006		} else { panic!("Unexpected event"); }
3007		if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
3008		events.clear();
3009		core::mem::drop(events);
3010
3011		// Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
3012		outbound_payments.send_payment(
3013			PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
3014			Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
3015			&&keys_manager, &&keys_manager, 0, &pending_events,
3016			|_| Err(APIError::MonitorUpdateInProgress)).unwrap();
3017		assert_eq!(pending_events.lock().unwrap().len(), 0);
3018
3019		// Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
3020		outbound_payments.send_payment(
3021			PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
3022			Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
3023			&&keys_manager, &&keys_manager, 0, &pending_events,
3024			|_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
3025		let events = pending_events.lock().unwrap();
3026		assert_eq!(events.len(), 2);
3027		if let Event::PaymentPathFailed {
3028			short_channel_id,
3029			failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
3030		{
3031			assert_eq!(short_channel_id, None);
3032		} else { panic!("Unexpected event"); }
3033		if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
3034	}
3035
3036	#[test]
3037	#[rustfmt::skip]
3038	fn removes_stale_awaiting_invoice_using_absolute_timeout() {
3039		let pending_events = Mutex::new(VecDeque::new());
3040		let logger = test_utils::TestLogger::new();
3041		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3042		let payment_id = PaymentId([0; 32]);
3043		let absolute_expiry = 100;
3044		let tick_interval = 10;
3045		let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
3046
3047		assert!(!outbound_payments.has_pending_payments());
3048		assert!(
3049			outbound_payments.add_new_awaiting_invoice(
3050				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3051			).is_ok()
3052		);
3053		assert!(outbound_payments.has_pending_payments());
3054
3055		for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
3056			let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
3057			outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
3058
3059			assert!(outbound_payments.has_pending_payments());
3060			assert!(pending_events.lock().unwrap().is_empty());
3061		}
3062
3063		let duration_since_epoch = Duration::from_secs(absolute_expiry);
3064		outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
3065
3066		assert!(!outbound_payments.has_pending_payments());
3067		assert!(!pending_events.lock().unwrap().is_empty());
3068		assert_eq!(
3069			pending_events.lock().unwrap().pop_front(),
3070			Some((Event::PaymentFailed {
3071				payment_id,
3072				payment_hash: None,
3073				reason: Some(PaymentFailureReason::InvoiceRequestExpired),
3074			}, None)),
3075		);
3076		assert!(pending_events.lock().unwrap().is_empty());
3077
3078		assert!(
3079			outbound_payments.add_new_awaiting_invoice(
3080				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3081			).is_ok()
3082		);
3083		assert!(outbound_payments.has_pending_payments());
3084
3085		assert!(
3086			outbound_payments.add_new_awaiting_invoice(
3087				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3088			).is_err()
3089		);
3090	}
3091
3092	#[test]
3093	#[rustfmt::skip]
3094	fn removes_stale_awaiting_invoice_using_timer_ticks() {
3095		let pending_events = Mutex::new(VecDeque::new());
3096		let logger = test_utils::TestLogger::new();
3097		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3098		let payment_id = PaymentId([0; 32]);
3099		let timer_ticks = 3;
3100		let expiration = StaleExpiration::TimerTicks(timer_ticks);
3101
3102		assert!(!outbound_payments.has_pending_payments());
3103		assert!(
3104			outbound_payments.add_new_awaiting_invoice(
3105				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3106			).is_ok()
3107		);
3108		assert!(outbound_payments.has_pending_payments());
3109
3110		for i in 0..timer_ticks {
3111			let duration_since_epoch = Duration::from_secs(i * 60);
3112			outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
3113
3114			assert!(outbound_payments.has_pending_payments());
3115			assert!(pending_events.lock().unwrap().is_empty());
3116		}
3117
3118		let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
3119		outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
3120
3121		assert!(!outbound_payments.has_pending_payments());
3122		assert!(!pending_events.lock().unwrap().is_empty());
3123		assert_eq!(
3124			pending_events.lock().unwrap().pop_front(),
3125			Some((Event::PaymentFailed {
3126				payment_id,
3127				payment_hash: None,
3128				reason: Some(PaymentFailureReason::InvoiceRequestExpired),
3129			}, None)),
3130		);
3131		assert!(pending_events.lock().unwrap().is_empty());
3132
3133		assert!(
3134			outbound_payments.add_new_awaiting_invoice(
3135				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3136			).is_ok()
3137		);
3138		assert!(outbound_payments.has_pending_payments());
3139
3140		assert!(
3141			outbound_payments.add_new_awaiting_invoice(
3142				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3143			).is_err()
3144		);
3145	}
3146
3147	#[test]
3148	#[rustfmt::skip]
3149	fn removes_abandoned_awaiting_invoice() {
3150		let pending_events = Mutex::new(VecDeque::new());
3151		let logger = test_utils::TestLogger::new();
3152		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3153		let payment_id = PaymentId([0; 32]);
3154		let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
3155
3156		assert!(!outbound_payments.has_pending_payments());
3157		assert!(
3158			outbound_payments.add_new_awaiting_invoice(
3159				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3160			).is_ok()
3161		);
3162		assert!(outbound_payments.has_pending_payments());
3163
3164		outbound_payments.abandon_payment(
3165			payment_id, PaymentFailureReason::UserAbandoned, &pending_events
3166		);
3167		assert!(!outbound_payments.has_pending_payments());
3168		assert!(!pending_events.lock().unwrap().is_empty());
3169		assert_eq!(
3170			pending_events.lock().unwrap().pop_front(),
3171			Some((Event::PaymentFailed {
3172				payment_id, payment_hash: None, reason: Some(PaymentFailureReason::UserAbandoned),
3173			}, None)),
3174		);
3175		assert!(pending_events.lock().unwrap().is_empty());
3176	}
3177
3178	#[cfg(feature = "std")]
3179	#[test]
3180	#[rustfmt::skip]
3181	fn fails_sending_payment_for_expired_bolt12_invoice() {
3182		let logger = test_utils::TestLogger::new();
3183		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
3184		let scorer = RwLock::new(test_utils::TestScorer::new());
3185		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
3186		let secp_ctx = Secp256k1::new();
3187		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
3188		let expanded_key = ExpandedKey::new([42; 32]);
3189		let nonce = Nonce([0; 16]);
3190
3191		let pending_events = Mutex::new(VecDeque::new());
3192		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3193		let payment_id = PaymentId([0; 32]);
3194		let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
3195
3196		assert!(
3197			outbound_payments.add_new_awaiting_invoice(
3198				payment_id, expiration, Retry::Attempts(0), RouteParametersConfig::default(), None,
3199			).is_ok()
3200		);
3201		assert!(outbound_payments.has_pending_payments());
3202
3203		let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
3204		let invoice = OfferBuilder::new(recipient_pubkey())
3205			.amount_msats(1000)
3206			.build().unwrap()
3207			.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
3208			.build_and_sign().unwrap()
3209			.respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
3210			.build().unwrap()
3211			.sign(recipient_sign).unwrap();
3212
3213		assert_eq!(
3214			outbound_payments.send_payment_for_bolt12_invoice(
3215				&invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
3216				|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
3217				&secp_ctx, 0, &pending_events, |_| panic!()
3218			),
3219			Err(Bolt12PaymentError::SendingFailed(RetryableSendFailure::PaymentExpired)),
3220		);
3221		assert!(!outbound_payments.has_pending_payments());
3222
3223		let payment_hash = Some(invoice.payment_hash());
3224		let reason = Some(PaymentFailureReason::PaymentExpired);
3225
3226		assert!(!pending_events.lock().unwrap().is_empty());
3227		assert_eq!(
3228			pending_events.lock().unwrap().pop_front(),
3229			Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
3230		);
3231		assert!(pending_events.lock().unwrap().is_empty());
3232	}
3233
3234	#[test]
3235	#[rustfmt::skip]
3236	fn fails_finding_route_for_bolt12_invoice() {
3237		let logger = test_utils::TestLogger::new();
3238		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
3239		let scorer = RwLock::new(test_utils::TestScorer::new());
3240		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
3241		let secp_ctx = Secp256k1::new();
3242		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
3243
3244		let pending_events = Mutex::new(VecDeque::new());
3245		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3246		let expanded_key = ExpandedKey::new([42; 32]);
3247		let nonce = Nonce([0; 16]);
3248		let payment_id = PaymentId([0; 32]);
3249		let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
3250
3251		let invoice = OfferBuilder::new(recipient_pubkey())
3252			.amount_msats(1000)
3253			.build().unwrap()
3254			.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
3255			.build_and_sign().unwrap()
3256			.respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
3257			.build().unwrap()
3258			.sign(recipient_sign).unwrap();
3259
3260		let route_params_config = RouteParametersConfig::default().with_max_total_routing_fee_msat(invoice.amount_msats() / 100 + 50_000);
3261
3262		assert!(
3263			outbound_payments.add_new_awaiting_invoice(
3264				payment_id, expiration, Retry::Attempts(0),
3265				route_params_config, None,
3266			).is_ok()
3267		);
3268		assert!(outbound_payments.has_pending_payments());
3269
3270		let route_params = RouteParameters::from_payment_params_and_value(
3271			PaymentParameters::from_bolt12_invoice(&invoice),
3272			invoice.amount_msats(),
3273		);
3274		router.expect_find_route(route_params, Err(""));
3275
3276		assert_eq!(
3277			outbound_payments.send_payment_for_bolt12_invoice(
3278				&invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
3279				|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
3280				&secp_ctx, 0, &pending_events, |_| panic!()
3281			),
3282			Err(Bolt12PaymentError::SendingFailed(RetryableSendFailure::RouteNotFound)),
3283		);
3284		assert!(!outbound_payments.has_pending_payments());
3285
3286		let payment_hash = Some(invoice.payment_hash());
3287		let reason = Some(PaymentFailureReason::RouteNotFound);
3288
3289		assert!(!pending_events.lock().unwrap().is_empty());
3290		assert_eq!(
3291			pending_events.lock().unwrap().pop_front(),
3292			Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
3293		);
3294		assert!(pending_events.lock().unwrap().is_empty());
3295	}
3296
3297	#[test]
3298	#[rustfmt::skip]
3299	fn sends_payment_for_bolt12_invoice() {
3300		let logger = test_utils::TestLogger::new();
3301		let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
3302		let scorer = RwLock::new(test_utils::TestScorer::new());
3303		let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
3304		let secp_ctx = Secp256k1::new();
3305		let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
3306
3307		let pending_events = Mutex::new(VecDeque::new());
3308		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3309		let expanded_key = ExpandedKey::new([42; 32]);
3310		let nonce = Nonce([0; 16]);
3311		let payment_id = PaymentId([0; 32]);
3312		let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
3313
3314		let invoice = OfferBuilder::new(recipient_pubkey())
3315			.amount_msats(1000)
3316			.build().unwrap()
3317			.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
3318			.build_and_sign().unwrap()
3319			.respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
3320			.build().unwrap()
3321			.sign(recipient_sign).unwrap();
3322
3323		let route_params = RouteParameters {
3324			payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
3325			final_value_msat: invoice.amount_msats(),
3326			max_total_routing_fee_msat: Some(1234),
3327		};
3328		router.expect_find_route(
3329			route_params.clone(),
3330			Ok(Route {
3331				paths: vec![
3332					Path {
3333						hops: vec![
3334							RouteHop {
3335								pubkey: recipient_pubkey(),
3336								node_features: NodeFeatures::empty(),
3337								short_channel_id: 42,
3338								channel_features: ChannelFeatures::empty(),
3339								fee_msat: invoice.amount_msats(),
3340								cltv_expiry_delta: 0,
3341								maybe_announced_channel: true,
3342							}
3343						],
3344						blinded_tail: None,
3345					}
3346				],
3347				route_params: Some(route_params),
3348			})
3349		);
3350
3351		assert!(!outbound_payments.has_pending_payments());
3352		assert_eq!(
3353			outbound_payments.send_payment_for_bolt12_invoice(
3354				&invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
3355				|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
3356				&secp_ctx, 0, &pending_events, |_| panic!()
3357			),
3358			Err(Bolt12PaymentError::UnexpectedInvoice),
3359		);
3360		assert!(!outbound_payments.has_pending_payments());
3361		assert!(pending_events.lock().unwrap().is_empty());
3362
3363		let route_params_config = RouteParametersConfig::default().with_max_total_routing_fee_msat(1234);
3364
3365		assert!(
3366			outbound_payments.add_new_awaiting_invoice(
3367				payment_id, expiration, Retry::Attempts(0), route_params_config, None,
3368			).is_ok()
3369		);
3370		assert!(outbound_payments.has_pending_payments());
3371
3372		assert_eq!(
3373			outbound_payments.send_payment_for_bolt12_invoice(
3374				&invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
3375				|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
3376				&secp_ctx, 0, &pending_events, |_| Ok(())
3377			),
3378			Ok(()),
3379		);
3380		assert!(outbound_payments.has_pending_payments());
3381		assert!(pending_events.lock().unwrap().is_empty());
3382
3383		assert_eq!(
3384			outbound_payments.send_payment_for_bolt12_invoice(
3385				&invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
3386				|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
3387				&secp_ctx, 0, &pending_events, |_| panic!()
3388			),
3389			Err(Bolt12PaymentError::DuplicateInvoice),
3390		);
3391		assert!(outbound_payments.has_pending_payments());
3392		assert!(pending_events.lock().unwrap().is_empty());
3393	}
3394
3395	#[rustfmt::skip]
3396	fn dummy_invoice_request() -> InvoiceRequest {
3397		let expanded_key = ExpandedKey::new([42; 32]);
3398		let entropy = FixedEntropy {};
3399		let nonce = Nonce::from_entropy_source(&entropy);
3400		let secp_ctx = Secp256k1::new();
3401		let payment_id = PaymentId([1; 32]);
3402
3403		OfferBuilder::new(recipient_pubkey())
3404			.amount_msats(1000)
3405			.build().unwrap()
3406			.request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)
3407			.unwrap()
3408			.build_and_sign()
3409			.unwrap()
3410	}
3411
3412	#[test]
3413	#[rustfmt::skip]
3414	fn time_out_unreleased_async_payments() {
3415		let pending_events = Mutex::new(VecDeque::new());
3416		let logger = test_utils::TestLogger::new();
3417		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3418		let payment_id = PaymentId([0; 32]);
3419		let absolute_expiry = 60;
3420
3421		let mut outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3422		let payment_params = PaymentParameters::from_node_id(test_utils::pubkey(42), 0)
3423			.with_expiry_time(absolute_expiry);
3424		let route_params = RouteParameters {
3425			payment_params,
3426			final_value_msat: 0,
3427			max_total_routing_fee_msat: None,
3428		};
3429		let payment_hash = PaymentHash([0; 32]);
3430		let outbound = PendingOutboundPayment::StaticInvoiceReceived {
3431			payment_hash,
3432			keysend_preimage: PaymentPreimage([0; 32]),
3433			retry_strategy: Retry::Attempts(0),
3434			route_params,
3435			invoice_request: dummy_invoice_request(),
3436			static_invoice: dummy_static_invoice(),
3437			expiry_time: Duration::from_secs(absolute_expiry + 2),
3438		};
3439		outbounds.insert(payment_id, outbound);
3440		core::mem::drop(outbounds);
3441
3442		// The payment will not be removed if it isn't expired yet.
3443		outbound_payments.remove_stale_payments(Duration::from_secs(absolute_expiry), &pending_events);
3444		let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3445		assert_eq!(outbounds.len(), 1);
3446		let events = pending_events.lock().unwrap();
3447		assert_eq!(events.len(), 0);
3448		core::mem::drop(outbounds);
3449		core::mem::drop(events);
3450
3451		outbound_payments.remove_stale_payments(Duration::from_secs(absolute_expiry + 1), &pending_events);
3452		let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3453		assert_eq!(outbounds.len(), 0);
3454		let events = pending_events.lock().unwrap();
3455		assert_eq!(events.len(), 1);
3456		assert_eq!(events[0], (Event::PaymentFailed {
3457			payment_hash: Some(payment_hash),
3458			payment_id,
3459			reason: Some(PaymentFailureReason::PaymentExpired),
3460		}, None));
3461	}
3462
3463	#[test]
3464	#[rustfmt::skip]
3465	fn abandon_unreleased_async_payment() {
3466		let pending_events = Mutex::new(VecDeque::new());
3467		let logger = test_utils::TestLogger::new();
3468		let outbound_payments = OutboundPayments::new(new_hash_map(), &logger);
3469		let payment_id = PaymentId([0; 32]);
3470		let absolute_expiry = 60;
3471
3472		let mut outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3473		let payment_params = PaymentParameters::from_node_id(test_utils::pubkey(42), 0)
3474			.with_expiry_time(absolute_expiry);
3475		let route_params = RouteParameters {
3476			payment_params,
3477			final_value_msat: 0,
3478			max_total_routing_fee_msat: None,
3479		};
3480		let payment_hash = PaymentHash([0; 32]);
3481		let outbound = PendingOutboundPayment::StaticInvoiceReceived {
3482			payment_hash,
3483			keysend_preimage: PaymentPreimage([0; 32]),
3484			retry_strategy: Retry::Attempts(0),
3485			route_params,
3486			invoice_request: dummy_invoice_request(),
3487			static_invoice: dummy_static_invoice(),
3488			expiry_time: now(),
3489		};
3490		outbounds.insert(payment_id, outbound);
3491		core::mem::drop(outbounds);
3492
3493		outbound_payments.abandon_payment(
3494			payment_id, PaymentFailureReason::UserAbandoned, &pending_events
3495		);
3496		let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3497		assert_eq!(outbounds.len(), 0);
3498		let events = pending_events.lock().unwrap();
3499		assert_eq!(events.len(), 1);
3500		assert_eq!(events[0], (Event::PaymentFailed {
3501			payment_hash: Some(payment_hash),
3502			payment_id,
3503			reason: Some(PaymentFailureReason::UserAbandoned),
3504		}, None));
3505	}
3506}