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