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