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