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