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