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