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