Add tests for create invoice route hints filtering
[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 hint in phantom_route_hints {
70                 for channel in &hint.channels {
71                         let short_channel_id = match channel.get_inbound_payment_scid() {
72                                 Some(id) => id,
73                                 None => continue,
74                         };
75                         let forwarding_info = match &channel.counterparty.forwarding_info {
76                                 Some(info) => info.clone(),
77                                 None => continue,
78                         };
79                         invoice = invoice.private_route(RouteHint(vec![
80                                         RouteHintHop {
81                                                 src_node_id: channel.counterparty.node_id,
82                                                 short_channel_id,
83                                                 fees: RoutingFees {
84                                                         base_msat: forwarding_info.fee_base_msat,
85                                                         proportional_millionths: forwarding_info.fee_proportional_millionths,
86                                                 },
87                                                 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
88                                                 htlc_minimum_msat: None,
89                                                 htlc_maximum_msat: None,
90                                         },
91                                         RouteHintHop {
92                                                 src_node_id: hint.real_node_pubkey,
93                                                 short_channel_id: hint.phantom_scid,
94                                                 fees: RoutingFees {
95                                                         base_msat: 0,
96                                                         proportional_millionths: 0,
97                                                 },
98                                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
99                                                 htlc_minimum_msat: None,
100                                                 htlc_maximum_msat: None,
101                                         }])
102                         );
103                 }
104         }
105
106         let raw_invoice = match invoice.build_raw() {
107                 Ok(inv) => inv,
108                 Err(e) => return Err(SignOrCreationError::CreationError(e))
109         };
110         let hrp_str = raw_invoice.hrp.to_string();
111         let hrp_bytes = hrp_str.as_bytes();
112         let data_without_signature = raw_invoice.data.to_base32();
113         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
114         match signed_raw_invoice {
115                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
116                 Err(e) => Err(SignOrCreationError::SignError(e))
117         }
118 }
119
120 #[cfg(feature = "std")]
121 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
122 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
123 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
124 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
125 /// that the payment secret is valid when the invoice is paid.
126 pub fn create_invoice_from_channelmanager<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
127         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
128         amt_msat: Option<u64>, description: String
129 ) -> Result<Invoice, SignOrCreationError<()>>
130 where
131         M::Target: chain::Watch<Signer>,
132         T::Target: BroadcasterInterface,
133         K::Target: KeysInterface<Signer = Signer>,
134         F::Target: FeeEstimator,
135         L::Target: Logger,
136 {
137         use std::time::SystemTime;
138         let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
139                 .expect("for the foreseeable future this shouldn't happen");
140         create_invoice_from_channelmanager_and_duration_since_epoch(
141                 channelmanager,
142                 keys_manager,
143                 network,
144                 amt_msat,
145                 description,
146                 duration
147         )
148 }
149
150 /// See [`create_invoice_from_channelmanager`]
151 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
152 /// available and the current time is supplied by the caller.
153 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
154         channelmanager: &ChannelManager<Signer, M, T, K, F, L>, keys_manager: K, network: Currency,
155         amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
156 ) -> Result<Invoice, SignOrCreationError<()>>
157 where
158         M::Target: chain::Watch<Signer>,
159         T::Target: BroadcasterInterface,
160         K::Target: KeysInterface<Signer = Signer>,
161         F::Target: FeeEstimator,
162         L::Target: Logger,
163 {
164         let route_hints = filter_channels(channelmanager.list_usable_channels(), amt_msat);
165
166         // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
167         // supply.
168         let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
169                 amt_msat, DEFAULT_EXPIRY_TIME.try_into().unwrap())
170                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
171         let our_node_pubkey = channelmanager.get_our_node_id();
172         let mut invoice = InvoiceBuilder::new(network)
173                 .description(description)
174                 .duration_since_epoch(duration_since_epoch)
175                 .payee_pub_key(our_node_pubkey)
176                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
177                 .payment_secret(payment_secret)
178                 .basic_mpp()
179                 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
180         if let Some(amt) = amt_msat {
181                 invoice = invoice.amount_milli_satoshis(amt);
182         }
183         for hint in route_hints {
184                 invoice = invoice.private_route(hint);
185         }
186
187         let raw_invoice = match invoice.build_raw() {
188                 Ok(inv) => inv,
189                 Err(e) => return Err(SignOrCreationError::CreationError(e))
190         };
191         let hrp_str = raw_invoice.hrp.to_string();
192         let hrp_bytes = hrp_str.as_bytes();
193         let data_without_signature = raw_invoice.data.to_base32();
194         let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
195         match signed_raw_invoice {
196                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
197                 Err(e) => Err(SignOrCreationError::SignError(e))
198         }
199 }
200
201 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
202 /// in the invoice.
203 ///
204 /// The filtering is based on the following criteria:
205 /// * Only one channel per counterparty node
206 /// * Always select the channel with the highest inbound capacity per counterparty node
207 /// * Filter out channels with a lower inbound capacity than `min_inbound_capacity_msat`, if any
208 /// channel with a higher or equal inbound capacity than `min_inbound_capacity_msat` exists
209 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
210 /// need to find the path by looking at the public channels instead
211 fn filter_channels(channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>) -> Vec<RouteHint>{
212         let mut filtered_channels: HashMap<PublicKey, &ChannelDetails> = HashMap::new();
213         let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
214         let mut min_capacity_channel_exists = false;
215
216         for channel in channels.iter() {
217                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
218                         continue;
219                 }
220
221                 if channel.is_public {
222                         // If any public channel exists, return no hints and let the sender
223                         // look at the public channels instead.
224                         return vec![]
225                 }
226
227                 if channel.inbound_capacity_msat >= min_inbound_capacity {
228                         min_capacity_channel_exists = true;
229                 };
230                 match filtered_channels.entry(channel.counterparty.node_id) {
231                         hash_map::Entry::Occupied(mut entry) => {
232                                 let current_max_capacity = entry.get().inbound_capacity_msat;
233                                 if channel.inbound_capacity_msat < current_max_capacity {
234                                         continue;
235                                 }
236                                 entry.insert(channel);
237                         }
238                         hash_map::Entry::Vacant(entry) => {
239                                 entry.insert(channel);
240                         }
241                 }
242         }
243
244         let route_hint_from_channel = |channel: &ChannelDetails| {
245                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
246                 RouteHint(vec![RouteHintHop {
247                         src_node_id: channel.counterparty.node_id,
248                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
249                         fees: RoutingFees {
250                                 base_msat: forwarding_info.fee_base_msat,
251                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
252                         },
253                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
254                         htlc_minimum_msat: None,
255                         htlc_maximum_msat: None,}])
256         };
257         // If all channels are private, return the route hint for the highest inbound capacity channel
258         // per counterparty node. If channels with an higher inbound capacity than the
259         // min_inbound_capacity exists, filter out the channels with a lower capacity than that.
260         filtered_channels.into_iter()
261                 .filter(|(_counterparty_id, channel)| {
262                         min_capacity_channel_exists && channel.inbound_capacity_msat >= min_inbound_capacity ||
263                         !min_capacity_channel_exists
264                 })
265                 .map(|(_counterparty_id, channel)| route_hint_from_channel(&channel))
266                 .collect::<Vec<RouteHint>>()
267 }
268
269 /// A [`Router`] implemented using [`find_route`].
270 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
271         network_graph: G,
272         logger: L,
273         random_seed_bytes: Mutex<[u8; 32]>,
274 }
275
276 impl<G: Deref<Target = NetworkGraph>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
277         /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
278         /// `random_seed_bytes`.
279         pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32]) -> Self {
280                 let random_seed_bytes = Mutex::new(random_seed_bytes);
281                 Self { network_graph, logger, random_seed_bytes }
282         }
283 }
284
285 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
286 where L::Target: Logger {
287         fn find_route(
288                 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
289                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
290         ) -> Result<Route, LightningError> {
291                 let random_seed_bytes = {
292                         let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
293                         *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
294                         *locked_random_seed_bytes
295                 };
296                 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
297         }
298 }
299
300 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
301 where
302         M::Target: chain::Watch<Signer>,
303         T::Target: BroadcasterInterface,
304         K::Target: KeysInterface<Signer = Signer>,
305         F::Target: FeeEstimator,
306         L::Target: Logger,
307 {
308         fn node_id(&self) -> PublicKey {
309                 self.get_our_node_id()
310         }
311
312         fn first_hops(&self) -> Vec<ChannelDetails> {
313                 self.list_usable_channels()
314         }
315
316         fn send_payment(
317                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
318         ) -> Result<PaymentId, PaymentSendFailure> {
319                 self.send_payment(route, payment_hash, payment_secret)
320         }
321
322         fn send_spontaneous_payment(
323                 &self, route: &Route, payment_preimage: PaymentPreimage,
324         ) -> Result<PaymentId, PaymentSendFailure> {
325                 self.send_spontaneous_payment(route, Some(payment_preimage))
326                         .map(|(_, payment_id)| payment_id)
327         }
328
329         fn retry_payment(
330                 &self, route: &Route, payment_id: PaymentId
331         ) -> Result<(), PaymentSendFailure> {
332                 self.retry_payment(route, payment_id)
333         }
334
335         fn abandon_payment(&self, payment_id: PaymentId) {
336                 self.abandon_payment(payment_id)
337         }
338 }
339
340 #[cfg(test)]
341 mod test {
342         use core::time::Duration;
343         use {Currency, Description, InvoiceDescription};
344         use bitcoin_hashes::Hash;
345         use bitcoin_hashes::sha256::Hash as Sha256;
346         use lightning::chain::keysinterface::PhantomKeysManager;
347         use lightning::ln::{PaymentPreimage, PaymentHash};
348         use lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY;
349         use lightning::ln::functional_test_utils::*;
350         use lightning::ln::features::InitFeatures;
351         use lightning::ln::msgs::ChannelMessageHandler;
352         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
353         use lightning::util::enforcing_trait_impls::EnforcingSigner;
354         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
355         use lightning::util::test_utils;
356         use lightning::util::config::UserConfig;
357         use lightning::chain::keysinterface::KeysInterface;
358         use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
359         use std::collections::HashSet;
360
361         #[test]
362         fn test_from_channelmanager() {
363                 let chanmon_cfgs = create_chanmon_cfgs(2);
364                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
365                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
366                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
367                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
368                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
369                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
370                         Duration::from_secs(1234567)).unwrap();
371                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
372                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
373                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
374
375                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
376                 // available.
377                 assert_eq!(invoice.route_hints().len(), 1);
378                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
379                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id,
380                         nodes[1].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
381
382                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
383                         .with_features(invoice.features().unwrap().clone())
384                         .with_route_hints(invoice.route_hints());
385                 let route_params = RouteParameters {
386                         payment_params,
387                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
388                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
389                 };
390                 let first_hops = nodes[0].node.list_usable_channels();
391                 let network_graph = node_cfgs[0].network_graph;
392                 let logger = test_utils::TestLogger::new();
393                 let scorer = test_utils::TestScorer::with_penalty(0);
394                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
395                 let route = find_route(
396                         &nodes[0].node.get_our_node_id(), &route_params, network_graph,
397                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
398                 ).unwrap();
399
400                 let payment_event = {
401                         let mut payment_hash = PaymentHash([0; 32]);
402                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
403                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
404                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
405                         assert_eq!(added_monitors.len(), 1);
406                         added_monitors.clear();
407
408                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
409                         assert_eq!(events.len(), 1);
410                         SendEvent::from_event(events.remove(0))
411
412                 };
413                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
414                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
415                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
416                 assert_eq!(added_monitors.len(), 1);
417                 added_monitors.clear();
418                 let events = nodes[1].node.get_and_clear_pending_msg_events();
419                 assert_eq!(events.len(), 2);
420         }
421
422         #[test]
423         fn test_hints_includes_single_channels_to_nodes() {
424                 let chanmon_cfgs = create_chanmon_cfgs(3);
425                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
426                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
427                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
428
429                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
430                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
431
432                 let mut scid_aliases = HashSet::new();
433                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
434                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
435
436                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
437         }
438
439         #[test]
440         fn test_hints_has_only_highest_inbound_capacity_channel() {
441                 let chanmon_cfgs = create_chanmon_cfgs(2);
442                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
443                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
444                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
445                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
446                 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());
447                 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());
448
449                 let mut scid_aliases = HashSet::new();
450                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
451
452                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
453         }
454
455         #[test]
456         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
457                 let chanmon_cfgs = create_chanmon_cfgs(3);
458                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
459                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
460                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
461                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
462
463                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
464                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
465                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
466                 let mut private_chan_cfg = UserConfig::default();
467                 private_chan_cfg.channel_options.announced_channel = false;
468                 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();
469                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
470                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &open_channel);
471                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
472                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
473
474                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
475
476                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
477                 confirm_transaction_at(&nodes[2], &tx, conf_height);
478                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
479                 confirm_transaction_at(&nodes[0], &tx, conf_height);
480                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
481                 let as_funding_locked = get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
482                 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()));
483                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
484                 nodes[0].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &as_funding_locked);
485                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
486
487                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
488                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
489                 // Therefore only `chan_1_0` should be included in the hints.
490                 let mut scid_aliases = HashSet::new();
491                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
492                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
493         }
494
495         #[test]
496         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
497                 let chanmon_cfgs = create_chanmon_cfgs(3);
498                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
499                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
500                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
501                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
502
503                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
504                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
505                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
506
507                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
508                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
509                 // public channel between `nodes[2]` and `nodes[0]`
510                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
511         }
512
513         #[test]
514         fn test_only_public_channels_includes_no_channels_in_hints() {
515                 let chanmon_cfgs = create_chanmon_cfgs(3);
516                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
517                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
518                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
519                 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
520                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
521                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
522
523                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
524                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
525                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
526
527                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
528                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
529         }
530
531         #[test]
532         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
533                 let chanmon_cfgs = create_chanmon_cfgs(3);
534                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
535                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
536                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
537                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
538                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
539
540                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
541                 let mut scid_aliases_99_000_001_msat = HashSet::new();
542                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
543
544                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
545
546                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
547                 let mut scid_aliases_99_000_000_msat = HashSet::new();
548                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
549                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
550
551                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
552
553                 // As the invoice amt is above all channels' inbound capacity, they will still be included
554                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
555                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
556                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
557
558                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
559
560                 // An invoice with no specified amount should include all channels in the route hints.
561                 let mut scid_aliases_no_specified_amount = HashSet::new();
562                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
563                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
564
565                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
566         }
567
568         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
569                 invoice_amt: Option<u64>,
570                 invoice_node: &Node<'a, 'b, 'c>,
571                 mut chan_ids_to_match: HashSet<u64>
572         ) {
573                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
574                         &invoice_node.node, invoice_node.keys_manager, Currency::BitcoinTestnet, invoice_amt, "test".to_string(),
575                         Duration::from_secs(1234567)).unwrap();
576                 let hints = invoice.private_routes();
577
578                 for hint in hints {
579                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
580                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
581                 }
582                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
583         }
584
585         #[test]
586         #[cfg(feature = "std")]
587         fn test_multi_node_receive() {
588                 do_test_multi_node_receive(true);
589                 do_test_multi_node_receive(false);
590         }
591
592         #[cfg(feature = "std")]
593         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
594                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
595                 let seed_1 = [42 as u8; 32];
596                 let seed_2 = [43 as u8; 32];
597                 let cross_node_seed = [44 as u8; 32];
598                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
599                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
600                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
601                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
602                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
603                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
604                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
605                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
606                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
607                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
608                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
609
610                 let payment_amt = 10_000;
611                 let (payment_preimage, payment_hash, payment_secret) = {
612                         if user_generated_pmt_hash {
613                                 let payment_preimage = PaymentPreimage([1; 32]);
614                                 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0[..]).into_inner());
615                                 let payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(payment_amt), 3600).unwrap();
616                                 (payment_preimage, payment_hash, payment_secret)
617                         } else {
618                                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
619                                 let payment_preimage = nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap();
620                                 (payment_preimage, payment_hash, payment_secret)
621                         }
622                 };
623                 let route_hints = vec![
624                         nodes[1].node.get_phantom_route_hints(),
625                         nodes[2].node.get_phantom_route_hints(),
626                 ];
627                 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();
628
629                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
630                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
631                 assert_eq!(invoice.route_hints().len(), 2);
632                 assert!(!invoice.features().unwrap().supports_basic_mpp());
633
634                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
635                         .with_features(invoice.features().unwrap().clone())
636                         .with_route_hints(invoice.route_hints());
637                 let params = RouteParameters {
638                         payment_params,
639                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
640                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
641                 };
642                 let first_hops = nodes[0].node.list_usable_channels();
643                 let network_graph = node_cfgs[0].network_graph;
644                 let logger = test_utils::TestLogger::new();
645                 let scorer = test_utils::TestScorer::with_penalty(0);
646                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
647                 let route = find_route(
648                         &nodes[0].node.get_our_node_id(), &params, network_graph,
649                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
650                 ).unwrap();
651                 let (payment_event, fwd_idx) = {
652                         let mut payment_hash = PaymentHash([0; 32]);
653                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
654                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
655                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
656                         assert_eq!(added_monitors.len(), 1);
657                         added_monitors.clear();
658
659                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
660                         assert_eq!(events.len(), 1);
661                         let fwd_idx = match events[0] {
662                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
663                                         if node_id == nodes[1].node.get_our_node_id() {
664                                                 1
665                                         } else { 2 }
666                                 },
667                                 _ => panic!("Unexpected event")
668                         };
669                         (SendEvent::from_event(events.remove(0)), fwd_idx)
670                 };
671                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
672                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
673
674                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
675                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
676                 // payments "look real" by taking more time.
677                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
678                 nodes[fwd_idx].node.process_pending_htlc_forwards();
679                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
680                 nodes[fwd_idx].node.process_pending_htlc_forwards();
681
682                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
683                 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
684                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
685                 let events = nodes[0].node.get_and_clear_pending_events();
686                 assert_eq!(events.len(), 2);
687                 match events[0] {
688                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
689                                 assert_eq!(payment_preimage, *ev_preimage);
690                                 assert_eq!(payment_hash, *ev_hash);
691                                 assert_eq!(fee_paid_msat, &Some(0));
692                         },
693                         _ => panic!("Unexpected event")
694                 }
695                 match events[1] {
696                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
697                                 assert_eq!(hash, Some(payment_hash));
698                         },
699                         _ => panic!("Unexpected event")
700                 }
701         }
702 }