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