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