Merge pull request #2100 from douglaz/docs_fixes
[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::chain::keysinterface::{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
22 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
23 /// See [`PhantomKeysManager`] for more information on phantom node payments.
24 ///
25 /// `phantom_route_hints` parameter:
26 /// * Contains channel info for all nodes participating in the phantom invoice
27 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
28 ///   participating node
29 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
30 ///   updated when a channel becomes disabled or closes
31 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
32 ///   may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
33 ///   down
34 ///
35 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
36 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
37 /// If `None` is provided for `payment_hash`, then one will be created.
38 ///
39 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
40 /// in excess of the current time.
41 ///
42 /// `duration_since_epoch` is the current time since epoch in seconds.
43 ///
44 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
45 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3.
46 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
47 /// confirmations during routing.
48 ///
49 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
50 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
51 /// requirement).
52 ///
53 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
54 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
55 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
56 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
57 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
58 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
59 ///
60 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
61 /// available and the current time is supplied by the caller.
62 pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
63         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
64         invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
65         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
66 ) -> Result<Invoice, SignOrCreationError<()>>
67 where
68         ES::Target: EntropySource,
69         NS::Target: NodeSigner,
70         L::Target: Logger,
71 {
72         let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
73         let description = InvoiceDescription::Direct(&description,);
74         _create_phantom_invoice::<ES, NS, L>(
75                 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
76                 entropy_source, node_signer, logger, network, min_final_cltv_expiry_delta, duration_since_epoch,
77         )
78 }
79
80 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
81 /// See [`PhantomKeysManager`] for more information on phantom node payments.
82 ///
83 /// `phantom_route_hints` parameter:
84 /// * Contains channel info for all nodes participating in the phantom invoice
85 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
86 ///   participating node
87 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
88 ///   updated when a channel becomes disabled or closes
89 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
90 ///   may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
91 ///   down
92 ///
93 /// `description_hash` is a SHA-256 hash of the description text
94 ///
95 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
96 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
97 /// If `None` is provided for `payment_hash`, then one will be created.
98 ///
99 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
100 /// in excess of the current time.
101 ///
102 /// `duration_since_epoch` is the current time since epoch in seconds.
103 ///
104 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
105 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
106 /// requirement).
107 ///
108 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
109 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
110 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
111 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
112 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
113 ///
114 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
115 /// available and the current time is supplied by the caller.
116 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
117         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
118         description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
119         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
120 ) -> Result<Invoice, SignOrCreationError<()>>
121 where
122         ES::Target: EntropySource,
123         NS::Target: NodeSigner,
124         L::Target: Logger,
125 {
126         _create_phantom_invoice::<ES, NS, L>(
127                 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
128                 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
129                 min_final_cltv_expiry_delta, duration_since_epoch,
130         )
131 }
132
133 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
134         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
135         invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
136         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
137 ) -> Result<Invoice, SignOrCreationError<()>>
138 where
139         ES::Target: EntropySource,
140         NS::Target: NodeSigner,
141         L::Target: Logger,
142 {
143
144         if phantom_route_hints.is_empty() {
145                 return Err(SignOrCreationError::CreationError(
146                         CreationError::MissingRouteHints,
147                 ));
148         }
149
150         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
151                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
152         }
153
154         let invoice = match description {
155                 InvoiceDescription::Direct(description) => {
156                         InvoiceBuilder::new(network).description(description.0.clone())
157                 }
158                 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
159         };
160
161         // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
162         let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
163         let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
164                 let payment_secret = create_from_hash(
165                         &keys,
166                         amt_msat,
167                         payment_hash,
168                         invoice_expiry_delta_secs,
169                         duration_since_epoch
170                                 .as_secs(),
171                         min_final_cltv_expiry_delta,
172                 )
173                 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
174                 (payment_hash, payment_secret)
175         } else {
176                 create(
177                         &keys,
178                         amt_msat,
179                         invoice_expiry_delta_secs,
180                         &entropy_source,
181                         duration_since_epoch
182                                 .as_secs(),
183                         min_final_cltv_expiry_delta,
184                 )
185                 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
186         };
187
188         log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
189                 phantom_route_hints.len(), log_bytes!(payment_hash.0));
190
191         let mut invoice = invoice
192                 .duration_since_epoch(duration_since_epoch)
193                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
194                 .payment_secret(payment_secret)
195                 .min_final_cltv_expiry_delta(
196                         // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
197                         min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
198                 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
199         if let Some(amt) = amt_msat {
200                 invoice = invoice.amount_milli_satoshis(amt);
201         }
202
203         for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
204                 log_trace!(logger, "Generating phantom route hints for node {}",
205                         log_pubkey!(real_node_pubkey));
206                 let mut route_hints = filter_channels(channels, amt_msat, &logger);
207
208                 // If we have any public channel, the route hints from `filter_channels` will be empty.
209                 // In that case we create a RouteHint on which we will push a single hop with the phantom
210                 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
211                 // node by looking at our public channels.
212                 if route_hints.is_empty() {
213                         route_hints.push(RouteHint(vec![]))
214                 }
215                 for mut route_hint in route_hints {
216                         route_hint.0.push(RouteHintHop {
217                                 src_node_id: real_node_pubkey,
218                                 short_channel_id: phantom_scid,
219                                 fees: RoutingFees {
220                                         base_msat: 0,
221                                         proportional_millionths: 0,
222                                 },
223                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
224                                 htlc_minimum_msat: None,
225                                 htlc_maximum_msat: None,});
226                         invoice = invoice.private_route(route_hint.clone());
227                 }
228         }
229
230         let raw_invoice = match invoice.build_raw() {
231                 Ok(inv) => inv,
232                 Err(e) => return Err(SignOrCreationError::CreationError(e))
233         };
234         let hrp_str = raw_invoice.hrp.to_string();
235         let hrp_bytes = hrp_str.as_bytes();
236         let data_without_signature = raw_invoice.data.to_base32();
237         let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
238         match signed_raw_invoice {
239                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
240                 Err(e) => Err(SignOrCreationError::SignError(e))
241         }
242 }
243
244 #[cfg(feature = "std")]
245 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
246 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
247 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
248 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
249 /// that the payment secret is valid when the invoice is paid.
250 ///
251 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
252 /// in excess of the current time.
253 ///
254 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
255 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
256 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
257 /// confirmations during routing.
258 ///
259 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
260 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
261         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
262         network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
263         min_final_cltv_expiry_delta: Option<u16>,
264 ) -> Result<Invoice, SignOrCreationError<()>>
265 where
266         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
267         T::Target: BroadcasterInterface,
268         ES::Target: EntropySource,
269         NS::Target: NodeSigner,
270         SP::Target: SignerProvider,
271         F::Target: FeeEstimator,
272         R::Target: Router,
273         L::Target: Logger,
274 {
275         use std::time::SystemTime;
276         let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
277                 .expect("for the foreseeable future this shouldn't happen");
278         create_invoice_from_channelmanager_and_duration_since_epoch(
279                 channelmanager, node_signer, logger, network, amt_msat,
280                 description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
281         )
282 }
283
284 #[cfg(feature = "std")]
285 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
286 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
287 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
288 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
289 /// that the payment secret is valid when the invoice is paid.
290 /// Use this variant if you want to pass the `description_hash` to the invoice.
291 ///
292 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
293 /// in excess of the current time.
294 ///
295 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
296 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
297 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
298 /// confirmations during routing.
299 ///
300 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
301 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>(
302         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
303         network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
304         invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
305 ) -> Result<Invoice, SignOrCreationError<()>>
306 where
307         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
308         T::Target: BroadcasterInterface,
309         ES::Target: EntropySource,
310         NS::Target: NodeSigner,
311         SP::Target: SignerProvider,
312         F::Target: FeeEstimator,
313         R::Target: Router,
314         L::Target: Logger,
315 {
316         use std::time::SystemTime;
317
318         let duration = SystemTime::now()
319                 .duration_since(SystemTime::UNIX_EPOCH)
320                 .expect("for the foreseeable future this shouldn't happen");
321
322         create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
323                 channelmanager, node_signer, logger, network, amt_msat,
324                 description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
325         )
326 }
327
328 /// See [`create_invoice_from_channelmanager_with_description_hash`]
329 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
330 /// available and the current time is supplied by the caller.
331 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>(
332         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
333         network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
334         duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
335 ) -> Result<Invoice, SignOrCreationError<()>>
336                 where
337                         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
338                         T::Target: BroadcasterInterface,
339                         ES::Target: EntropySource,
340                         NS::Target: NodeSigner,
341                         SP::Target: SignerProvider,
342                         F::Target: FeeEstimator,
343                         R::Target: Router,
344                         L::Target: Logger,
345 {
346         _create_invoice_from_channelmanager_and_duration_since_epoch(
347                 channelmanager, node_signer, logger, network, amt_msat,
348                 InvoiceDescription::Hash(&description_hash),
349                 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
350         )
351 }
352
353 /// See [`create_invoice_from_channelmanager`]
354 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
355 /// available and the current time is supplied by the caller.
356 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>(
357         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
358         network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
359         invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
360 ) -> Result<Invoice, SignOrCreationError<()>>
361                 where
362                         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
363                         T::Target: BroadcasterInterface,
364                         ES::Target: EntropySource,
365                         NS::Target: NodeSigner,
366                         SP::Target: SignerProvider,
367                         F::Target: FeeEstimator,
368                         R::Target: Router,
369                         L::Target: Logger,
370 {
371         _create_invoice_from_channelmanager_and_duration_since_epoch(
372                 channelmanager, node_signer, logger, network, amt_msat,
373                 InvoiceDescription::Direct(
374                         &Description::new(description).map_err(SignOrCreationError::CreationError)?,
375                 ),
376                 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
377         )
378 }
379
380 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>(
381         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
382         network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
383         duration_since_epoch: Duration, 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         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
396                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
397         }
398
399         // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
400         // supply.
401         let (payment_hash, payment_secret) = channelmanager
402                 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs, min_final_cltv_expiry_delta)
403                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
404         _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
405                 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch,
406                 invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta)
407 }
408
409 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
410 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
411 /// This may be useful if you're building an on-chain swap or involving another protocol where
412 /// the payment hash is also involved outside the scope of lightning.
413 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>(
414         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
415         network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
416         invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
417 ) -> Result<Invoice, SignOrCreationError<()>>
418         where
419                 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
420                 T::Target: BroadcasterInterface,
421                 ES::Target: EntropySource,
422                 NS::Target: NodeSigner,
423                 SP::Target: SignerProvider,
424                 F::Target: FeeEstimator,
425                 R::Target: Router,
426                 L::Target: Logger,
427 {
428         let payment_secret = channelmanager
429                 .create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs,
430                         min_final_cltv_expiry_delta)
431                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
432         _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
433                 channelmanager, node_signer, logger, network, amt_msat,
434                 InvoiceDescription::Direct(
435                         &Description::new(description).map_err(SignOrCreationError::CreationError)?,
436                 ),
437                 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret,
438                 min_final_cltv_expiry_delta,
439         )
440 }
441
442 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>(
443         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
444         network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
445         invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
446         min_final_cltv_expiry_delta: Option<u16>,
447 ) -> Result<Invoice, SignOrCreationError<()>>
448         where
449                 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
450                 T::Target: BroadcasterInterface,
451                 ES::Target: EntropySource,
452                 NS::Target: NodeSigner,
453                 SP::Target: SignerProvider,
454                 F::Target: FeeEstimator,
455                 R::Target: Router,
456                 L::Target: Logger,
457 {
458         let our_node_pubkey = channelmanager.get_our_node_id();
459         let channels = channelmanager.list_channels();
460
461         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
462                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
463         }
464
465         log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
466
467         let invoice = match description {
468                 InvoiceDescription::Direct(description) => {
469                         InvoiceBuilder::new(network).description(description.0.clone())
470                 }
471                 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
472         };
473
474         let mut invoice = invoice
475                 .duration_since_epoch(duration_since_epoch)
476                 .payee_pub_key(our_node_pubkey)
477                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
478                 .payment_secret(payment_secret)
479                 .basic_mpp()
480                 .min_final_cltv_expiry_delta(
481                         // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
482                         min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
483                 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
484         if let Some(amt) = amt_msat {
485                 invoice = invoice.amount_milli_satoshis(amt);
486         }
487
488         let route_hints = filter_channels(channels, amt_msat, &logger);
489         for hint in route_hints {
490                 invoice = invoice.private_route(hint);
491         }
492
493         let raw_invoice = match invoice.build_raw() {
494                 Ok(inv) => inv,
495                 Err(e) => return Err(SignOrCreationError::CreationError(e))
496         };
497         let hrp_str = raw_invoice.hrp.to_string();
498         let hrp_bytes = hrp_str.as_bytes();
499         let data_without_signature = raw_invoice.data.to_base32();
500         let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
501         match signed_raw_invoice {
502                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
503                 Err(e) => Err(SignOrCreationError::SignError(e))
504         }
505 }
506
507 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
508 /// in the invoice.
509 ///
510 /// The filtering is based on the following criteria:
511 /// * Only one channel per counterparty node
512 /// * Always select the channel with the highest inbound capacity per counterparty node
513 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
514 ///   `is_usable` (i.e. the peer is connected).
515 /// * If any public channel exists, only public [`RouteHint`]s will be returned.
516 /// * If any public, announced, channel exists (i.e. a channel with 7+ confs, to ensure the
517 ///   announcement has had a chance to propagate), no [`RouteHint`]s will be returned, as the
518 ///   sender is expected to find the path by looking at the public channels instead.
519 fn filter_channels<L: Deref>(
520         channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
521 ) -> Vec<RouteHint> where L::Target: Logger {
522         let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
523         let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
524         let mut min_capacity_channel_exists = false;
525         let mut online_channel_exists = false;
526         let mut online_min_capacity_channel_exists = false;
527         let mut has_pub_unconf_chan = false;
528
529         log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
530         for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
531                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
532                         log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
533                         continue;
534                 }
535
536                 if channel.is_public {
537                         if channel.confirmations.is_some() && channel.confirmations < Some(7) {
538                                 // If we have a public channel, but it doesn't have enough confirmations to (yet)
539                                 // be in the public network graph (and have gotten a chance to propagate), include
540                                 // route hints but only for public channels to protect private channel privacy.
541                                 has_pub_unconf_chan = true;
542                         } else {
543                                 // If any public channel exists, return no hints and let the sender
544                                 // look at the public channels instead.
545                                 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
546                                         log_bytes!(channel.channel_id));
547                                 return vec![]
548                         }
549                 }
550
551                 if channel.inbound_capacity_msat >= min_inbound_capacity {
552                         if !min_capacity_channel_exists {
553                                 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
554                                 min_capacity_channel_exists = true;
555                         }
556
557                         if channel.is_usable {
558                                 online_min_capacity_channel_exists = true;
559                         }
560                 }
561
562                 if channel.is_usable && !online_channel_exists {
563                         log_trace!(logger, "Channel with connected peer exists for invoice route hints");
564                         online_channel_exists = true;
565                 }
566
567                 match filtered_channels.entry(channel.counterparty.node_id) {
568                         hash_map::Entry::Occupied(mut entry) => {
569                                 let current_max_capacity = entry.get().inbound_capacity_msat;
570                                 // If this channel is public and the previous channel is not, ensure we replace the
571                                 // previous channel to avoid announcing non-public channels.
572                                 let new_now_public = channel.is_public && !entry.get().is_public;
573                                 // If the public-ness of the channel has not changed (in which case simply defer to
574                                 // `new_now_public), and this channel has a greater capacity, prefer to announce
575                                 // this channel.
576                                 let new_higher_capacity = channel.is_public == entry.get().is_public &&
577                                         channel.inbound_capacity_msat > current_max_capacity;
578                                 if new_now_public || new_higher_capacity {
579                                         log_trace!(logger,
580                                                 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
581                                                 log_pubkey!(channel.counterparty.node_id),
582                                                 log_bytes!(channel.channel_id), channel.short_channel_id,
583                                                 channel.inbound_capacity_msat,
584                                                 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
585                                                 current_max_capacity);
586                                         entry.insert(channel);
587                                 } else {
588                                         log_trace!(logger,
589                                                 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
590                                                 log_pubkey!(channel.counterparty.node_id),
591                                                 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
592                                                 current_max_capacity,
593                                                 log_bytes!(channel.channel_id), channel.short_channel_id,
594                                                 channel.inbound_capacity_msat);
595                                 }
596                         }
597                         hash_map::Entry::Vacant(entry) => {
598                                 entry.insert(channel);
599                         }
600                 }
601         }
602
603         let route_hint_from_channel = |channel: ChannelDetails| {
604                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
605                 RouteHint(vec![RouteHintHop {
606                         src_node_id: channel.counterparty.node_id,
607                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
608                         fees: RoutingFees {
609                                 base_msat: forwarding_info.fee_base_msat,
610                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
611                         },
612                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
613                         htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
614                         htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
615         };
616         // If all channels are private, prefer to return route hints which have a higher capacity than
617         // the payment value and where we're currently connected to the channel counterparty.
618         // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
619         // those which meet at least one criteria.
620         filtered_channels
621                 .into_iter()
622                 .map(|(_, channel)| channel)
623                 .filter(|channel| {
624                         let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
625                         let include_channel = if has_pub_unconf_chan {
626                                 // If we have a public channel, but it doesn't have enough confirmations to (yet)
627                                 // be in the public network graph (and have gotten a chance to propagate), include
628                                 // route hints but only for public channels to protect private channel privacy.
629                                 channel.is_public
630                         } else if online_min_capacity_channel_exists {
631                                 has_enough_capacity && channel.is_usable
632                         } else if min_capacity_channel_exists && online_channel_exists {
633                                 // If there are some online channels and some min_capacity channels, but no
634                                 // online-and-min_capacity channels, just include the min capacity ones and ignore
635                                 // online-ness.
636                                 has_enough_capacity
637                         } else if min_capacity_channel_exists {
638                                 has_enough_capacity
639                         } else if online_channel_exists {
640                                 channel.is_usable
641                         } else { true };
642
643                         if include_channel {
644                                 log_trace!(logger, "Including channel {} in invoice route hints",
645                                         log_bytes!(channel.channel_id));
646                         } else if !has_enough_capacity {
647                                 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
648                                         log_bytes!(channel.channel_id));
649                         } else {
650                                 debug_assert!(!channel.is_usable || (has_pub_unconf_chan && !channel.is_public));
651                                 log_trace!(logger, "Ignoring channel {} with disconnected peer",
652                                         log_bytes!(channel.channel_id));
653                         }
654
655                         include_channel
656                 })
657                 .map(route_hint_from_channel)
658                 .collect::<Vec<RouteHint>>()
659 }
660
661 #[cfg(test)]
662 mod test {
663         use core::time::Duration;
664         use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
665         use bitcoin_hashes::{Hash, sha256};
666         use bitcoin_hashes::sha256::Hash as Sha256;
667         use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
668         use lightning::ln::{PaymentPreimage, PaymentHash};
669         use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
670         use lightning::ln::functional_test_utils::*;
671         use lightning::ln::msgs::ChannelMessageHandler;
672         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
673         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
674         use lightning::util::test_utils;
675         use lightning::util::config::UserConfig;
676         use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
677         use std::collections::HashSet;
678
679         #[test]
680         fn test_from_channelmanager() {
681                 let chanmon_cfgs = create_chanmon_cfgs(2);
682                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
683                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
684                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
685                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
686                 let non_default_invoice_expiry_secs = 4200;
687                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
688                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
689                         Some(10_000), "test".to_string(), Duration::from_secs(1234567),
690                         non_default_invoice_expiry_secs, None).unwrap();
691                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
692                 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
693                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
694                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
695                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
696
697                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
698                 // available.
699                 let chan = &nodes[1].node.list_usable_channels()[0];
700                 assert_eq!(invoice.route_hints().len(), 1);
701                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
702                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
703
704                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
705                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
706
707                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
708                                 invoice.min_final_cltv_expiry_delta() as u32)
709                         .with_features(invoice.features().unwrap().clone())
710                         .with_route_hints(invoice.route_hints());
711                 let route_params = RouteParameters {
712                         payment_params,
713                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
714                 };
715                 let first_hops = nodes[0].node.list_usable_channels();
716                 let network_graph = &node_cfgs[0].network_graph;
717                 let logger = test_utils::TestLogger::new();
718                 let scorer = test_utils::TestScorer::new();
719                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
720                 let route = find_route(
721                         &nodes[0].node.get_our_node_id(), &route_params, network_graph,
722                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
723                 ).unwrap();
724
725                 let payment_event = {
726                         let mut payment_hash = PaymentHash([0; 32]);
727                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
728                         nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
729                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
730                         assert_eq!(added_monitors.len(), 1);
731                         added_monitors.clear();
732
733                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
734                         assert_eq!(events.len(), 1);
735                         SendEvent::from_event(events.remove(0))
736
737                 };
738                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
739                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
740                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
741                 assert_eq!(added_monitors.len(), 1);
742                 added_monitors.clear();
743                 let events = nodes[1].node.get_and_clear_pending_msg_events();
744                 assert_eq!(events.len(), 2);
745         }
746
747         fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
748                 let chanmon_cfgs = create_chanmon_cfgs(2);
749                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
750                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
751                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
752                 let custom_min_final_cltv_expiry_delta = Some(50);
753
754                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
755                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
756                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
757                         if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
758                 ).unwrap();
759                 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
760                         custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
761         }
762
763         #[test]
764         fn test_create_invoice_custom_min_final_cltv_delta() {
765                 do_create_invoice_min_final_cltv_delta(true);
766                 do_create_invoice_min_final_cltv_delta(false);
767         }
768
769         #[test]
770         fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
771                 let chanmon_cfgs = create_chanmon_cfgs(2);
772                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
773                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
774                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
775                 let custom_min_final_cltv_expiry_delta = Some(21);
776
777                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
778                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
779                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
780                         custom_min_final_cltv_expiry_delta,
781                 ).unwrap();
782                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
783         }
784
785         #[test]
786         fn test_create_invoice_with_description_hash() {
787                 let chanmon_cfgs = create_chanmon_cfgs(2);
788                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
789                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
790                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
791                 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
792                 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
793                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
794                         Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
795                 ).unwrap();
796                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
797                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
798                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
799         }
800
801         #[test]
802         fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
803                 let chanmon_cfgs = create_chanmon_cfgs(2);
804                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
805                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
806                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
807                 let payment_hash = PaymentHash([0; 32]);
808                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
809                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
810                         Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
811                         payment_hash, None,
812                 ).unwrap();
813                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
814                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
815                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
816                 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
817         }
818
819         #[test]
820         fn test_hints_has_only_public_confd_channels() {
821                 let chanmon_cfgs = create_chanmon_cfgs(2);
822                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
823                 let mut config = test_default_channel_config();
824                 config.channel_handshake_config.minimum_depth = 1;
825                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
826                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
827
828                 // Create a private channel with lots of capacity and a lower value public channel (without
829                 // confirming the funding tx yet).
830                 let unannounced_scid = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
831                 let conf_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 10_000, 0);
832
833                 // Before the channel is available, we should include the unannounced_scid.
834                 let mut scid_aliases = HashSet::new();
835                 scid_aliases.insert(unannounced_scid.0.short_channel_id_alias.unwrap());
836                 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
837
838                 // However after we mine the funding tx and exchange channel_ready messages for the public
839                 // channel we'll immediately switch to including it as a route hint, even though it isn't
840                 // yet announced.
841                 let pub_channel_scid = mine_transaction(&nodes[0], &conf_tx);
842                 let node_a_pub_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
843                 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &node_a_pub_channel_ready);
844
845                 assert_eq!(mine_transaction(&nodes[1], &conf_tx), pub_channel_scid);
846                 let events = nodes[1].node.get_and_clear_pending_msg_events();
847                 assert_eq!(events.len(), 2);
848                 if let MessageSendEvent::SendChannelReady { msg, .. } = &events[0] {
849                         nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), msg);
850                 } else { panic!(); }
851                 if let MessageSendEvent::SendChannelUpdate { msg, .. } = &events[1] {
852                         nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), msg);
853                 } else { panic!(); }
854
855                 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()));
856
857                 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
858                 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
859
860                 scid_aliases.clear();
861                 scid_aliases.insert(node_a_pub_channel_ready.short_channel_id_alias.unwrap());
862                 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
863                 // This also applies even if the amount is more than the payment amount, to ensure users
864                 // dont screw up their privacy.
865                 match_invoice_routes(Some(50_000_000), &nodes[1], scid_aliases.clone());
866
867                 // The same remains true until the channel has 7 confirmations, at which point we include
868                 // no hints.
869                 connect_blocks(&nodes[1], 5);
870                 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
871                 connect_blocks(&nodes[1], 1);
872                 get_event_msg!(nodes[1], MessageSendEvent::SendAnnouncementSignatures, nodes[0].node.get_our_node_id());
873                 match_invoice_routes(Some(5000), &nodes[1], HashSet::new());
874         }
875
876         #[test]
877         fn test_hints_includes_single_channels_to_nodes() {
878                 let chanmon_cfgs = create_chanmon_cfgs(3);
879                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
880                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
881                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
882
883                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
884                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
885
886                 let mut scid_aliases = HashSet::new();
887                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
888                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
889
890                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
891         }
892
893         #[test]
894         fn test_hints_has_only_highest_inbound_capacity_channel() {
895                 let chanmon_cfgs = create_chanmon_cfgs(2);
896                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
897                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
898                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
899                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
900                 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
901                 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0);
902                 let mut scid_aliases = HashSet::new();
903                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
904                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
905         }
906
907         #[test]
908         fn test_hints_has_only_online_channels() {
909                 let chanmon_cfgs = create_chanmon_cfgs(4);
910                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
911                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
912                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
913                 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
914                 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
915                 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
916
917                 // With all peers connected we should get all hints that have sufficient value
918                 let mut scid_aliases = HashSet::new();
919                 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
920                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
921
922                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
923
924                 // With only one sufficient-value peer connected we should only get its hint
925                 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
926                 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
927                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
928
929                 // If we don't have any sufficient-value peers connected we should get all hints with
930                 // sufficient value, even though there is a connected insufficient-value peer.
931                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
932                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
933                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
934         }
935
936         #[test]
937         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
938                 let chanmon_cfgs = create_chanmon_cfgs(3);
939                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
940                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
941                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
942                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
943
944                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
945                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
946                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
947                 let mut private_chan_cfg = UserConfig::default();
948                 private_chan_cfg.channel_handshake_config.announced_channel = false;
949                 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();
950                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
951                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
952                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
953                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
954
955                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
956
957                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
958                 confirm_transaction_at(&nodes[2], &tx, conf_height);
959                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
960                 confirm_transaction_at(&nodes[0], &tx, conf_height);
961                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
962                 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
963                 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()));
964                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
965                 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
966                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
967                 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
968                 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
969
970                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
971                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
972                 // Therefore only `chan_1_0` should be included in the hints.
973                 let mut scid_aliases = HashSet::new();
974                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
975                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
976         }
977
978         #[test]
979         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
980                 let chanmon_cfgs = create_chanmon_cfgs(3);
981                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
982                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
983                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
984                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
985
986                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
987                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
988                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
989
990                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
991                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
992                 // public channel between `nodes[2]` and `nodes[0]`
993                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
994         }
995
996         #[test]
997         fn test_only_public_channels_includes_no_channels_in_hints() {
998                 let chanmon_cfgs = create_chanmon_cfgs(3);
999                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1000                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1001                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1002                 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1003                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
1004                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
1005
1006                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1007                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1008                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1009
1010                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
1011                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1012         }
1013
1014         #[test]
1015         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
1016                 let chanmon_cfgs = create_chanmon_cfgs(3);
1017                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1018                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1019                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1020                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1021                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
1022
1023                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
1024                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1025                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1026
1027                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
1028
1029                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
1030                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1031                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1032                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1033
1034                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
1035
1036                 // As the invoice amt is above all channels' inbound capacity, they will still be included
1037                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
1038                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1039                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1040
1041                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1042
1043                 // An invoice with no specified amount should include all channels in the route hints.
1044                 let mut scid_aliases_no_specified_amount = HashSet::new();
1045                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1046                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1047
1048                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1049         }
1050
1051         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1052                 invoice_amt: Option<u64>,
1053                 invoice_node: &Node<'a, 'b, 'c>,
1054                 mut chan_ids_to_match: HashSet<u64>
1055         ) {
1056                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
1057                         invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
1058                         Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
1059                         3600, None).unwrap();
1060                 let hints = invoice.private_routes();
1061
1062                 for hint in hints {
1063                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
1064                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1065                 }
1066                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1067         }
1068
1069         #[test]
1070         #[cfg(feature = "std")]
1071         fn test_multi_node_receive() {
1072                 do_test_multi_node_receive(true);
1073                 do_test_multi_node_receive(false);
1074         }
1075
1076         #[cfg(feature = "std")]
1077         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1078                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1079                 let seed_1 = [42u8; 32];
1080                 let seed_2 = [43u8; 32];
1081                 let cross_node_seed = [44u8; 32];
1082                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1083                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1084                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1085                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1086                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1087                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1088                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1089                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1090                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1091                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1092                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1093
1094                 let payment_amt = 10_000;
1095                 let route_hints = vec![
1096                         nodes[1].node.get_phantom_route_hints(),
1097                         nodes[2].node.get_phantom_route_hints(),
1098                 ];
1099
1100                 let user_payment_preimage = PaymentPreimage([1; 32]);
1101                 let payment_hash = if user_generated_pmt_hash {
1102                         Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1103                 } else {
1104                         None
1105                 };
1106                 let non_default_invoice_expiry_secs = 4200;
1107
1108                 let invoice =
1109                         crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1110                                 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1111                                 route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1112                                 Currency::BitcoinTestnet, None, Duration::from_secs(1234567)
1113                         ).unwrap();
1114                 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1115                 let payment_preimage = if user_generated_pmt_hash {
1116                         user_payment_preimage
1117                 } else {
1118                         nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1119                 };
1120
1121                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1122                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1123                 assert_eq!(invoice.route_hints().len(), 2);
1124                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1125                 assert!(!invoice.features().unwrap().supports_basic_mpp());
1126
1127                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
1128                                 invoice.min_final_cltv_expiry_delta() as u32)
1129                         .with_features(invoice.features().unwrap().clone())
1130                         .with_route_hints(invoice.route_hints());
1131                 let params = RouteParameters {
1132                         payment_params,
1133                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1134                 };
1135                 let first_hops = nodes[0].node.list_usable_channels();
1136                 let network_graph = &node_cfgs[0].network_graph;
1137                 let logger = test_utils::TestLogger::new();
1138                 let scorer = test_utils::TestScorer::new();
1139                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1140                 let route = find_route(
1141                         &nodes[0].node.get_our_node_id(), &params, network_graph,
1142                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1143                 ).unwrap();
1144                 let (payment_event, fwd_idx) = {
1145                         let mut payment_hash = PaymentHash([0; 32]);
1146                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1147                         nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
1148                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1149                         assert_eq!(added_monitors.len(), 1);
1150                         added_monitors.clear();
1151
1152                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1153                         assert_eq!(events.len(), 1);
1154                         let fwd_idx = match events[0] {
1155                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1156                                         if node_id == nodes[1].node.get_our_node_id() {
1157                                                 1
1158                                         } else { 2 }
1159                                 },
1160                                 _ => panic!("Unexpected event")
1161                         };
1162                         (SendEvent::from_event(events.remove(0)), fwd_idx)
1163                 };
1164                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1165                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1166
1167                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1168                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1169                 // payments "look real" by taking more time.
1170                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1171                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1172                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1173                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1174
1175                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1176                 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1177                 do_claim_payment_along_route(&nodes[0], &[&vec!(&nodes[fwd_idx])[..]], false, payment_preimage);
1178                 let events = nodes[0].node.get_and_clear_pending_events();
1179                 assert_eq!(events.len(), 2);
1180                 match events[0] {
1181                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1182                                 assert_eq!(payment_preimage, *ev_preimage);
1183                                 assert_eq!(payment_hash, *ev_hash);
1184                                 assert_eq!(fee_paid_msat, &Some(0));
1185                         },
1186                         _ => panic!("Unexpected event")
1187                 }
1188                 match events[1] {
1189                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1190                                 assert_eq!(hash, Some(payment_hash));
1191                         },
1192                         _ => panic!("Unexpected event")
1193                 }
1194         }
1195
1196         #[test]
1197         #[cfg(feature = "std")]
1198         fn test_multi_node_hints_has_htlc_min_max_values() {
1199                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1200                 let seed_1 = [42u8; 32];
1201                 let seed_2 = [43u8; 32];
1202                 let cross_node_seed = [44u8; 32];
1203                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1204                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1205                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1206                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1207                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1208
1209                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1210                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1211
1212                 let payment_amt = 20_000;
1213                 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1214                 let route_hints = vec![
1215                         nodes[1].node.get_phantom_route_hints(),
1216                         nodes[2].node.get_phantom_route_hints(),
1217                 ];
1218
1219                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1220                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1221                                 "test".to_string(), 3600, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1222                                 nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1223
1224                 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1225                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1226                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1227
1228                 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1229                 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1230                 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1231         }
1232
1233         #[test]
1234         #[cfg(feature = "std")]
1235         fn create_phantom_invoice_with_description_hash() {
1236                 let chanmon_cfgs = create_chanmon_cfgs(3);
1237                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1238                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1239                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1240
1241                 let payment_amt = 20_000;
1242                 let route_hints = vec![
1243                         nodes[1].node.get_phantom_route_hints(),
1244                         nodes[2].node.get_phantom_route_hints(),
1245                 ];
1246
1247                 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1248                 let non_default_invoice_expiry_secs = 4200;
1249                 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1250                         &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1251                 >(
1252                         Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1253                         route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1254                         Currency::BitcoinTestnet, None, Duration::from_secs(1234567),
1255                 )
1256                 .unwrap();
1257                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1258                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1259                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1260                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1261         }
1262
1263         #[test]
1264         #[cfg(feature = "std")]
1265         fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1266                 let chanmon_cfgs = create_chanmon_cfgs(3);
1267                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1268                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1269                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1270
1271                 let payment_amt = 20_000;
1272                 let route_hints = vec![
1273                         nodes[1].node.get_phantom_route_hints(),
1274                         nodes[2].node.get_phantom_route_hints(),
1275                 ];
1276                 let user_payment_preimage = PaymentPreimage([1; 32]);
1277                 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1278                 let non_default_invoice_expiry_secs = 4200;
1279                 let min_final_cltv_expiry_delta = Some(100);
1280                 let duration_since_epoch = Duration::from_secs(1234567);
1281                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1282                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1283                                 "".to_string(), non_default_invoice_expiry_secs, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1284                                 nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap();
1285                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1286                 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1287                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1288         }
1289
1290         #[test]
1291         #[cfg(feature = "std")]
1292         fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1293                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1294                 let seed_1 = [42u8; 32];
1295                 let seed_2 = [43u8; 32];
1296                 let cross_node_seed = [44u8; 32];
1297                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1298                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1299                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1300                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1301                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1302
1303                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1304                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1305
1306                 let mut scid_aliases = HashSet::new();
1307                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1308                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1309
1310                 match_multi_node_invoice_routes(
1311                         Some(10_000),
1312                         &nodes[1],
1313                         vec![&nodes[1], &nodes[2],],
1314                         scid_aliases,
1315                         false
1316                 );
1317         }
1318
1319         #[test]
1320         #[cfg(feature = "std")]
1321         fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1322                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1323                 let seed_1 = [42u8; 32];
1324                 let seed_2 = [43u8; 32];
1325                 let cross_node_seed = [44u8; 32];
1326                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1327                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1328                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1329                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1330                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1331
1332                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1333                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1334                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1335
1336                 let mut scid_aliases = HashSet::new();
1337                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1338                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1339                 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1340
1341                 match_multi_node_invoice_routes(
1342                         Some(10_000),
1343                         &nodes[2],
1344                         vec![&nodes[2], &nodes[3],],
1345                         scid_aliases,
1346                         false
1347                 );
1348         }
1349
1350         #[test]
1351         #[cfg(feature = "std")]
1352         fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1353                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1354                 let seed_1 = [42u8; 32];
1355                 let seed_2 = [43u8; 32];
1356                 let cross_node_seed = [44u8; 32];
1357                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1358                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1359                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1360                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1361                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1362
1363                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1364                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1365
1366                 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1367                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1368                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1369                 let mut private_chan_cfg = UserConfig::default();
1370                 private_chan_cfg.channel_handshake_config.announced_channel = false;
1371                 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();
1372                 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1373                 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1374                 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1375                 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1376
1377                 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1378
1379                 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1380                 confirm_transaction_at(&nodes[1], &tx, conf_height);
1381                 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1382                 confirm_transaction_at(&nodes[3], &tx, conf_height);
1383                 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1384                 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1385                 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()));
1386                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1387                 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1388                 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1389                 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1390                 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1391
1392                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1393                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1394                 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1395                 let mut scid_aliases = HashSet::new();
1396                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1397                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1398
1399                 match_multi_node_invoice_routes(
1400                         Some(10_000),
1401                         &nodes[2],
1402                         vec![&nodes[2], &nodes[3],],
1403                         scid_aliases,
1404                         false
1405                 );
1406         }
1407
1408         #[test]
1409         #[cfg(feature = "std")]
1410         fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1411                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1412                 let seed_1 = [42u8; 32];
1413                 let seed_2 = [43u8; 32];
1414                 let cross_node_seed = [44u8; 32];
1415                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1416                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1417                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1418                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1419                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1420
1421                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1422
1423                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1424                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1425                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1426
1427                 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1428                 // `chan_0_2` as `nodes[2]` only has public channels.
1429                 let mut scid_aliases = HashSet::new();
1430                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1431
1432                 match_multi_node_invoice_routes(
1433                         Some(10_000),
1434                         &nodes[1],
1435                         vec![&nodes[1], &nodes[2],],
1436                         scid_aliases,
1437                         true
1438                 );
1439         }
1440
1441         #[test]
1442         #[cfg(feature = "std")]
1443         fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1444                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1445                 let seed_1 = [42u8; 32];
1446                 let seed_2 = [43u8; 32];
1447                 let cross_node_seed = [44u8; 32];
1448                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1449                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1450                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1451                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1452                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1453
1454                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1455                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1456                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1457                 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1458
1459                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1460
1461                 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1462                 // channels for `nodes[2]` as it contains a mix of public and private channels.
1463                 let mut scid_aliases = HashSet::new();
1464                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1465
1466                 match_multi_node_invoice_routes(
1467                         Some(10_000),
1468                         &nodes[2],
1469                         vec![&nodes[2], &nodes[3],],
1470                         scid_aliases,
1471                         true
1472                 );
1473         }
1474
1475         #[test]
1476         #[cfg(feature = "std")]
1477         fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1478                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1479                 let seed_1 = [42u8; 32];
1480                 let seed_2 = [43u8; 32];
1481                 let cross_node_seed = [44u8; 32];
1482                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1483                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1484                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1485                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1486                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1487
1488                 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1489                 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
1490                 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1491                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1492
1493                 let mut scid_aliases = HashSet::new();
1494                 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1495                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1496
1497                 match_multi_node_invoice_routes(
1498                         Some(10_000),
1499                         &nodes[1],
1500                         vec![&nodes[1], &nodes[2],],
1501                         scid_aliases,
1502                         false
1503                 );
1504         }
1505
1506         #[test]
1507         #[cfg(feature = "std")]
1508         fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1509                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1510                 let seed_1 = [42u8; 32];
1511                 let seed_2 = [43u8; 32];
1512                 let cross_node_seed = [44u8; 32];
1513                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1514                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1515                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1516                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1517                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1518
1519                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1520                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1521                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1522
1523                 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1524                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1525                 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1526                 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1527
1528                 match_multi_node_invoice_routes(
1529                         Some(99_000_001),
1530                         &nodes[2],
1531                         vec![&nodes[2], &nodes[3],],
1532                         scid_aliases_99_000_001_msat,
1533                         false
1534                 );
1535
1536                 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1537                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1538                 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1539                 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1540                 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1541
1542                 match_multi_node_invoice_routes(
1543                         Some(99_000_000),
1544                         &nodes[2],
1545                         vec![&nodes[2], &nodes[3],],
1546                         scid_aliases_99_000_000_msat,
1547                         false
1548                 );
1549
1550                 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1551                 // `nodes[2]` them should be included.
1552                 let mut scid_aliases_300_000_000_msat = HashSet::new();
1553                 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1554                 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1555                 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1556
1557                 match_multi_node_invoice_routes(
1558                         Some(300_000_000),
1559                         &nodes[2],
1560                         vec![&nodes[2], &nodes[3],],
1561                         scid_aliases_300_000_000_msat,
1562                         false
1563                 );
1564
1565                 // Since the no specified amount, all channels should included.
1566                 let mut scid_aliases_no_specified_amount = HashSet::new();
1567                 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1568                 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1569                 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1570
1571                 match_multi_node_invoice_routes(
1572                         None,
1573                         &nodes[2],
1574                         vec![&nodes[2], &nodes[3],],
1575                         scid_aliases_no_specified_amount,
1576                         false
1577                 );
1578         }
1579
1580         #[cfg(feature = "std")]
1581         fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1582                 invoice_amt: Option<u64>,
1583                 invoice_node: &Node<'a, 'b, 'c>,
1584                 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1585                 mut chan_ids_to_match: HashSet<u64>,
1586                 nodes_contains_public_channels: bool
1587         ){
1588                 let phantom_route_hints = network_multi_nodes.iter()
1589                         .map(|node| node.node.get_phantom_route_hints())
1590                         .collect::<Vec<PhantomRouteHints>>();
1591                 let phantom_scids = phantom_route_hints.iter()
1592                         .map(|route_hint| route_hint.phantom_scid)
1593                         .collect::<HashSet<u64>>();
1594
1595                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1596                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1597                                 3600, phantom_route_hints, invoice_node.keys_manager, invoice_node.keys_manager,
1598                                 invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1599
1600                 let invoice_hints = invoice.private_routes();
1601
1602                 for hint in invoice_hints {
1603                         let hints = &(hint.0).0;
1604                         match hints.len() {
1605                                 1 => {
1606                                         assert!(nodes_contains_public_channels);
1607                                         let phantom_scid = hints[0].short_channel_id;
1608                                         assert!(phantom_scids.contains(&phantom_scid));
1609                                 },
1610                                 2 => {
1611                                         let hint_short_chan_id = hints[0].short_channel_id;
1612                                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1613                                         let phantom_scid = hints[1].short_channel_id;
1614                                         assert!(phantom_scids.contains(&phantom_scid));
1615                                 },
1616                                 _ => panic!("Incorrect hint length generated")
1617                         }
1618                 }
1619                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1620         }
1621
1622         #[test]
1623         fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1624                 let chanmon_cfgs = create_chanmon_cfgs(2);
1625                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1626                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1627                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1628                 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1629                         nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1630                         Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1631                 );
1632                 match result {
1633                         Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},
1634                         _ => panic!(),
1635                 }
1636         }
1637 }