lightning/ln/
invoice_utils.rs

1//! Convenient utilities to create an invoice.
2
3use lightning_invoice::{
4	Bolt11Invoice, CreationError, Currency, InvoiceBuilder, SignOrCreationError,
5};
6use lightning_invoice::{Bolt11InvoiceDescription, Description, Sha256};
7
8use crate::prelude::*;
9
10use crate::ln::channel_state::ChannelDetails;
11use crate::ln::channelmanager::{
12	PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA, MIN_FINAL_CLTV_EXPIRY_DELTA,
13};
14use crate::ln::inbound_payment::{create, create_from_hash};
15use crate::routing::gossip::RoutingFees;
16use crate::routing::router::{RouteHint, RouteHintHop};
17use crate::sign::{EntropySource, NodeSigner, Recipient};
18use crate::types::payment::PaymentHash;
19use crate::util::logger::{Logger, Record};
20use alloc::collections::{btree_map, BTreeMap};
21use bitcoin::hashes::Hash;
22use bitcoin::secp256k1::PublicKey;
23#[cfg(not(feature = "std"))]
24use core::iter::Iterator;
25use core::ops::Deref;
26use core::time::Duration;
27
28/// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
29/// See [`PhantomKeysManager`] for more information on phantom node payments.
30///
31/// `phantom_route_hints` parameter:
32/// * Contains channel info for all nodes participating in the phantom invoice
33/// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
34///   participating node
35/// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
36///   updated when a channel becomes disabled or closes
37/// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
38///   may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
39///   down
40///
41/// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
42/// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
43/// If `None` is provided for `payment_hash`, then one will be created.
44///
45/// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
46/// in excess of the current time.
47///
48/// `duration_since_epoch` is the current time since epoch in seconds.
49///
50/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
51/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3.
52/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
53/// confirmations during routing.
54///
55/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
56/// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
57/// requirement).
58///
59/// [`PhantomKeysManager`]: crate::sign::PhantomKeysManager
60/// [`ChannelManager::get_phantom_route_hints`]: crate::ln::channelmanager::ChannelManager::get_phantom_route_hints
61/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
62/// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
63/// [`PhantomRouteHints::channels`]: crate::ln::channelmanager::PhantomRouteHints::channels
64/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: crate::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
65#[cfg_attr(feature = "std", doc = "")]
66#[cfg_attr(
67	feature = "std",
68	doc = "This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not available and the current time is supplied by the caller."
69)]
70pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
71	amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
72	invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>,
73	entropy_source: ES, node_signer: NS, logger: L, network: Currency,
74	min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
75) -> Result<Bolt11Invoice, SignOrCreationError<()>>
76where
77	ES::Target: EntropySource,
78	NS::Target: NodeSigner,
79	L::Target: Logger,
80{
81	let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
82	let description = Bolt11InvoiceDescription::Direct(description);
83	_create_phantom_invoice::<ES, NS, L>(
84		amt_msat,
85		payment_hash,
86		description,
87		invoice_expiry_delta_secs,
88		phantom_route_hints,
89		entropy_source,
90		node_signer,
91		logger,
92		network,
93		min_final_cltv_expiry_delta,
94		duration_since_epoch,
95	)
96}
97
98/// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
99/// See [`PhantomKeysManager`] for more information on phantom node payments.
100///
101/// `phantom_route_hints` parameter:
102/// * Contains channel info for all nodes participating in the phantom invoice
103/// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
104///   participating node
105/// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
106///   updated when a channel becomes disabled or closes
107/// * Note that the route hints generated from `phantom_route_hints` will be limited to a maximum
108///   of 3 hints to ensure that the invoice can be scanned in a QR code. These hints are selected
109///   in the order that the nodes in `PhantomRouteHints` are specified, selecting one hint per node
110///   until the maximum is hit. Callers may provide as many `PhantomRouteHints::channels` as
111///   desired, but note that some nodes will be trimmed if more than 3 nodes are provided.
112///
113/// `description_hash` is a SHA-256 hash of the description text
114///
115/// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
116/// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
117/// If `None` is provided for `payment_hash`, then one will be created.
118///
119/// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
120/// in excess of the current time.
121///
122/// `duration_since_epoch` is the current time since epoch in seconds.
123///
124/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
125/// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
126/// requirement).
127///
128/// [`PhantomKeysManager`]: crate::sign::PhantomKeysManager
129/// [`ChannelManager::get_phantom_route_hints`]: crate::ln::channelmanager::ChannelManager::get_phantom_route_hints
130/// [`ChannelManager::create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
131/// [`ChannelManager::create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
132/// [`PhantomRouteHints::channels`]: crate::ln::channelmanager::PhantomRouteHints::channels
133#[cfg_attr(feature = "std", doc = "")]
134#[cfg_attr(
135	feature = "std",
136	doc = "This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not available and the current time is supplied by the caller."
137)]
138pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
139	amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
140	description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
141	node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>,
142	duration_since_epoch: Duration,
143) -> Result<Bolt11Invoice, SignOrCreationError<()>>
144where
145	ES::Target: EntropySource,
146	NS::Target: NodeSigner,
147	L::Target: Logger,
148{
149	_create_phantom_invoice::<ES, NS, L>(
150		amt_msat,
151		payment_hash,
152		Bolt11InvoiceDescription::Hash(description_hash),
153		invoice_expiry_delta_secs,
154		phantom_route_hints,
155		entropy_source,
156		node_signer,
157		logger,
158		network,
159		min_final_cltv_expiry_delta,
160		duration_since_epoch,
161	)
162}
163
164const MAX_CHANNEL_HINTS: usize = 3;
165
166fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
167	amt_msat: Option<u64>, payment_hash: Option<PaymentHash>,
168	description: Bolt11InvoiceDescription, invoice_expiry_delta_secs: u32,
169	phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES, node_signer: NS, logger: L,
170	network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
171) -> Result<Bolt11Invoice, SignOrCreationError<()>>
172where
173	ES::Target: EntropySource,
174	NS::Target: NodeSigner,
175	L::Target: Logger,
176{
177	if phantom_route_hints.is_empty() {
178		return Err(SignOrCreationError::CreationError(CreationError::MissingRouteHints));
179	}
180
181	if min_final_cltv_expiry_delta.is_some()
182		&& min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA
183	{
184		return Err(SignOrCreationError::CreationError(
185			CreationError::MinFinalCltvExpiryDeltaTooShort,
186		));
187	}
188
189	let invoice = match description {
190		Bolt11InvoiceDescription::Direct(description) => {
191			InvoiceBuilder::new(network).description(description.into_inner().0)
192		},
193		Bolt11InvoiceDescription::Hash(hash) => {
194			InvoiceBuilder::new(network).description_hash(hash.0)
195		},
196	};
197
198	let keys = node_signer.get_expanded_key();
199	let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
200		let payment_secret = create_from_hash(
201			&keys,
202			amt_msat,
203			payment_hash,
204			invoice_expiry_delta_secs,
205			duration_since_epoch.as_secs(),
206			min_final_cltv_expiry_delta,
207		)
208		.map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
209		(payment_hash, payment_secret)
210	} else {
211		create(
212			&keys,
213			amt_msat,
214			invoice_expiry_delta_secs,
215			&entropy_source,
216			duration_since_epoch.as_secs(),
217			min_final_cltv_expiry_delta,
218		)
219		.map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
220	};
221
222	log_trace!(
223		logger,
224		"Creating phantom invoice from {} participating nodes with payment hash {}",
225		phantom_route_hints.len(),
226		&payment_hash
227	);
228
229	let mut invoice = invoice
230		.duration_since_epoch(duration_since_epoch)
231		.payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
232		.payment_secret(payment_secret)
233		.min_final_cltv_expiry_delta(
234			// Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
235			min_final_cltv_expiry_delta
236				.map(|x| x.saturating_add(3))
237				.unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA)
238				.into(),
239		)
240		.expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
241	if let Some(amt) = amt_msat {
242		invoice = invoice.amount_milli_satoshis(amt);
243	}
244
245	for route_hint in
246		select_phantom_hints(amt_msat, phantom_route_hints, logger).take(MAX_CHANNEL_HINTS)
247	{
248		invoice = invoice.private_route(route_hint);
249	}
250
251	let raw_invoice = match invoice.build_raw() {
252		Ok(inv) => inv,
253		Err(e) => return Err(SignOrCreationError::CreationError(e)),
254	};
255	let signature = node_signer.sign_invoice(&raw_invoice, Recipient::PhantomNode);
256	let signed_raw_invoice = raw_invoice.sign(|_| signature);
257	match signed_raw_invoice {
258		Ok(inv) => Ok(Bolt11Invoice::from_signed(inv).unwrap()),
259		Err(e) => Err(SignOrCreationError::SignError(e)),
260	}
261}
262
263/// Utility to select route hints for phantom invoices.
264/// See [`PhantomKeysManager`] for more information on phantom node payments.
265///
266/// To ensure that the phantom invoice is still readable by QR code, we limit to 3 hints per invoice:
267/// * Select up to three channels per node.
268/// * Select one hint from each node, up to three hints or until we run out of hints.
269///
270/// [`PhantomKeysManager`]: crate::sign::PhantomKeysManager
271fn select_phantom_hints<L: Deref>(
272	amt_msat: Option<u64>, phantom_route_hints: Vec<PhantomRouteHints>, logger: L,
273) -> impl Iterator<Item = RouteHint>
274where
275	L::Target: Logger,
276{
277	let mut phantom_hints: Vec<_> = Vec::new();
278
279	for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
280		log_trace!(
281			logger,
282			"Generating phantom route hints for node {}",
283			log_pubkey!(real_node_pubkey)
284		);
285		let route_hints = sort_and_filter_channels(channels, amt_msat, &logger);
286
287		// If we have any public channel, the route hints from `sort_and_filter_channels` will be
288		// empty. In that case we create a RouteHint on which we will push a single hop with the
289		// phantom route into the invoice, and let the sender find the path to the `real_node_pubkey`
290		// node by looking at our public channels.
291		let empty_route_hints = route_hints.len() == 0;
292		let mut have_pushed_empty = false;
293		let route_hints = route_hints
294			.chain(core::iter::from_fn(move || {
295				if empty_route_hints && !have_pushed_empty {
296					// set flag of having handled the empty route_hints and ensure empty vector
297					// returned only once
298					have_pushed_empty = true;
299					Some(RouteHint(Vec::new()))
300				} else {
301					None
302				}
303			}))
304			.map(move |mut hint| {
305				hint.0.push(RouteHintHop {
306					src_node_id: real_node_pubkey,
307					short_channel_id: phantom_scid,
308					fees: RoutingFees { base_msat: 0, proportional_millionths: 0 },
309					cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
310					htlc_minimum_msat: None,
311					htlc_maximum_msat: None,
312				});
313				hint
314			});
315
316		phantom_hints.push(route_hints);
317	}
318
319	// We have one vector per real node involved in creating the phantom invoice. To distribute
320	// the hints across our real nodes we add one hint from each in turn until no node has any hints
321	// left (if one node has more hints than any other, these will accumulate at the end of the
322	// vector).
323	rotate_through_iterators(phantom_hints)
324}
325
326/// Draw items iteratively from multiple iterators.  The items are retrieved by index and
327/// rotates through the iterators - first the zero index then the first index then second index, etc.
328fn rotate_through_iterators<T, I: Iterator<Item = T>>(mut vecs: Vec<I>) -> impl Iterator<Item = T> {
329	let mut iterations = 0;
330
331	core::iter::from_fn(move || {
332		let mut exhausted_iterators = 0;
333		loop {
334			if vecs.is_empty() {
335				return None;
336			}
337			let next_idx = iterations % vecs.len();
338			iterations += 1;
339			if let Some(item) = vecs[next_idx].next() {
340				return Some(item);
341			}
342			// exhausted_vectors increase when the "next_idx" vector is exhausted
343			exhausted_iterators += 1;
344			// The check for exhausted iterators gets reset to 0 after each yield of `Some()`
345			// The loop will return None when all of the nested iterators are exhausted
346			if exhausted_iterators == vecs.len() {
347				return None;
348			}
349		}
350	})
351}
352
353/// Sorts and filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
354/// in the invoice.
355///
356/// The filtering is based on the following criteria:
357/// * Only one channel per counterparty node
358/// * If the counterparty has a channel that is above the `min_inbound_capacity_msat` + 10% scaling
359///   factor (to allow some margin for change in inbound), select the channel with the lowest
360///   inbound capacity that is above this threshold.
361/// * If no `min_inbound_capacity_msat` is specified, or the counterparty has no channels above the
362///   minimum + 10% scaling factor, select the channel with the highest inbound capacity per counterparty.
363/// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
364///   `is_usable` (i.e. the peer is connected).
365/// * If any public channel exists, only public [`RouteHint`]s will be returned.
366/// * If any public, announced, channel exists (i.e. a channel with 7+ confs, to ensure the
367///   announcement has had a chance to propagate), no [`RouteHint`]s will be returned, as the
368///   sender is expected to find the path by looking at the public channels instead.
369/// * Limited to a total of 3 channels.
370/// * Sorted by lowest inbound capacity if an online channel with the minimum amount requested exists,
371///   otherwise sort by highest inbound capacity to give the payment the best chance of succeeding.
372pub(super) fn sort_and_filter_channels<L: Deref>(
373	channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L,
374) -> impl ExactSizeIterator<Item = RouteHint>
375where
376	L::Target: Logger,
377{
378	let mut filtered_channels: BTreeMap<PublicKey, ChannelDetails> = BTreeMap::new();
379	let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
380	let mut min_capacity_channel_exists = false;
381	let mut online_channel_exists = false;
382	let mut online_min_capacity_channel_exists = false;
383	let mut has_pub_unconf_chan = false;
384
385	let route_hint_from_channel = |channel: ChannelDetails| {
386		let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
387		RouteHint(vec![RouteHintHop {
388			src_node_id: channel.counterparty.node_id,
389			short_channel_id: channel.get_inbound_payment_scid().unwrap(),
390			fees: RoutingFees {
391				base_msat: forwarding_info.fee_base_msat,
392				proportional_millionths: forwarding_info.fee_proportional_millionths,
393			},
394			cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
395			htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
396			htlc_maximum_msat: channel.inbound_htlc_maximum_msat,
397		}])
398	};
399
400	log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
401	for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
402		let logger = WithChannelDetails::from(logger, &channel);
403		if channel.get_inbound_payment_scid().is_none()
404			|| channel.counterparty.forwarding_info.is_none()
405		{
406			log_trace!(logger, "Ignoring channel {} for invoice route hints", &channel.channel_id);
407			continue;
408		}
409
410		if channel.is_announced {
411			if channel.confirmations.is_some() && channel.confirmations < Some(7) {
412				// If we have a public channel, but it doesn't have enough confirmations to (yet)
413				// be in the public network graph (and have gotten a chance to propagate), include
414				// route hints but only for public channels to protect private channel privacy.
415				has_pub_unconf_chan = true;
416			} else {
417				// If any public channel exists, return no hints and let the sender
418				// look at the public channels instead.
419				log_trace!(
420					logger,
421					"Not including channels in invoice route hints on account of public channel {}",
422					&channel.channel_id
423				);
424				return vec![].into_iter().take(MAX_CHANNEL_HINTS).map(route_hint_from_channel);
425			}
426		}
427
428		if channel.inbound_capacity_msat >= min_inbound_capacity {
429			if !min_capacity_channel_exists {
430				log_trace!(
431					logger,
432					"Channel with enough inbound capacity exists for invoice route hints"
433				);
434				min_capacity_channel_exists = true;
435			}
436
437			if channel.is_usable {
438				online_min_capacity_channel_exists = true;
439			}
440		}
441
442		if channel.is_usable && !online_channel_exists {
443			log_trace!(logger, "Channel with connected peer exists for invoice route hints");
444			online_channel_exists = true;
445		}
446
447		match filtered_channels.entry(channel.counterparty.node_id) {
448			btree_map::Entry::Occupied(mut entry) => {
449				let current_max_capacity = entry.get().inbound_capacity_msat;
450				// If this channel is public and the previous channel is not, ensure we replace the
451				// previous channel to avoid announcing non-public channels.
452				let new_now_public = channel.is_announced && !entry.get().is_announced;
453				// Decide whether we prefer the currently selected channel with the node to the new one,
454				// based on their inbound capacity.
455				let prefer_current = prefer_current_channel(
456					min_inbound_capacity_msat,
457					current_max_capacity,
458					channel.inbound_capacity_msat,
459				);
460				// If the public-ness of the channel has not changed (in which case simply defer to
461				// `new_now_public), and this channel has more desirable inbound than the incumbent,
462				// prefer to include this channel.
463				let new_channel_preferable =
464					channel.is_announced == entry.get().is_announced && !prefer_current;
465
466				if new_now_public || new_channel_preferable {
467					log_trace!(logger,
468						"Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
469						log_pubkey!(channel.counterparty.node_id),
470						&channel.channel_id, channel.short_channel_id,
471						channel.inbound_capacity_msat,
472						&entry.get().channel_id, entry.get().short_channel_id,
473						current_max_capacity);
474					entry.insert(channel);
475				} else {
476					log_trace!(logger,
477						"Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
478						log_pubkey!(channel.counterparty.node_id),
479						&entry.get().channel_id, entry.get().short_channel_id,
480						current_max_capacity,
481						&channel.channel_id, channel.short_channel_id,
482						channel.inbound_capacity_msat);
483				}
484			},
485			btree_map::Entry::Vacant(entry) => {
486				entry.insert(channel);
487			},
488		}
489	}
490
491	// If all channels are private, prefer to return route hints which have a higher capacity than
492	// the payment value and where we're currently connected to the channel counterparty.
493	// Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
494	// those which meet at least one criteria.
495	let mut eligible_channels = filtered_channels
496		.into_iter()
497		.map(|(_, channel)| channel)
498		.filter(|channel| {
499			let logger = WithChannelDetails::from(logger, &channel);
500			let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
501			let include_channel = if has_pub_unconf_chan {
502				// If we have a public channel, but it doesn't have enough confirmations to (yet)
503				// be in the public network graph (and have gotten a chance to propagate), include
504				// route hints but only for public channels to protect private channel privacy.
505				channel.is_announced
506			} else if online_min_capacity_channel_exists {
507				has_enough_capacity && channel.is_usable
508			} else if min_capacity_channel_exists && online_channel_exists {
509				// If there are some online channels and some min_capacity channels, but no
510				// online-and-min_capacity channels, just include the min capacity ones and ignore
511				// online-ness.
512				has_enough_capacity
513			} else if min_capacity_channel_exists {
514				has_enough_capacity
515			} else if online_channel_exists {
516				channel.is_usable
517			} else {
518				true
519			};
520
521			if include_channel {
522				log_trace!(
523					logger,
524					"Including channel {} in invoice route hints",
525					&channel.channel_id
526				);
527			} else if !has_enough_capacity {
528				log_trace!(
529					logger,
530					"Ignoring channel {} without enough capacity for invoice route hints",
531					&channel.channel_id
532				);
533			} else {
534				debug_assert!(!channel.is_usable || (has_pub_unconf_chan && !channel.is_announced));
535				log_trace!(
536					logger,
537					"Ignoring channel {} with disconnected peer",
538					&channel.channel_id
539				);
540			}
541
542			include_channel
543		})
544		.collect::<Vec<ChannelDetails>>();
545
546	eligible_channels.sort_unstable_by(|a, b| {
547		if online_min_capacity_channel_exists {
548			a.inbound_capacity_msat.cmp(&b.inbound_capacity_msat)
549		} else {
550			b.inbound_capacity_msat.cmp(&a.inbound_capacity_msat)
551		}
552	});
553
554	eligible_channels.into_iter().take(MAX_CHANNEL_HINTS).map(route_hint_from_channel)
555}
556
557/// prefer_current_channel chooses a channel to use for route hints between a currently selected and candidate
558/// channel based on the inbound capacity of each channel and the minimum inbound capacity requested for the hints,
559/// returning true if the current channel should be preferred over the candidate channel.
560/// * If no minimum amount is requested, the channel with the most inbound is chosen to maximize the chances that a
561///   payment of any size will succeed.
562/// * If we have channels with inbound above our minimum requested inbound (plus a 10% scaling factor, expressed as a
563///   percentage) then we choose the lowest inbound channel with above this amount. If we have sufficient inbound
564///   channels, we don't want to deplete our larger channels with small payments (the off-chain version of "grinding
565///   our change").
566/// * If no channel above our minimum amount exists, then we just prefer the channel with the most inbound to give
567///   payments the best chance of succeeding in multiple parts.
568fn prefer_current_channel(
569	min_inbound_capacity_msat: Option<u64>, current_channel: u64, candidate_channel: u64,
570) -> bool {
571	// If no min amount is given for the hints, err of the side of caution and choose the largest channel inbound to
572	// maximize chances of any payment succeeding.
573	if min_inbound_capacity_msat.is_none() {
574		return current_channel > candidate_channel;
575	}
576
577	let scaled_min_inbound = min_inbound_capacity_msat.unwrap() * 110;
578	let current_sufficient = current_channel * 100 >= scaled_min_inbound;
579	let candidate_sufficient = candidate_channel * 100 >= scaled_min_inbound;
580
581	if current_sufficient && candidate_sufficient {
582		return current_channel < candidate_channel;
583	} else if current_sufficient {
584		return true;
585	} else if candidate_sufficient {
586		return false;
587	}
588
589	current_channel > candidate_channel
590}
591
592/// Adds relevant context to a [`Record`] before passing it to the wrapped [`Logger`].
593struct WithChannelDetails<'a, 'b, L: Deref>
594where
595	L::Target: Logger,
596{
597	/// The logger to delegate to after adding context to the record.
598	logger: &'a L,
599	/// The [`ChannelDetails`] for adding relevant context to the logged record.
600	details: &'b ChannelDetails,
601}
602
603impl<'a, 'b, L: Deref> Logger for WithChannelDetails<'a, 'b, L>
604where
605	L::Target: Logger,
606{
607	fn log(&self, mut record: Record) {
608		record.peer_id = Some(self.details.counterparty.node_id);
609		record.channel_id = Some(self.details.channel_id);
610		self.logger.log(record)
611	}
612}
613
614impl<'a, 'b, L: Deref> WithChannelDetails<'a, 'b, L>
615where
616	L::Target: Logger,
617{
618	fn from(logger: &'a L, details: &'b ChannelDetails) -> Self {
619		Self { logger, details }
620	}
621}
622
623#[cfg(test)]
624mod test {
625	use super::*;
626	use crate::chain::channelmonitor::HTLC_FAIL_BACK_BUFFER;
627	use crate::ln::channelmanager::{
628		Bolt11InvoiceParameters, PaymentId, PhantomRouteHints, RecipientOnionFields, Retry,
629		MIN_FINAL_CLTV_EXPIRY_DELTA,
630	};
631	use crate::ln::functional_test_utils::*;
632	use crate::ln::msgs::{BaseMessageHandler, ChannelMessageHandler, MessageSendEvent};
633	use crate::routing::router::{PaymentParameters, RouteParameters};
634	use crate::sign::PhantomKeysManager;
635	use crate::types::payment::{PaymentHash, PaymentPreimage};
636	use crate::util::config::UserConfig;
637	use crate::util::dyn_signer::{DynKeysInterface, DynPhantomKeysInterface};
638	use crate::util::test_utils;
639	use bitcoin::hashes::sha256::Hash as Sha256;
640	use bitcoin::hashes::{sha256, Hash};
641	use bitcoin::network::Network;
642	use core::time::Duration;
643	use lightning_invoice::{
644		Bolt11InvoiceDescriptionRef, CreationError, Currency, Description, SignOrCreationError,
645	};
646	use std::collections::HashSet;
647
648	#[test]
649	fn test_prefer_current_channel() {
650		// No minimum, prefer larger candidate channel.
651		assert_eq!(prefer_current_channel(None, 100, 200), false);
652
653		// No minimum, prefer larger current channel.
654		assert_eq!(prefer_current_channel(None, 200, 100), true);
655
656		// Minimum set, prefer current channel over minimum + buffer.
657		assert_eq!(prefer_current_channel(Some(100), 115, 100), true);
658
659		// Minimum set, prefer candidate channel over minimum + buffer.
660		assert_eq!(prefer_current_channel(Some(100), 105, 125), false);
661
662		// Minimum set, both channels sufficient, prefer smaller current channel.
663		assert_eq!(prefer_current_channel(Some(100), 115, 125), true);
664
665		// Minimum set, both channels sufficient, prefer smaller candidate channel.
666		assert_eq!(prefer_current_channel(Some(100), 200, 160), false);
667
668		// Minimum set, neither sufficient, prefer larger current channel.
669		assert_eq!(prefer_current_channel(Some(200), 100, 50), true);
670
671		// Minimum set, neither sufficient, prefer larger candidate channel.
672		assert_eq!(prefer_current_channel(Some(200), 100, 150), false);
673	}
674
675	#[test]
676	fn create_and_pay_for_bolt11_invoice() {
677		let chanmon_cfgs = create_chanmon_cfgs(2);
678		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
679		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
680		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
681		create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
682
683		let node_a_id = nodes[0].node.get_our_node_id();
684
685		let description =
686			Bolt11InvoiceDescription::Direct(Description::new("test".to_string()).unwrap());
687		let non_default_invoice_expiry_secs = 4200;
688		let invoice_params = Bolt11InvoiceParameters {
689			amount_msats: Some(10_000),
690			description,
691			invoice_expiry_delta_secs: Some(non_default_invoice_expiry_secs),
692			..Default::default()
693		};
694		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
695		assert_eq!(invoice.amount_milli_satoshis(), Some(10_000));
696		// If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
697		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
698		assert_eq!(
699			invoice.description(),
700			Bolt11InvoiceDescriptionRef::Direct(&Description::new("test".to_string()).unwrap())
701		);
702		assert_eq!(
703			invoice.expiry_time(),
704			Duration::from_secs(non_default_invoice_expiry_secs.into())
705		);
706
707		// Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
708		// available.
709		let chan = &nodes[1].node.list_usable_channels()[0];
710		assert_eq!(invoice.route_hints().len(), 1);
711		assert_eq!(invoice.route_hints()[0].0.len(), 1);
712		assert_eq!(
713			invoice.route_hints()[0].0[0].short_channel_id,
714			chan.inbound_scid_alias.unwrap()
715		);
716
717		assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
718		assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
719
720		let retry = Retry::Attempts(0);
721		nodes[0]
722			.node
723			.pay_for_bolt11_invoice(&invoice, PaymentId([42; 32]), None, Default::default(), retry)
724			.unwrap();
725		check_added_monitors(&nodes[0], 1);
726
727		let mut events = nodes[0].node.get_and_clear_pending_msg_events();
728		assert_eq!(events.len(), 1);
729		let payment_event = SendEvent::from_event(events.remove(0));
730		nodes[1].node.handle_update_add_htlc(node_a_id, &payment_event.msgs[0]);
731		nodes[1].node.handle_commitment_signed_batch_test(node_a_id, &payment_event.commitment_msg);
732		check_added_monitors(&nodes[1], 1);
733		let events = nodes[1].node.get_and_clear_pending_msg_events();
734		assert_eq!(events.len(), 2);
735	}
736
737	fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
738		let chanmon_cfgs = create_chanmon_cfgs(2);
739		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
740		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
741		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
742		let custom_min_final_cltv_expiry_delta = Some(50);
743
744		let description = Bolt11InvoiceDescription::Direct(Description::empty());
745		let min_final_cltv_expiry_delta =
746			if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None };
747		let invoice_params = Bolt11InvoiceParameters {
748			amount_msats: Some(10_000),
749			description,
750			invoice_expiry_delta_secs: Some(3600),
751			min_final_cltv_expiry_delta,
752			..Default::default()
753		};
754		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
755		assert_eq!(
756			invoice.min_final_cltv_expiry_delta(),
757			if with_custom_delta {
758				custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */
759			} else {
760				MIN_FINAL_CLTV_EXPIRY_DELTA
761			} as u64
762		);
763	}
764
765	#[test]
766	fn test_create_invoice_custom_min_final_cltv_delta() {
767		do_create_invoice_min_final_cltv_delta(true);
768		do_create_invoice_min_final_cltv_delta(false);
769	}
770
771	#[test]
772	fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
773		let chanmon_cfgs = create_chanmon_cfgs(2);
774		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
775		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
776		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
777
778		let custom_min_final_cltv_expiry_delta = Some(HTLC_FAIL_BACK_BUFFER as u16);
779		let description = Bolt11InvoiceDescription::Direct(Description::empty());
780		let invoice_params = Bolt11InvoiceParameters {
781			amount_msats: Some(10_000),
782			description,
783			invoice_expiry_delta_secs: Some(3600),
784			min_final_cltv_expiry_delta: custom_min_final_cltv_expiry_delta,
785			..Default::default()
786		};
787		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
788		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
789	}
790
791	#[test]
792	fn test_create_invoice_with_description_hash() {
793		let chanmon_cfgs = create_chanmon_cfgs(2);
794		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
795		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
796		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
797
798		let description = Bolt11InvoiceDescription::Hash(Sha256(Hash::hash(
799			"Testing description_hash".as_bytes(),
800		)));
801		let invoice_params = Bolt11InvoiceParameters {
802			amount_msats: Some(10_000),
803			description,
804			invoice_expiry_delta_secs: Some(3600),
805			..Default::default()
806		};
807		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
808		assert_eq!(invoice.amount_milli_satoshis(), Some(10_000));
809		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
810		assert_eq!(
811			invoice.description(),
812			Bolt11InvoiceDescriptionRef::Hash(&Sha256(Sha256::hash(
813				"Testing description_hash".as_bytes()
814			)))
815		);
816	}
817
818	#[test]
819	fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
820		let chanmon_cfgs = create_chanmon_cfgs(2);
821		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
822		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
823		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
824
825		let payment_hash = PaymentHash([0; 32]);
826		let description =
827			Bolt11InvoiceDescription::Direct(Description::new("test".to_string()).unwrap());
828		let invoice_params = Bolt11InvoiceParameters {
829			amount_msats: Some(10_000),
830			description,
831			invoice_expiry_delta_secs: Some(3600),
832			payment_hash: Some(payment_hash),
833			..Default::default()
834		};
835		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
836		assert_eq!(invoice.amount_milli_satoshis(), Some(10_000));
837		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
838		assert_eq!(
839			invoice.description(),
840			Bolt11InvoiceDescriptionRef::Direct(&Description::new("test".to_string()).unwrap())
841		);
842		assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
843	}
844
845	#[cfg(not(feature = "std"))]
846	#[test]
847	fn creates_invoice_using_highest_seen_timestamp() {
848		let chanmon_cfgs = create_chanmon_cfgs(2);
849		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
850		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
851		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
852
853		let invoice_params = Bolt11InvoiceParameters::default();
854		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
855		let best_block = bitcoin::constants::genesis_block(Network::Testnet);
856		assert_eq!(
857			invoice.duration_since_epoch(),
858			Duration::from_secs(best_block.header.time.into()),
859		);
860	}
861
862	#[test]
863	fn creates_invoice_using_currency_inferred_from_chain_hash() {
864		let chanmon_cfgs = create_chanmon_cfgs(2);
865		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
866		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
867		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
868
869		let invoice_params = Bolt11InvoiceParameters::default();
870		let invoice = nodes[1].node.create_bolt11_invoice(invoice_params).unwrap();
871		assert_eq!(invoice.currency(), Currency::BitcoinTestnet);
872		assert_eq!(invoice.network(), Network::Testnet);
873	}
874
875	#[test]
876	fn test_hints_has_only_public_confd_channels() {
877		let chanmon_cfgs = create_chanmon_cfgs(2);
878		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
879		let mut config = test_default_channel_config();
880		config.channel_handshake_config.minimum_depth = 1;
881		let node_chanmgrs =
882			create_node_chanmgrs(2, &node_cfgs, &[Some(config.clone()), Some(config)]);
883		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884
885		let node_a_id = nodes[0].node.get_our_node_id();
886		let node_b_id = nodes[1].node.get_our_node_id();
887
888		// Create a private channel with lots of capacity and a lower value public channel (without
889		// confirming the funding tx yet).
890		let unannounced_scid =
891			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
892		let conf_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 10_000, 0);
893
894		// Before the channel is available, we should include the unannounced_scid.
895		let mut scid_aliases = HashSet::new();
896		scid_aliases.insert(unannounced_scid.0.short_channel_id_alias.unwrap());
897		match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
898
899		// However after we mine the funding tx and exchange channel_ready messages for the public
900		// channel we'll immediately switch to including it as a route hint, even though it isn't
901		// yet announced.
902		let pub_channel_scid = mine_transaction(&nodes[0], &conf_tx);
903		let node_a_pub_channel_ready =
904			get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, node_b_id);
905		nodes[1].node.handle_channel_ready(node_a_id, &node_a_pub_channel_ready);
906
907		assert_eq!(mine_transaction(&nodes[1], &conf_tx), pub_channel_scid);
908		let events = nodes[1].node.get_and_clear_pending_msg_events();
909		assert_eq!(events.len(), 2);
910		if let MessageSendEvent::SendChannelReady { msg, .. } = &events[0] {
911			nodes[0].node.handle_channel_ready(node_b_id, msg);
912		} else {
913			panic!();
914		}
915		if let MessageSendEvent::SendChannelUpdate { msg, .. } = &events[1] {
916			nodes[0].node.handle_channel_update(node_b_id, msg);
917		} else {
918			panic!();
919		}
920
921		let as_update = get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, node_b_id);
922		nodes[1].node.handle_channel_update(node_a_id, &as_update);
923
924		expect_channel_ready_event(&nodes[0], &node_b_id);
925		expect_channel_ready_event(&nodes[1], &node_a_id);
926
927		scid_aliases.clear();
928		scid_aliases.insert(node_a_pub_channel_ready.short_channel_id_alias.unwrap());
929		match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
930		// This also applies even if the amount is more than the payment amount, to ensure users
931		// dont screw up their privacy.
932		match_invoice_routes(Some(50_000_000), &nodes[1], scid_aliases.clone());
933
934		// The same remains true until the channel has 7 confirmations, at which point we include
935		// no hints.
936		connect_blocks(&nodes[1], 5);
937		match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
938		connect_blocks(&nodes[1], 1);
939		get_event_msg!(nodes[1], MessageSendEvent::SendAnnouncementSignatures, node_a_id);
940		match_invoice_routes(Some(5000), &nodes[1], HashSet::new());
941	}
942
943	#[test]
944	fn test_hints_includes_single_channels_to_nodes() {
945		let chanmon_cfgs = create_chanmon_cfgs(3);
946		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
947		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
948		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
949
950		let chan_1_0 =
951			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
952		let chan_2_0 =
953			create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
954
955		let mut scid_aliases = HashSet::new();
956		scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
957		scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
958
959		match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
960	}
961
962	#[test]
963	fn test_hints_has_only_lowest_inbound_capacity_channel_above_minimum() {
964		let chanmon_cfgs = create_chanmon_cfgs(2);
965		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
966		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
967		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
968
969		let _chan_1_0_inbound_below_amt =
970			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000, 0);
971		let _chan_1_0_large_inbound_above_amt =
972			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 500_000, 0);
973		let chan_1_0_low_inbound_above_amt =
974			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 200_000, 0);
975
976		let mut scid_aliases = HashSet::new();
977		scid_aliases.insert(chan_1_0_low_inbound_above_amt.0.short_channel_id_alias.unwrap());
978		match_invoice_routes(Some(100_000_000), &nodes[0], scid_aliases);
979	}
980
981	#[test]
982	fn test_hints_has_only_online_channels() {
983		let chanmon_cfgs = create_chanmon_cfgs(4);
984		let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
985		let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
986		let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
987		let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
988		let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
989		let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
990
991		// With all peers connected we should get all hints that have sufficient value
992		let mut scid_aliases = HashSet::new();
993		scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
994		scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
995
996		match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
997
998		// With only one sufficient-value peer connected we should only get its hint
999		scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
1000		nodes[0].node.peer_disconnected(nodes[2].node.get_our_node_id());
1001		match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1002
1003		// If we don't have any sufficient-value peers connected we should get all hints with
1004		// sufficient value, even though there is a connected insufficient-value peer.
1005		scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
1006		nodes[0].node.peer_disconnected(nodes[1].node.get_our_node_id());
1007		match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
1008	}
1009
1010	#[test]
1011	fn test_insufficient_inbound_sort_by_highest_capacity() {
1012		let chanmon_cfgs = create_chanmon_cfgs(5);
1013		let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1014		let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1015		let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1016		let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1017		let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 200_000, 0);
1018		let chan_3_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 300_000, 0);
1019		let chan_4_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 4, 0, 400_000, 0);
1020
1021		// When no single channel has enough inbound capacity for the payment, we expect the three
1022		// highest inbound channels to be chosen.
1023		let mut scid_aliases = HashSet::new();
1024		scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1025		scid_aliases.insert(chan_3_0.0.short_channel_id_alias.unwrap());
1026		scid_aliases.insert(chan_4_0.0.short_channel_id_alias.unwrap());
1027
1028		match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1029	}
1030
1031	#[test]
1032	fn test_sufficient_inbound_sort_by_lowest_capacity() {
1033		let chanmon_cfgs = create_chanmon_cfgs(5);
1034		let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1035		let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1036		let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1037		let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1038		let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 200_000, 0);
1039		let chan_3_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 300_000, 0);
1040		let _chan_4_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 4, 0, 400_000, 0);
1041
1042		// When we have channels that have sufficient inbound for the payment, test that we sort
1043		// by lowest inbound capacity.
1044		let mut scid_aliases = HashSet::new();
1045		scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1046		scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1047		scid_aliases.insert(chan_3_0.0.short_channel_id_alias.unwrap());
1048
1049		match_invoice_routes(Some(50_000_000), &nodes[0], scid_aliases.clone());
1050	}
1051
1052	#[test]
1053	fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
1054		let chanmon_cfgs = create_chanmon_cfgs(3);
1055		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1056		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1057		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1058		let chan_1_0 =
1059			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1060
1061		let node_a_id = nodes[0].node.get_our_node_id();
1062		let node_c_id = nodes[2].node.get_our_node_id();
1063
1064		// Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
1065		// `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1066		// is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1067		let mut private_chan_cfg = UserConfig::default();
1068		private_chan_cfg.channel_handshake_config.announce_for_forwarding = false;
1069		let temporary_channel_id = nodes[2]
1070			.node
1071			.create_channel(node_a_id, 1_000_000, 500_000_000, 42, None, Some(private_chan_cfg))
1072			.unwrap();
1073		let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, node_a_id);
1074		nodes[0].node.handle_open_channel(node_c_id, &open_channel);
1075		let accept_channel =
1076			get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, node_c_id);
1077		nodes[2].node.handle_accept_channel(node_a_id, &accept_channel);
1078
1079		let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
1080
1081		let conf_height =
1082			core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
1083		confirm_transaction_at(&nodes[2], &tx, conf_height);
1084		connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
1085		confirm_transaction_at(&nodes[0], &tx, conf_height);
1086		connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
1087		let as_channel_ready =
1088			get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, node_c_id);
1089		let cs_channel_ready =
1090			get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, node_a_id);
1091		nodes[2].node.handle_channel_ready(node_a_id, &as_channel_ready);
1092		get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, node_a_id);
1093		nodes[0].node.handle_channel_ready(node_c_id, &cs_channel_ready);
1094		get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, node_c_id);
1095		expect_channel_ready_event(&nodes[0], &node_c_id);
1096		expect_channel_ready_event(&nodes[2], &node_a_id);
1097
1098		// As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
1099		// channel, the channel will never be assigned any `counterparty.forwarding_info`.
1100		// Therefore only `chan_1_0` should be included in the hints.
1101		let mut scid_aliases = HashSet::new();
1102		scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1103		match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
1104	}
1105
1106	#[test]
1107	fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
1108		let chanmon_cfgs = create_chanmon_cfgs(3);
1109		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1110		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1111		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1112		let _chan_1_0 =
1113			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1114
1115		let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1116		nodes[2].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_2_0.1);
1117		nodes[0].node.handle_channel_update(nodes[2].node.get_our_node_id(), &chan_2_0.0);
1118
1119		// Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
1120		// even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
1121		// public channel between `nodes[2]` and `nodes[0]`
1122		match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1123	}
1124
1125	#[test]
1126	fn test_only_public_channels_includes_no_channels_in_hints() {
1127		let chanmon_cfgs = create_chanmon_cfgs(3);
1128		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1129		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1130		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1131		let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1132		nodes[0].node.handle_channel_update(nodes[1].node.get_our_node_id(), &chan_1_0.0);
1133		nodes[1].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_1_0.1);
1134
1135		let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1136		nodes[2].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_2_0.1);
1137		nodes[0].node.handle_channel_update(nodes[2].node.get_our_node_id(), &chan_2_0.0);
1138
1139		// As all of `nodes[0]` channels are public, no channels should be included in the hints
1140		match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1141	}
1142
1143	#[test]
1144	fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
1145		let chanmon_cfgs = create_chanmon_cfgs(3);
1146		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1147		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1148		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1149		let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1150		let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
1151
1152		// As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
1153		let mut scid_aliases_99_000_001_msat = HashSet::new();
1154		scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1155
1156		match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
1157
1158		// As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
1159		let mut scid_aliases_99_000_000_msat = HashSet::new();
1160		scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1161		scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1162
1163		match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
1164
1165		// As the invoice amt is above all channels' inbound capacity, they will still be included
1166		let mut scid_aliases_2_000_000_000_msat = HashSet::new();
1167		scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1168		scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1169
1170		match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1171
1172		// An invoice with no specified amount should include all channels in the route hints.
1173		let mut scid_aliases_no_specified_amount = HashSet::new();
1174		scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1175		scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1176
1177		match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1178	}
1179
1180	fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1181		invoice_amt: Option<u64>, invoice_node: &Node<'a, 'b, 'c>,
1182		mut chan_ids_to_match: HashSet<u64>,
1183	) {
1184		let description =
1185			Bolt11InvoiceDescription::Direct(Description::new("test".to_string()).unwrap());
1186		let invoice_params = Bolt11InvoiceParameters {
1187			amount_msats: invoice_amt,
1188			description,
1189			invoice_expiry_delta_secs: Some(3600),
1190			..Default::default()
1191		};
1192		let invoice = invoice_node.node.create_bolt11_invoice(invoice_params).unwrap();
1193		let hints = invoice.private_routes();
1194
1195		for hint in hints {
1196			let hint_short_chan_id = hint.0[0].short_channel_id;
1197			assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1198		}
1199		assert!(
1200			chan_ids_to_match.is_empty(),
1201			"Unmatched short channel ids: {:?}",
1202			chan_ids_to_match
1203		);
1204	}
1205
1206	#[test]
1207	fn test_multi_node_receive() {
1208		do_test_multi_node_receive(true);
1209		do_test_multi_node_receive(false);
1210	}
1211
1212	fn make_dyn_keys_interface(seed: &[u8; 32]) -> DynKeysInterface {
1213		let cross_node_seed = [44u8; 32];
1214		let inner = PhantomKeysManager::new(&seed, 43, 44, &cross_node_seed, true);
1215		let dyn_inner = DynPhantomKeysInterface::new(inner);
1216		DynKeysInterface::new(Box::new(dyn_inner))
1217	}
1218
1219	fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1220		use crate::events::{Event, EventsProvider};
1221		use core::cell::RefCell;
1222
1223		let mut chanmon_cfgs = create_chanmon_cfgs(3);
1224		let seed_1 = [42u8; 32];
1225		let seed_2 = [43u8; 32];
1226		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1227		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1228		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1229		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1230		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1231		let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1232		nodes[0].node.handle_channel_update(nodes[1].node.get_our_node_id(), &chan_0_1.1);
1233		nodes[1].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_0_1.0);
1234		let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1235		nodes[0].node.handle_channel_update(nodes[2].node.get_our_node_id(), &chan_0_2.1);
1236		nodes[2].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_0_2.0);
1237
1238		let payment_amt = 10_000;
1239		let route_hints =
1240			vec![nodes[1].node.get_phantom_route_hints(), nodes[2].node.get_phantom_route_hints()];
1241
1242		let user_payment_preimage = PaymentPreimage([1; 32]);
1243		let payment_hash = if user_generated_pmt_hash {
1244			Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).to_byte_array()))
1245		} else {
1246			None
1247		};
1248		let genesis_timestamp =
1249			bitcoin::constants::genesis_block(bitcoin::Network::Testnet).header.time as u64;
1250		let non_default_invoice_expiry_secs = 4200;
1251
1252		let invoice = create_phantom_invoice::<
1253			&test_utils::TestKeysInterface,
1254			&test_utils::TestKeysInterface,
1255			&test_utils::TestLogger,
1256		>(
1257			Some(payment_amt),
1258			payment_hash,
1259			"test".to_string(),
1260			non_default_invoice_expiry_secs,
1261			route_hints,
1262			nodes[1].keys_manager,
1263			nodes[1].keys_manager,
1264			nodes[1].logger,
1265			Currency::BitcoinTestnet,
1266			None,
1267			Duration::from_secs(genesis_timestamp),
1268		)
1269		.unwrap();
1270		let (payment_hash, payment_secret) =
1271			(PaymentHash(invoice.payment_hash().to_byte_array()), *invoice.payment_secret());
1272		let payment_preimage = if user_generated_pmt_hash {
1273			user_payment_preimage
1274		} else {
1275			nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1276		};
1277
1278		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1279		assert_eq!(
1280			invoice.description(),
1281			Bolt11InvoiceDescriptionRef::Direct(&Description::new("test".to_string()).unwrap())
1282		);
1283		assert_eq!(invoice.route_hints().len(), 2);
1284		assert_eq!(
1285			invoice.expiry_time(),
1286			Duration::from_secs(non_default_invoice_expiry_secs.into())
1287		);
1288		assert!(!invoice.features().unwrap().supports_basic_mpp());
1289
1290		let payment_params = PaymentParameters::from_node_id(
1291			invoice.recover_payee_pub_key(),
1292			invoice.min_final_cltv_expiry_delta() as u32,
1293		)
1294		.with_bolt11_features(invoice.features().unwrap().clone())
1295		.unwrap()
1296		.with_route_hints(invoice.route_hints())
1297		.unwrap();
1298		let params = RouteParameters::from_payment_params_and_value(
1299			payment_params,
1300			invoice.amount_milli_satoshis().unwrap(),
1301		);
1302
1303		let payment_hash = PaymentHash(invoice.payment_hash().to_byte_array());
1304		let id = PaymentId(payment_hash.0);
1305		let onion = RecipientOnionFields::secret_only(*invoice.payment_secret());
1306		nodes[0].node.send_payment(payment_hash, onion, id, params, Retry::Attempts(0)).unwrap();
1307		check_added_monitors(&nodes[0], 1);
1308
1309		let (send_event, fwd_idx) = {
1310			let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1311			assert_eq!(events.len(), 1);
1312			let fwd_idx = match events[0] {
1313				MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1314					if node_id == nodes[1].node.get_our_node_id() {
1315						1
1316					} else {
1317						2
1318					}
1319				},
1320				_ => panic!("Unexpected event"),
1321			};
1322			(SendEvent::from_event(events.remove(0)), fwd_idx)
1323		};
1324		nodes[fwd_idx]
1325			.node
1326			.handle_update_add_htlc(nodes[0].node.get_our_node_id(), &send_event.msgs[0]);
1327		commitment_signed_dance!(nodes[fwd_idx], nodes[0], &send_event.commitment_msg, false, true);
1328
1329		// Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1330		// this "emulates" the payment taking two hops, providing some privacy to make phantom node
1331		// payments "look real" by taking more time.
1332		nodes[fwd_idx].node.process_pending_htlc_forwards();
1333		nodes[fwd_idx].node.process_pending_htlc_forwards();
1334
1335		let events = RefCell::new(Vec::new());
1336		let event_handler = |event: Event| {
1337			events.borrow_mut().push(event);
1338			Ok(())
1339		};
1340
1341		nodes[fwd_idx].node.process_pending_events(&event_handler);
1342		nodes[fwd_idx].node.process_pending_events(&event_handler);
1343
1344		let payment_preimage_opt =
1345			if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1346		assert_eq!(events.borrow().len(), 1);
1347		check_payment_claimable(
1348			&events.borrow()[0],
1349			payment_hash,
1350			payment_secret,
1351			payment_amt,
1352			payment_preimage_opt,
1353			invoice.recover_payee_pub_key(),
1354		);
1355		do_claim_payment_along_route(ClaimAlongRouteArgs::new(
1356			&nodes[0],
1357			&[&[&nodes[fwd_idx]]],
1358			payment_preimage,
1359		));
1360		expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
1361	}
1362
1363	#[test]
1364	fn test_multi_node_hints_has_htlc_min_max_values() {
1365		let mut chanmon_cfgs = create_chanmon_cfgs(3);
1366		let seed_1 = [42u8; 32];
1367		let seed_2 = [43u8; 32];
1368		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1369		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1370		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1371		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1372		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1373
1374		create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1375		create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1376
1377		let payment_amt = 20_000;
1378		let (payment_hash, _payment_secret) =
1379			nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1380		let route_hints =
1381			vec![nodes[1].node.get_phantom_route_hints(), nodes[2].node.get_phantom_route_hints()];
1382
1383		let invoice = create_phantom_invoice::<
1384			&test_utils::TestKeysInterface,
1385			&test_utils::TestKeysInterface,
1386			&test_utils::TestLogger,
1387		>(
1388			Some(payment_amt),
1389			Some(payment_hash),
1390			"test".to_string(),
1391			3600,
1392			route_hints,
1393			nodes[1].keys_manager,
1394			nodes[1].keys_manager,
1395			nodes[1].logger,
1396			Currency::BitcoinTestnet,
1397			None,
1398			Duration::from_secs(1234567),
1399		)
1400		.unwrap();
1401
1402		let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1403		assert_eq!(
1404			invoice.route_hints()[0].0[0].htlc_minimum_msat,
1405			chan_0_1.inbound_htlc_minimum_msat
1406		);
1407		assert_eq!(
1408			invoice.route_hints()[0].0[0].htlc_maximum_msat,
1409			chan_0_1.inbound_htlc_maximum_msat
1410		);
1411
1412		let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1413		assert_eq!(
1414			invoice.route_hints()[1].0[0].htlc_minimum_msat,
1415			chan_0_2.inbound_htlc_minimum_msat
1416		);
1417		assert_eq!(
1418			invoice.route_hints()[1].0[0].htlc_maximum_msat,
1419			chan_0_2.inbound_htlc_maximum_msat
1420		);
1421	}
1422
1423	#[test]
1424	fn test_create_phantom_invoice_with_description_hash() {
1425		let chanmon_cfgs = create_chanmon_cfgs(3);
1426		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1427		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1428		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1429
1430		let payment_amt = 20_000;
1431		let route_hints =
1432			vec![nodes[1].node.get_phantom_route_hints(), nodes[2].node.get_phantom_route_hints()];
1433
1434		let description_hash = Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1435		let non_default_invoice_expiry_secs = 4200;
1436		let invoice = create_phantom_invoice_with_description_hash::<
1437			&test_utils::TestKeysInterface,
1438			&test_utils::TestKeysInterface,
1439			&test_utils::TestLogger,
1440		>(
1441			Some(payment_amt),
1442			None,
1443			non_default_invoice_expiry_secs,
1444			description_hash,
1445			route_hints,
1446			nodes[1].keys_manager,
1447			nodes[1].keys_manager,
1448			nodes[1].logger,
1449			Currency::BitcoinTestnet,
1450			None,
1451			Duration::from_secs(1234567),
1452		)
1453		.unwrap();
1454		assert_eq!(invoice.amount_milli_satoshis(), Some(20_000));
1455		assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1456		assert_eq!(
1457			invoice.expiry_time(),
1458			Duration::from_secs(non_default_invoice_expiry_secs.into())
1459		);
1460		assert_eq!(
1461			invoice.description(),
1462			Bolt11InvoiceDescriptionRef::Hash(&Sha256(Sha256::hash(
1463				"Description hash phantom invoice".as_bytes()
1464			)))
1465		);
1466	}
1467
1468	#[test]
1469	fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1470		let chanmon_cfgs = create_chanmon_cfgs(3);
1471		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1472		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1473		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1474
1475		let payment_amt = 20_000;
1476		let route_hints =
1477			vec![nodes[1].node.get_phantom_route_hints(), nodes[2].node.get_phantom_route_hints()];
1478		let user_payment_preimage = PaymentPreimage([1; 32]);
1479		let payment_hash =
1480			Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).to_byte_array()));
1481		let non_default_invoice_expiry_secs = 4200;
1482		let min_final_cltv_expiry_delta = Some(100);
1483		let duration_since_epoch = Duration::from_secs(1234567);
1484		let invoice = create_phantom_invoice::<
1485			&test_utils::TestKeysInterface,
1486			&test_utils::TestKeysInterface,
1487			&test_utils::TestLogger,
1488		>(
1489			Some(payment_amt),
1490			payment_hash,
1491			"".to_string(),
1492			non_default_invoice_expiry_secs,
1493			route_hints,
1494			nodes[1].keys_manager,
1495			nodes[1].keys_manager,
1496			nodes[1].logger,
1497			Currency::BitcoinTestnet,
1498			min_final_cltv_expiry_delta,
1499			duration_since_epoch,
1500		)
1501		.unwrap();
1502		assert_eq!(invoice.amount_milli_satoshis(), Some(20_000));
1503		assert_eq!(
1504			invoice.min_final_cltv_expiry_delta(),
1505			(min_final_cltv_expiry_delta.unwrap() + 3) as u64
1506		);
1507		assert_eq!(
1508			invoice.expiry_time(),
1509			Duration::from_secs(non_default_invoice_expiry_secs.into())
1510		);
1511	}
1512
1513	#[test]
1514	fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1515		let mut chanmon_cfgs = create_chanmon_cfgs(3);
1516		let seed_1 = [42u8; 32];
1517		let seed_2 = [43u8; 32];
1518		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1519		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1520		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1521		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1522		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1523
1524		let chan_0_1 =
1525			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1526		let chan_0_2 =
1527			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1528
1529		let mut scid_aliases = HashSet::new();
1530		scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1531		scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1532
1533		match_multi_node_invoice_routes(
1534			Some(10_000),
1535			&nodes[1],
1536			vec![&nodes[1], &nodes[2]],
1537			scid_aliases,
1538			false,
1539		);
1540	}
1541
1542	#[test]
1543	fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node(
1544	) {
1545		let mut chanmon_cfgs = create_chanmon_cfgs(4);
1546		let seed_1 = [42u8; 32];
1547		let seed_2 = [43u8; 32];
1548		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1549		chanmon_cfgs[3].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1550		let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1551		let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1552		let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1553
1554		let chan_0_2 =
1555			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1556		let chan_0_3 =
1557			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1558		let chan_1_3 =
1559			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1560
1561		let mut scid_aliases = HashSet::new();
1562		scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1563		scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1564		scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1565
1566		match_multi_node_invoice_routes(
1567			Some(10_000),
1568			&nodes[2],
1569			vec![&nodes[2], &nodes[3]],
1570			scid_aliases,
1571			false,
1572		);
1573	}
1574
1575	#[test]
1576	fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1577		let mut chanmon_cfgs = create_chanmon_cfgs(4);
1578		let seed_1 = [42u8; 32];
1579		let seed_2 = [43u8; 32];
1580		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1581		chanmon_cfgs[3].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1582		let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1583		let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1584		let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1585
1586		let node_b_id = nodes[1].node.get_our_node_id();
1587		let node_d_id = nodes[3].node.get_our_node_id();
1588
1589		let chan_0_2 =
1590			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1591		let chan_0_3 =
1592			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1593
1594		// Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1595		// `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1596		// is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1597		let mut private_chan_cfg = UserConfig::default();
1598		private_chan_cfg.channel_handshake_config.announce_for_forwarding = false;
1599		let temporary_channel_id = nodes[1]
1600			.node
1601			.create_channel(node_d_id, 1_000_000, 500_000_000, 42, None, Some(private_chan_cfg))
1602			.unwrap();
1603		let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, node_d_id);
1604		nodes[3].node.handle_open_channel(nodes[1].node.get_our_node_id(), &open_channel);
1605		let accept_channel =
1606			get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, node_b_id);
1607		nodes[1].node.handle_accept_channel(nodes[3].node.get_our_node_id(), &accept_channel);
1608
1609		let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1610
1611		let conf_height =
1612			core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1613		confirm_transaction_at(&nodes[1], &tx, conf_height);
1614		connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1615		confirm_transaction_at(&nodes[3], &tx, conf_height);
1616		connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1617
1618		let bs_channel_ready =
1619			get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, node_d_id);
1620		let ds_channel_ready =
1621			get_event_msg!(nodes[3], MessageSendEvent::SendChannelReady, node_b_id);
1622		nodes[1].node.handle_channel_ready(node_d_id, &ds_channel_ready);
1623		get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, node_d_id);
1624		nodes[3].node.handle_channel_ready(nodes[1].node.get_our_node_id(), &bs_channel_ready);
1625		get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, node_b_id);
1626		expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1627		expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1628
1629		// As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1630		// channel, the channel will never be assigned any `counterparty.forwarding_info`.
1631		// Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1632		let mut scid_aliases = HashSet::new();
1633		scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1634		scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1635
1636		match_multi_node_invoice_routes(
1637			Some(10_000),
1638			&nodes[2],
1639			vec![&nodes[2], &nodes[3]],
1640			scid_aliases,
1641			false,
1642		);
1643	}
1644
1645	#[test]
1646	fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1647		let mut chanmon_cfgs = create_chanmon_cfgs(3);
1648		let seed_1 = [42u8; 32];
1649		let seed_2 = [43u8; 32];
1650		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1651		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1652		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1653		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1654		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1655
1656		let chan_0_1 =
1657			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1658
1659		let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1660		nodes[2].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_2_0.1);
1661		nodes[0].node.handle_channel_update(nodes[2].node.get_our_node_id(), &chan_2_0.0);
1662
1663		// Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1664		// `chan_0_2` as `nodes[2]` only has public channels.
1665		let mut scid_aliases = HashSet::new();
1666		scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1667
1668		match_multi_node_invoice_routes(
1669			Some(10_000),
1670			&nodes[1],
1671			vec![&nodes[1], &nodes[2]],
1672			scid_aliases,
1673			true,
1674		);
1675	}
1676
1677	#[test]
1678	fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1679		let mut chanmon_cfgs = create_chanmon_cfgs(4);
1680		let seed_1 = [42u8; 32];
1681		let seed_2 = [43u8; 32];
1682		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1683		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1684		let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1685		let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1686		let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1687
1688		let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1689		nodes[0].node.handle_channel_update(nodes[2].node.get_our_node_id(), &chan_0_2.1);
1690		nodes[2].node.handle_channel_update(nodes[0].node.get_our_node_id(), &chan_0_2.0);
1691		let _chan_1_2 =
1692			create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1693
1694		let chan_0_3 =
1695			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1696
1697		// Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1698		// channels for `nodes[2]` as it contains a mix of public and private channels.
1699		let mut scid_aliases = HashSet::new();
1700		scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1701
1702		match_multi_node_invoice_routes(
1703			Some(10_000),
1704			&nodes[2],
1705			vec![&nodes[2], &nodes[3]],
1706			scid_aliases,
1707			true,
1708		);
1709	}
1710
1711	#[test]
1712	fn test_multi_node_hints_has_only_lowest_inbound_channel_above_minimum() {
1713		let mut chanmon_cfgs = create_chanmon_cfgs(3);
1714		let seed_1 = [42u8; 32];
1715		let seed_2 = [43u8; 32];
1716		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1717		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1718		let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1719		let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1720		let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1721
1722		let _chan_0_1_below_amt =
1723			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1724		let _chan_0_1_above_amt_high_inbound =
1725			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 500_000, 0);
1726		let chan_0_1_above_amt_low_inbound =
1727			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 180_000, 0);
1728		let chan_0_2 =
1729			create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1730
1731		let mut scid_aliases = HashSet::new();
1732		scid_aliases.insert(chan_0_1_above_amt_low_inbound.0.short_channel_id_alias.unwrap());
1733		scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1734
1735		match_multi_node_invoice_routes(
1736			Some(100_000_000),
1737			&nodes[1],
1738			vec![&nodes[1], &nodes[2]],
1739			scid_aliases,
1740			false,
1741		);
1742	}
1743
1744	#[test]
1745	fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1746		let mut chanmon_cfgs = create_chanmon_cfgs(4);
1747		let seed_1 = [42u8; 32];
1748		let seed_2 = [43u8; 32];
1749		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1750		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1751		let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1752		let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1753		let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1754
1755		let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1756		let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1757		let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1758
1759		// Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1760		let mut scid_aliases_99_000_001_msat = HashSet::new();
1761		scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1762		scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1763
1764		match_multi_node_invoice_routes(
1765			Some(99_000_001),
1766			&nodes[2],
1767			vec![&nodes[2], &nodes[3]],
1768			scid_aliases_99_000_001_msat,
1769			false,
1770		);
1771
1772		// Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1773		let mut scid_aliases_99_000_000_msat = HashSet::new();
1774		scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1775		scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1776		scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1777
1778		match_multi_node_invoice_routes(
1779			Some(99_000_000),
1780			&nodes[2],
1781			vec![&nodes[2], &nodes[3]],
1782			scid_aliases_99_000_000_msat,
1783			false,
1784		);
1785
1786		// Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1787		// `nodes[2]` them should be included.
1788		let mut scid_aliases_300_000_000_msat = HashSet::new();
1789		scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1790		scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1791		scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1792
1793		match_multi_node_invoice_routes(
1794			Some(300_000_000),
1795			&nodes[2],
1796			vec![&nodes[2], &nodes[3]],
1797			scid_aliases_300_000_000_msat,
1798			false,
1799		);
1800
1801		// Since the no specified amount, all channels should included.
1802		let mut scid_aliases_no_specified_amount = HashSet::new();
1803		scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1804		scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1805		scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1806
1807		match_multi_node_invoice_routes(
1808			None,
1809			&nodes[2],
1810			vec![&nodes[2], &nodes[3]],
1811			scid_aliases_no_specified_amount,
1812			false,
1813		);
1814	}
1815
1816	#[test]
1817	fn test_multi_node_hints_limited_to_3() {
1818		let mut chanmon_cfgs = create_chanmon_cfgs(6);
1819		let seed_1 = [42 as u8; 32];
1820		let seed_2 = [43 as u8; 32];
1821		let seed_3 = [44 as u8; 32];
1822		let seed_4 = [45 as u8; 32];
1823		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1824		chanmon_cfgs[3].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1825		chanmon_cfgs[4].keys_manager.backing = make_dyn_keys_interface(&seed_3);
1826		chanmon_cfgs[4].keys_manager.backing = make_dyn_keys_interface(&seed_4);
1827		let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1828		let node_chanmgrs =
1829			create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1830		let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1831
1832		// Setup each phantom node with two channels from distinct peers.
1833		let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000, 0);
1834		let chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 20_000, 0);
1835		let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 20_000, 0);
1836		let _chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000, 0);
1837		let chan_0_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 4, 20_000, 0);
1838		let _chan_1_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000, 0);
1839		let _chan_0_5 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 5, 20_000, 0);
1840		let _chan_1_5 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000, 0);
1841
1842		// Set invoice amount > all channels inbound so that every one is eligible for inclusion
1843		// and hints will be sorted by largest inbound capacity.
1844		let invoice_amt = Some(100_000_000);
1845
1846		// With 4 phantom nodes, assert that we include 1 hint per node, up to 3 nodes.
1847		let mut scid_aliases = HashSet::new();
1848		scid_aliases.insert(chan_1_2.0.short_channel_id_alias.unwrap());
1849		scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1850		scid_aliases.insert(chan_0_4.0.short_channel_id_alias.unwrap());
1851
1852		match_multi_node_invoice_routes(
1853			invoice_amt,
1854			&nodes[3],
1855			vec![&nodes[2], &nodes[3], &nodes[4], &nodes[5]],
1856			scid_aliases,
1857			false,
1858		);
1859
1860		// With 2 phantom nodes, assert that we include no more than 3 hints.
1861		let mut scid_aliases = HashSet::new();
1862		scid_aliases.insert(chan_1_2.0.short_channel_id_alias.unwrap());
1863		scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1864		scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1865
1866		match_multi_node_invoice_routes(
1867			invoice_amt,
1868			&nodes[3],
1869			vec![&nodes[2], &nodes[3]],
1870			scid_aliases,
1871			false,
1872		);
1873	}
1874
1875	#[test]
1876	fn test_multi_node_hints_at_least_3() {
1877		let mut chanmon_cfgs = create_chanmon_cfgs(5);
1878		let seed_1 = [42 as u8; 32];
1879		let seed_2 = [43 as u8; 32];
1880		chanmon_cfgs[1].keys_manager.backing = make_dyn_keys_interface(&seed_1);
1881		chanmon_cfgs[2].keys_manager.backing = make_dyn_keys_interface(&seed_2);
1882		let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1883		let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1884		let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1885
1886		let _chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 10_000, 0);
1887		let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 20_000, 0);
1888		let chan_2_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 30_000, 0);
1889		let chan_0_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 4, 10_000, 0);
1890
1891		// Since the invoice amount is above all channels inbound, all four are eligible. Test that
1892		// we still include 3 hints from 2 distinct nodes sorted by inbound.
1893		let mut scid_aliases = HashSet::new();
1894		scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1895		scid_aliases.insert(chan_2_3.0.short_channel_id_alias.unwrap());
1896		scid_aliases.insert(chan_0_4.0.short_channel_id_alias.unwrap());
1897
1898		match_multi_node_invoice_routes(
1899			Some(100_000_000),
1900			&nodes[3],
1901			vec![&nodes[3], &nodes[4]],
1902			scid_aliases,
1903			false,
1904		);
1905	}
1906
1907	fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1908		invoice_amt: Option<u64>, invoice_node: &Node<'a, 'b, 'c>,
1909		network_multi_nodes: Vec<&Node<'a, 'b, 'c>>, mut chan_ids_to_match: HashSet<u64>,
1910		nodes_contains_public_channels: bool,
1911	) {
1912		let phantom_route_hints = network_multi_nodes
1913			.iter()
1914			.map(|node| node.node.get_phantom_route_hints())
1915			.collect::<Vec<PhantomRouteHints>>();
1916		let phantom_scids = phantom_route_hints
1917			.iter()
1918			.map(|route_hint| route_hint.phantom_scid)
1919			.collect::<HashSet<u64>>();
1920
1921		let invoice = create_phantom_invoice::<
1922			&test_utils::TestKeysInterface,
1923			&test_utils::TestKeysInterface,
1924			&test_utils::TestLogger,
1925		>(
1926			invoice_amt,
1927			None,
1928			"test".to_string(),
1929			3600,
1930			phantom_route_hints,
1931			invoice_node.keys_manager,
1932			invoice_node.keys_manager,
1933			invoice_node.logger,
1934			Currency::BitcoinTestnet,
1935			None,
1936			Duration::from_secs(1234567),
1937		)
1938		.unwrap();
1939
1940		let invoice_hints = invoice.private_routes();
1941
1942		for hint in invoice_hints {
1943			let hints = &hint.0;
1944			match hints.len() {
1945				1 => {
1946					assert!(nodes_contains_public_channels);
1947					let phantom_scid = hints[0].short_channel_id;
1948					assert!(phantom_scids.contains(&phantom_scid));
1949				},
1950				2 => {
1951					let hint_short_chan_id = hints[0].short_channel_id;
1952					assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1953					let phantom_scid = hints[1].short_channel_id;
1954					assert!(phantom_scids.contains(&phantom_scid));
1955				},
1956				_ => panic!("Incorrect hint length generated"),
1957			}
1958		}
1959		assert!(
1960			chan_ids_to_match.is_empty(),
1961			"Unmatched short channel ids: {:?}",
1962			chan_ids_to_match
1963		);
1964	}
1965
1966	#[test]
1967	fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1968		let chanmon_cfgs = create_chanmon_cfgs(2);
1969		let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1970		let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1971		let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1972
1973		let description = Bolt11InvoiceDescription::Direct(
1974			Description::new("Some description".to_string()).unwrap(),
1975		);
1976		let invoice_params = Bolt11InvoiceParameters {
1977			amount_msats: Some(10_000),
1978			description,
1979			invoice_expiry_delta_secs: Some(3600),
1980			min_final_cltv_expiry_delta: Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1981			..Default::default()
1982		};
1983		match nodes[1].node.create_bolt11_invoice(invoice_params) {
1984			Err(SignOrCreationError::CreationError(
1985				CreationError::MinFinalCltvExpiryDeltaTooShort,
1986			)) => {},
1987			_ => panic!(),
1988		}
1989	}
1990
1991	#[test]
1992	fn test_rotate_through_iterators() {
1993		// two nested vectors
1994		let a = vec![vec!["a0", "b0", "c0"].into_iter(), vec!["a1", "b1"].into_iter()];
1995		let result = rotate_through_iterators(a).collect::<Vec<_>>();
1996
1997		let expected = vec!["a0", "a1", "b0", "b1", "c0"];
1998		assert_eq!(expected, result);
1999
2000		// test single nested vector
2001		let a = vec![vec!["a0", "b0", "c0"].into_iter()];
2002		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2003
2004		let expected = vec!["a0", "b0", "c0"];
2005		assert_eq!(expected, result);
2006
2007		// test second vector with only one element
2008		let a = vec![vec!["a0", "b0", "c0"].into_iter(), vec!["a1"].into_iter()];
2009		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2010
2011		let expected = vec!["a0", "a1", "b0", "c0"];
2012		assert_eq!(expected, result);
2013
2014		// test three nestend vectors
2015		let a = vec![
2016			vec!["a0"].into_iter(),
2017			vec!["a1", "b1", "c1"].into_iter(),
2018			vec!["a2"].into_iter(),
2019		];
2020		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2021
2022		let expected = vec!["a0", "a1", "a2", "b1", "c1"];
2023		assert_eq!(expected, result);
2024
2025		// test single nested vector with a single value
2026		let a = vec![vec!["a0"].into_iter()];
2027		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2028
2029		let expected = vec!["a0"];
2030		assert_eq!(expected, result);
2031
2032		// test single empty nested vector
2033		let a: Vec<std::vec::IntoIter<&str>> = vec![vec![].into_iter()];
2034		let result = rotate_through_iterators(a).collect::<Vec<&str>>();
2035		let expected: Vec<&str> = vec![];
2036
2037		assert_eq!(expected, result);
2038
2039		// test first nested vector is empty
2040		let a: Vec<std::vec::IntoIter<&str>> =
2041			vec![vec![].into_iter(), vec!["a1", "b1", "c1"].into_iter()];
2042		let result = rotate_through_iterators(a).collect::<Vec<&str>>();
2043
2044		let expected = vec!["a1", "b1", "c1"];
2045		assert_eq!(expected, result);
2046
2047		// test two empty vectors
2048		let a: Vec<std::vec::IntoIter<&str>> = vec![vec![].into_iter(), vec![].into_iter()];
2049		let result = rotate_through_iterators(a).collect::<Vec<&str>>();
2050
2051		let expected: Vec<&str> = vec![];
2052		assert_eq!(expected, result);
2053
2054		// test an empty vector amongst other filled vectors
2055		let a = vec![
2056			vec!["a0", "b0", "c0"].into_iter(),
2057			vec![].into_iter(),
2058			vec!["a1", "b1", "c1"].into_iter(),
2059			vec!["a2", "b2", "c2"].into_iter(),
2060		];
2061		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2062
2063		let expected = vec!["a0", "a1", "a2", "b0", "b1", "b2", "c0", "c1", "c2"];
2064		assert_eq!(expected, result);
2065
2066		// test a filled vector between two empty vectors
2067		let a = vec![vec![].into_iter(), vec!["a1", "b1", "c1"].into_iter(), vec![].into_iter()];
2068		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2069
2070		let expected = vec!["a1", "b1", "c1"];
2071		assert_eq!(expected, result);
2072
2073		// test an empty vector at the end of the vectors
2074		let a = vec![vec!["a0", "b0", "c0"].into_iter(), vec![].into_iter()];
2075		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2076
2077		let expected = vec!["a0", "b0", "c0"];
2078		assert_eq!(expected, result);
2079
2080		// test multiple empty vectors amongst multiple filled vectors
2081		let a = vec![
2082			vec![].into_iter(),
2083			vec!["a1", "b1", "c1"].into_iter(),
2084			vec![].into_iter(),
2085			vec!["a3", "b3"].into_iter(),
2086			vec![].into_iter(),
2087		];
2088
2089		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2090
2091		let expected = vec!["a1", "a3", "b1", "b3", "c1"];
2092		assert_eq!(expected, result);
2093
2094		// test one element in the first nested vectore and two elements in the second nested
2095		// vector
2096		let a = vec![vec!["a0"].into_iter(), vec!["a1", "b1"].into_iter()];
2097		let result = rotate_through_iterators(a).collect::<Vec<_>>();
2098
2099		let expected = vec!["a0", "a1", "b1"];
2100		assert_eq!(expected, result);
2101	}
2102}