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