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