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