Merge pull request #2006 from TheBlueMatt/2023-02-no-recursive-read-locks
[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.len() == 0 {
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, the returned `RouteHint`s will be empty, and the sender will
516 ///   need to find the path by looking at the public channels instead
517 fn filter_channels<L: Deref>(
518         channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
519 ) -> Vec<RouteHint> where L::Target: Logger {
520         let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
521         let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
522         let mut min_capacity_channel_exists = false;
523         let mut online_channel_exists = false;
524         let mut online_min_capacity_channel_exists = false;
525
526         log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
527         for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
528                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
529                         log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
530                         continue;
531                 }
532
533                 if channel.is_public {
534                         // If any public channel exists, return no hints and let the sender
535                         // look at the public channels instead.
536                         log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
537                                 log_bytes!(channel.channel_id));
538                         return vec![]
539                 }
540
541                 if channel.inbound_capacity_msat >= min_inbound_capacity {
542                         if !min_capacity_channel_exists {
543                                 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
544                                 min_capacity_channel_exists = true;
545                         }
546
547                         if channel.is_usable {
548                                 online_min_capacity_channel_exists = true;
549                         }
550                 }
551
552                 if channel.is_usable {
553                         if !online_channel_exists {
554                                 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
555                                 online_channel_exists = true;
556                         }
557                 }
558
559                 match filtered_channels.entry(channel.counterparty.node_id) {
560                         hash_map::Entry::Occupied(mut entry) => {
561                                 let current_max_capacity = entry.get().inbound_capacity_msat;
562                                 if channel.inbound_capacity_msat < current_max_capacity {
563                                         log_trace!(logger,
564                                                 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
565                                                 log_pubkey!(channel.counterparty.node_id),
566                                                 log_bytes!(entry.get().channel_id), current_max_capacity,
567                                                 log_bytes!(channel.channel_id), channel.inbound_capacity_msat);
568                                         continue;
569                                 }
570                                 log_trace!(logger,
571                                         "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
572                                         log_pubkey!(channel.counterparty.node_id),
573                                         log_bytes!(channel.channel_id), channel.inbound_capacity_msat,
574                                         log_bytes!(entry.get().channel_id), current_max_capacity);
575                                 entry.insert(channel);
576                         }
577                         hash_map::Entry::Vacant(entry) => {
578                                 entry.insert(channel);
579                         }
580                 }
581         }
582
583         let route_hint_from_channel = |channel: ChannelDetails| {
584                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
585                 RouteHint(vec![RouteHintHop {
586                         src_node_id: channel.counterparty.node_id,
587                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
588                         fees: RoutingFees {
589                                 base_msat: forwarding_info.fee_base_msat,
590                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
591                         },
592                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
593                         htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
594                         htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
595         };
596         // If all channels are private, prefer to return route hints which have a higher capacity than
597         // the payment value and where we're currently connected to the channel counterparty.
598         // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
599         // those which meet at least one criteria.
600         filtered_channels
601                 .into_iter()
602                 .map(|(_, channel)| channel)
603                 .filter(|channel| {
604                         let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
605                         let include_channel = if online_min_capacity_channel_exists {
606                                 has_enough_capacity && channel.is_usable
607                         } else if min_capacity_channel_exists && online_channel_exists {
608                                 // If there are some online channels and some min_capacity channels, but no
609                                 // online-and-min_capacity channels, just include the min capacity ones and ignore
610                                 // online-ness.
611                                 has_enough_capacity
612                         } else if min_capacity_channel_exists {
613                                 has_enough_capacity
614                         } else if online_channel_exists {
615                                 channel.is_usable
616                         } else { true };
617
618                         if include_channel {
619                                 log_trace!(logger, "Including channel {} in invoice route hints",
620                                         log_bytes!(channel.channel_id));
621                         } else if !has_enough_capacity {
622                                 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
623                                         log_bytes!(channel.channel_id));
624                         } else {
625                                 debug_assert!(!channel.is_usable);
626                                 log_trace!(logger, "Ignoring channel {} with disconnected peer",
627                                         log_bytes!(channel.channel_id));
628                         }
629
630                         include_channel
631                 })
632                 .map(route_hint_from_channel)
633                 .collect::<Vec<RouteHint>>()
634 }
635
636 #[cfg(test)]
637 mod test {
638         use core::time::Duration;
639         use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
640         use bitcoin_hashes::{Hash, sha256};
641         use bitcoin_hashes::sha256::Hash as Sha256;
642         use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
643         use lightning::ln::{PaymentPreimage, PaymentHash};
644         use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
645         use lightning::ln::functional_test_utils::*;
646         use lightning::ln::msgs::ChannelMessageHandler;
647         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
648         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
649         use lightning::util::test_utils;
650         use lightning::util::config::UserConfig;
651         use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
652         use std::collections::HashSet;
653
654         #[test]
655         fn test_from_channelmanager() {
656                 let chanmon_cfgs = create_chanmon_cfgs(2);
657                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
658                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
659                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
660                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
661                 let non_default_invoice_expiry_secs = 4200;
662                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
663                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
664                         Some(10_000), "test".to_string(), Duration::from_secs(1234567),
665                         non_default_invoice_expiry_secs, None).unwrap();
666                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
667                 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
668                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
669                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
670                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
671
672                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
673                 // available.
674                 let chan = &nodes[1].node.list_usable_channels()[0];
675                 assert_eq!(invoice.route_hints().len(), 1);
676                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
677                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
678
679                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
680                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
681
682                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
683                                 invoice.min_final_cltv_expiry_delta() as u32)
684                         .with_features(invoice.features().unwrap().clone())
685                         .with_route_hints(invoice.route_hints());
686                 let route_params = RouteParameters {
687                         payment_params,
688                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
689                 };
690                 let first_hops = nodes[0].node.list_usable_channels();
691                 let network_graph = &node_cfgs[0].network_graph;
692                 let logger = test_utils::TestLogger::new();
693                 let scorer = test_utils::TestScorer::new();
694                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
695                 let route = find_route(
696                         &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
697                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
698                 ).unwrap();
699
700                 let payment_event = {
701                         let mut payment_hash = PaymentHash([0; 32]);
702                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
703                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
704                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
705                         assert_eq!(added_monitors.len(), 1);
706                         added_monitors.clear();
707
708                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
709                         assert_eq!(events.len(), 1);
710                         SendEvent::from_event(events.remove(0))
711
712                 };
713                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
714                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
715                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
716                 assert_eq!(added_monitors.len(), 1);
717                 added_monitors.clear();
718                 let events = nodes[1].node.get_and_clear_pending_msg_events();
719                 assert_eq!(events.len(), 2);
720         }
721
722         fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
723                 let chanmon_cfgs = create_chanmon_cfgs(2);
724                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
725                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
726                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
727                 let custom_min_final_cltv_expiry_delta = Some(50);
728
729                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
730                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
731                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
732                         if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
733                 ).unwrap();
734                 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
735                         custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
736         }
737
738         #[test]
739         fn test_create_invoice_custom_min_final_cltv_delta() {
740                 do_create_invoice_min_final_cltv_delta(true);
741                 do_create_invoice_min_final_cltv_delta(false);
742         }
743
744         #[test]
745         fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
746                 let chanmon_cfgs = create_chanmon_cfgs(2);
747                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
748                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
749                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
750                 let custom_min_final_cltv_expiry_delta = Some(21);
751
752                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
753                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
754                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
755                         custom_min_final_cltv_expiry_delta,
756                 ).unwrap();
757                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
758         }
759
760         #[test]
761         fn test_create_invoice_with_description_hash() {
762                 let chanmon_cfgs = create_chanmon_cfgs(2);
763                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
764                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
765                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
766                 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
767                 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
768                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
769                         Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
770                 ).unwrap();
771                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
772                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
773                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
774         }
775
776         #[test]
777         fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
778                 let chanmon_cfgs = create_chanmon_cfgs(2);
779                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
780                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
781                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
782                 let payment_hash = PaymentHash([0; 32]);
783                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
784                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
785                         Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
786                         payment_hash, None,
787                 ).unwrap();
788                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
789                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
790                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
791                 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
792         }
793
794         #[test]
795         fn test_hints_includes_single_channels_to_nodes() {
796                 let chanmon_cfgs = create_chanmon_cfgs(3);
797                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
798                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
799                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
800
801                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
802                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
803
804                 let mut scid_aliases = HashSet::new();
805                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
806                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
807
808                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
809         }
810
811         #[test]
812         fn test_hints_has_only_highest_inbound_capacity_channel() {
813                 let chanmon_cfgs = create_chanmon_cfgs(2);
814                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
815                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
816                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
817                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
818                 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
819                 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0);
820                 let mut scid_aliases = HashSet::new();
821                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
822                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
823         }
824
825         #[test]
826         fn test_hints_has_only_online_channels() {
827                 let chanmon_cfgs = create_chanmon_cfgs(4);
828                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
829                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
830                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
831                 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
832                 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
833                 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
834
835                 // With all peers connected we should get all hints that have sufficient value
836                 let mut scid_aliases = HashSet::new();
837                 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
838                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
839
840                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
841
842                 // With only one sufficient-value peer connected we should only get its hint
843                 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
844                 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
845                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
846
847                 // If we don't have any sufficient-value peers connected we should get all hints with
848                 // sufficient value, even though there is a connected insufficient-value peer.
849                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
850                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
851                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
852         }
853
854         #[test]
855         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
856                 let chanmon_cfgs = create_chanmon_cfgs(3);
857                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
861
862                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
863                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
864                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
865                 let mut private_chan_cfg = UserConfig::default();
866                 private_chan_cfg.channel_handshake_config.announced_channel = false;
867                 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();
868                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
869                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
870                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
871                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
872
873                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
874
875                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
876                 confirm_transaction_at(&nodes[2], &tx, conf_height);
877                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
878                 confirm_transaction_at(&nodes[0], &tx, conf_height);
879                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
880                 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
881                 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()));
882                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
883                 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
884                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
885                 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
886                 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
887
888                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
889                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
890                 // Therefore only `chan_1_0` should be included in the hints.
891                 let mut scid_aliases = HashSet::new();
892                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
893                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
894         }
895
896         #[test]
897         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
898                 let chanmon_cfgs = create_chanmon_cfgs(3);
899                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
900                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
901                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
902                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
903
904                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
905                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
906                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
907
908                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
909                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
910                 // public channel between `nodes[2]` and `nodes[0]`
911                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
912         }
913
914         #[test]
915         fn test_only_public_channels_includes_no_channels_in_hints() {
916                 let chanmon_cfgs = create_chanmon_cfgs(3);
917                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
918                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
919                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
920                 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
921                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
922                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
923
924                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
925                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
926                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
927
928                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
929                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
930         }
931
932         #[test]
933         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
934                 let chanmon_cfgs = create_chanmon_cfgs(3);
935                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
936                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
937                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
938                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
939                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
940
941                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
942                 let mut scid_aliases_99_000_001_msat = HashSet::new();
943                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
944
945                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
946
947                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
948                 let mut scid_aliases_99_000_000_msat = HashSet::new();
949                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
950                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
951
952                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
953
954                 // As the invoice amt is above all channels' inbound capacity, they will still be included
955                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
956                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
957                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
958
959                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
960
961                 // An invoice with no specified amount should include all channels in the route hints.
962                 let mut scid_aliases_no_specified_amount = HashSet::new();
963                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
964                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
965
966                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
967         }
968
969         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
970                 invoice_amt: Option<u64>,
971                 invoice_node: &Node<'a, 'b, 'c>,
972                 mut chan_ids_to_match: HashSet<u64>
973         ) {
974                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
975                         &invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
976                         Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
977                         3600, None).unwrap();
978                 let hints = invoice.private_routes();
979
980                 for hint in hints {
981                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
982                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
983                 }
984                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
985         }
986
987         #[test]
988         #[cfg(feature = "std")]
989         fn test_multi_node_receive() {
990                 do_test_multi_node_receive(true);
991                 do_test_multi_node_receive(false);
992         }
993
994         #[cfg(feature = "std")]
995         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
996                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
997                 let seed_1 = [42 as u8; 32];
998                 let seed_2 = [43 as u8; 32];
999                 let cross_node_seed = [44 as u8; 32];
1000                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1001                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1002                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1003                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1004                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1005                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1006                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1007                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1008                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1009                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1010                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1011
1012                 let payment_amt = 10_000;
1013                 let route_hints = vec![
1014                         nodes[1].node.get_phantom_route_hints(),
1015                         nodes[2].node.get_phantom_route_hints(),
1016                 ];
1017
1018                 let user_payment_preimage = PaymentPreimage([1; 32]);
1019                 let payment_hash = if user_generated_pmt_hash {
1020                         Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1021                 } else {
1022                         None
1023                 };
1024                 let non_default_invoice_expiry_secs = 4200;
1025
1026                 let invoice =
1027                         crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1028                                 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1029                                 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1030                                 Currency::BitcoinTestnet, None, Duration::from_secs(1234567)
1031                         ).unwrap();
1032                 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1033                 let payment_preimage = if user_generated_pmt_hash {
1034                         user_payment_preimage
1035                 } else {
1036                         nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1037                 };
1038
1039                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1040                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1041                 assert_eq!(invoice.route_hints().len(), 2);
1042                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1043                 assert!(!invoice.features().unwrap().supports_basic_mpp());
1044
1045                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
1046                                 invoice.min_final_cltv_expiry_delta() as u32)
1047                         .with_features(invoice.features().unwrap().clone())
1048                         .with_route_hints(invoice.route_hints());
1049                 let params = RouteParameters {
1050                         payment_params,
1051                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1052                 };
1053                 let first_hops = nodes[0].node.list_usable_channels();
1054                 let network_graph = &node_cfgs[0].network_graph;
1055                 let logger = test_utils::TestLogger::new();
1056                 let scorer = test_utils::TestScorer::new();
1057                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1058                 let route = find_route(
1059                         &nodes[0].node.get_our_node_id(), &params, &network_graph,
1060                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1061                 ).unwrap();
1062                 let (payment_event, fwd_idx) = {
1063                         let mut payment_hash = PaymentHash([0; 32]);
1064                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1065                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
1066                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1067                         assert_eq!(added_monitors.len(), 1);
1068                         added_monitors.clear();
1069
1070                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1071                         assert_eq!(events.len(), 1);
1072                         let fwd_idx = match events[0] {
1073                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1074                                         if node_id == nodes[1].node.get_our_node_id() {
1075                                                 1
1076                                         } else { 2 }
1077                                 },
1078                                 _ => panic!("Unexpected event")
1079                         };
1080                         (SendEvent::from_event(events.remove(0)), fwd_idx)
1081                 };
1082                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1083                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1084
1085                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1086                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1087                 // payments "look real" by taking more time.
1088                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1089                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1090                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1091                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1092
1093                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1094                 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1095                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
1096                 let events = nodes[0].node.get_and_clear_pending_events();
1097                 assert_eq!(events.len(), 2);
1098                 match events[0] {
1099                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1100                                 assert_eq!(payment_preimage, *ev_preimage);
1101                                 assert_eq!(payment_hash, *ev_hash);
1102                                 assert_eq!(fee_paid_msat, &Some(0));
1103                         },
1104                         _ => panic!("Unexpected event")
1105                 }
1106                 match events[1] {
1107                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1108                                 assert_eq!(hash, Some(payment_hash));
1109                         },
1110                         _ => panic!("Unexpected event")
1111                 }
1112         }
1113
1114         #[test]
1115         #[cfg(feature = "std")]
1116         fn test_multi_node_hints_has_htlc_min_max_values() {
1117                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1118                 let seed_1 = [42 as u8; 32];
1119                 let seed_2 = [43 as u8; 32];
1120                 let cross_node_seed = [44 as u8; 32];
1121                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1122                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1123                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1124                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1125                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1126
1127                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1128                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1129
1130                 let payment_amt = 20_000;
1131                 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1132                 let route_hints = vec![
1133                         nodes[1].node.get_phantom_route_hints(),
1134                         nodes[2].node.get_phantom_route_hints(),
1135                 ];
1136
1137                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1138                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1139                                 "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1140                                 &nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1141
1142                 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1143                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1144                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1145
1146                 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1147                 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1148                 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1149         }
1150
1151         #[test]
1152         #[cfg(feature = "std")]
1153         fn create_phantom_invoice_with_description_hash() {
1154                 let chanmon_cfgs = create_chanmon_cfgs(3);
1155                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1156                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1157                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1158
1159                 let payment_amt = 20_000;
1160                 let route_hints = vec![
1161                         nodes[1].node.get_phantom_route_hints(),
1162                         nodes[2].node.get_phantom_route_hints(),
1163                 ];
1164
1165                 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1166                 let non_default_invoice_expiry_secs = 4200;
1167                 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1168                         &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1169                 >(
1170                         Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1171                         route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1172                         Currency::BitcoinTestnet, None, Duration::from_secs(1234567),
1173                 )
1174                 .unwrap();
1175                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1176                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1177                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1178                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1179         }
1180
1181         #[test]
1182         #[cfg(feature = "std")]
1183         fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1184                 let chanmon_cfgs = create_chanmon_cfgs(3);
1185                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1186                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1187                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1188
1189                 let payment_amt = 20_000;
1190                 let route_hints = vec![
1191                         nodes[1].node.get_phantom_route_hints(),
1192                         nodes[2].node.get_phantom_route_hints(),
1193                 ];
1194                 let user_payment_preimage = PaymentPreimage([1; 32]);
1195                 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1196                 let non_default_invoice_expiry_secs = 4200;
1197                 let min_final_cltv_expiry_delta = Some(100);
1198                 let duration_since_epoch = Duration::from_secs(1234567);
1199                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1200                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1201                                 "".to_string(), non_default_invoice_expiry_secs, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1202                                 &nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap();
1203                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1204                 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1205                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1206         }
1207
1208         #[test]
1209         #[cfg(feature = "std")]
1210         fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1211                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1212                 let seed_1 = [42 as u8; 32];
1213                 let seed_2 = [43 as u8; 32];
1214                 let cross_node_seed = [44 as u8; 32];
1215                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1216                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1217                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1218                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1219                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1220
1221                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1222                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1223
1224                 let mut scid_aliases = HashSet::new();
1225                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1226                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1227
1228                 match_multi_node_invoice_routes(
1229                         Some(10_000),
1230                         &nodes[1],
1231                         vec![&nodes[1], &nodes[2],],
1232                         scid_aliases,
1233                         false
1234                 );
1235         }
1236
1237         #[test]
1238         #[cfg(feature = "std")]
1239         fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1240                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1241                 let seed_1 = [42 as u8; 32];
1242                 let seed_2 = [43 as u8; 32];
1243                 let cross_node_seed = [44 as u8; 32];
1244                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1245                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1246                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1247                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1248                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1249
1250                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1251                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1252                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1253
1254                 let mut scid_aliases = HashSet::new();
1255                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1256                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1257                 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1258
1259                 match_multi_node_invoice_routes(
1260                         Some(10_000),
1261                         &nodes[2],
1262                         vec![&nodes[2], &nodes[3],],
1263                         scid_aliases,
1264                         false
1265                 );
1266         }
1267
1268         #[test]
1269         #[cfg(feature = "std")]
1270         fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1271                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1272                 let seed_1 = [42 as u8; 32];
1273                 let seed_2 = [43 as u8; 32];
1274                 let cross_node_seed = [44 as u8; 32];
1275                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1276                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1277                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1278                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1279                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1280
1281                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1282                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1283
1284                 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1285                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1286                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1287                 let mut private_chan_cfg = UserConfig::default();
1288                 private_chan_cfg.channel_handshake_config.announced_channel = false;
1289                 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();
1290                 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1291                 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1292                 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1293                 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1294
1295                 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1296
1297                 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1298                 confirm_transaction_at(&nodes[1], &tx, conf_height);
1299                 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1300                 confirm_transaction_at(&nodes[3], &tx, conf_height);
1301                 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1302                 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1303                 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()));
1304                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1305                 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1306                 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1307                 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1308                 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1309
1310                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1311                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1312                 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1313                 let mut scid_aliases = HashSet::new();
1314                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1315                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1316
1317                 match_multi_node_invoice_routes(
1318                         Some(10_000),
1319                         &nodes[2],
1320                         vec![&nodes[2], &nodes[3],],
1321                         scid_aliases,
1322                         false
1323                 );
1324         }
1325
1326         #[test]
1327         #[cfg(feature = "std")]
1328         fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1329                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1330                 let seed_1 = [42 as u8; 32];
1331                 let seed_2 = [43 as u8; 32];
1332                 let cross_node_seed = [44 as u8; 32];
1333                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1334                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1335                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1336                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1337                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1338
1339                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1340
1341                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1342                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1343                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1344
1345                 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1346                 // `chan_0_2` as `nodes[2]` only has public channels.
1347                 let mut scid_aliases = HashSet::new();
1348                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1349
1350                 match_multi_node_invoice_routes(
1351                         Some(10_000),
1352                         &nodes[1],
1353                         vec![&nodes[1], &nodes[2],],
1354                         scid_aliases,
1355                         true
1356                 );
1357         }
1358
1359         #[test]
1360         #[cfg(feature = "std")]
1361         fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1362                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1363                 let seed_1 = [42 as u8; 32];
1364                 let seed_2 = [43 as u8; 32];
1365                 let cross_node_seed = [44 as u8; 32];
1366                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1367                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1368                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1369                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1370                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1371
1372                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1373                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1374                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1375                 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1376
1377                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1378
1379                 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1380                 // channels for `nodes[2]` as it contains a mix of public and private channels.
1381                 let mut scid_aliases = HashSet::new();
1382                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1383
1384                 match_multi_node_invoice_routes(
1385                         Some(10_000),
1386                         &nodes[2],
1387                         vec![&nodes[2], &nodes[3],],
1388                         scid_aliases,
1389                         true
1390                 );
1391         }
1392
1393         #[test]
1394         #[cfg(feature = "std")]
1395         fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1396                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1397                 let seed_1 = [42 as u8; 32];
1398                 let seed_2 = [43 as u8; 32];
1399                 let cross_node_seed = [44 as u8; 32];
1400                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1401                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1402                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1403                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1404                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1405
1406                 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1407                 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
1408                 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1409                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1410
1411                 let mut scid_aliases = HashSet::new();
1412                 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1413                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1414
1415                 match_multi_node_invoice_routes(
1416                         Some(10_000),
1417                         &nodes[1],
1418                         vec![&nodes[1], &nodes[2],],
1419                         scid_aliases,
1420                         false
1421                 );
1422         }
1423
1424         #[test]
1425         #[cfg(feature = "std")]
1426         fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1427                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1428                 let seed_1 = [42 as u8; 32];
1429                 let seed_2 = [43 as u8; 32];
1430                 let cross_node_seed = [44 as u8; 32];
1431                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1432                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1433                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1434                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1435                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1436
1437                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1438                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1439                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1440
1441                 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1442                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1443                 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1444                 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1445
1446                 match_multi_node_invoice_routes(
1447                         Some(99_000_001),
1448                         &nodes[2],
1449                         vec![&nodes[2], &nodes[3],],
1450                         scid_aliases_99_000_001_msat,
1451                         false
1452                 );
1453
1454                 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1455                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1456                 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1457                 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1458                 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1459
1460                 match_multi_node_invoice_routes(
1461                         Some(99_000_000),
1462                         &nodes[2],
1463                         vec![&nodes[2], &nodes[3],],
1464                         scid_aliases_99_000_000_msat,
1465                         false
1466                 );
1467
1468                 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1469                 // `nodes[2]` them should be included.
1470                 let mut scid_aliases_300_000_000_msat = HashSet::new();
1471                 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1472                 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1473                 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1474
1475                 match_multi_node_invoice_routes(
1476                         Some(300_000_000),
1477                         &nodes[2],
1478                         vec![&nodes[2], &nodes[3],],
1479                         scid_aliases_300_000_000_msat,
1480                         false
1481                 );
1482
1483                 // Since the no specified amount, all channels should included.
1484                 let mut scid_aliases_no_specified_amount = HashSet::new();
1485                 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1486                 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1487                 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1488
1489                 match_multi_node_invoice_routes(
1490                         None,
1491                         &nodes[2],
1492                         vec![&nodes[2], &nodes[3],],
1493                         scid_aliases_no_specified_amount,
1494                         false
1495                 );
1496         }
1497
1498         #[cfg(feature = "std")]
1499         fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1500                 invoice_amt: Option<u64>,
1501                 invoice_node: &Node<'a, 'b, 'c>,
1502                 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1503                 mut chan_ids_to_match: HashSet<u64>,
1504                 nodes_contains_public_channels: bool
1505         ){
1506                 let phantom_route_hints = network_multi_nodes.iter()
1507                         .map(|node| node.node.get_phantom_route_hints())
1508                         .collect::<Vec<PhantomRouteHints>>();
1509                 let phantom_scids = phantom_route_hints.iter()
1510                         .map(|route_hint| route_hint.phantom_scid)
1511                         .collect::<HashSet<u64>>();
1512
1513                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1514                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1515                                 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.keys_manager,
1516                                 &invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1517
1518                 let invoice_hints = invoice.private_routes();
1519
1520                 for hint in invoice_hints {
1521                         let hints = &(hint.0).0;
1522                         match hints.len() {
1523                                 1 => {
1524                                         assert!(nodes_contains_public_channels);
1525                                         let phantom_scid = hints[0].short_channel_id;
1526                                         assert!(phantom_scids.contains(&phantom_scid));
1527                                 },
1528                                 2 => {
1529                                         let hint_short_chan_id = hints[0].short_channel_id;
1530                                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1531                                         let phantom_scid = hints[1].short_channel_id;
1532                                         assert!(phantom_scids.contains(&phantom_scid));
1533                                 },
1534                                 _ => panic!("Incorrect hint length generated")
1535                         }
1536                 }
1537                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1538         }
1539
1540         #[test]
1541         fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1542                 let chanmon_cfgs = create_chanmon_cfgs(2);
1543                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1544                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1545                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1546                 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1547                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1548                         Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1549                 );
1550                 match result {
1551                         Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},
1552                         _ => panic!(),
1553                 }
1554         }
1555 }