lightning/ln/
invoice_utils.rs

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