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