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