Parameterize NetworkGraph with Logger
[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::{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, RoutingFees};
19 use lightning::routing::router::{Route, RouteHint, RouteHintHop, RouteParameters, find_route};
20 use lightning::routing::scoring::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_usable_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 /// * Filter out channels with a lower inbound capacity than `min_inbound_capacity_msat`, if any
381 /// channel with a higher or equal inbound capacity than `min_inbound_capacity_msat` exists
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
389         for channel in channels.iter() {
390                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
391                         continue;
392                 }
393
394                 if channel.is_public {
395                         // If any public channel exists, return no hints and let the sender
396                         // look at the public channels instead.
397                         return vec![]
398                 }
399
400                 if channel.inbound_capacity_msat >= min_inbound_capacity {
401                         min_capacity_channel_exists = true;
402                 };
403                 match filtered_channels.entry(channel.counterparty.node_id) {
404                         hash_map::Entry::Occupied(mut entry) => {
405                                 let current_max_capacity = entry.get().inbound_capacity_msat;
406                                 if channel.inbound_capacity_msat < current_max_capacity {
407                                         continue;
408                                 }
409                                 entry.insert(channel);
410                         }
411                         hash_map::Entry::Vacant(entry) => {
412                                 entry.insert(channel);
413                         }
414                 }
415         }
416
417         let route_hint_from_channel = |channel: &ChannelDetails| {
418                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
419                 RouteHint(vec![RouteHintHop {
420                         src_node_id: channel.counterparty.node_id,
421                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
422                         fees: RoutingFees {
423                                 base_msat: forwarding_info.fee_base_msat,
424                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
425                         },
426                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
427                         htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
428                         htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
429         };
430         // If all channels are private, return the route hint for the highest inbound capacity channel
431         // per counterparty node. If channels with an higher inbound capacity than the
432         // min_inbound_capacity exists, filter out the channels with a lower capacity than that.
433         filtered_channels.into_iter()
434                 .filter(|(_counterparty_id, channel)| {
435                         min_capacity_channel_exists && channel.inbound_capacity_msat >= min_inbound_capacity ||
436                         !min_capacity_channel_exists
437                 })
438                 .map(|(_counterparty_id, channel)| route_hint_from_channel(&channel))
439                 .collect::<Vec<RouteHint>>()
440 }
441
442 /// A [`Router`] implemented using [`find_route`].
443 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref> where L::Target: Logger {
444         network_graph: G,
445         logger: L,
446         random_seed_bytes: Mutex<[u8; 32]>,
447 }
448
449 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> DefaultRouter<G, L> where L::Target: Logger {
450         /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
451         /// `random_seed_bytes`.
452         pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32]) -> Self {
453                 let random_seed_bytes = Mutex::new(random_seed_bytes);
454                 Self { network_graph, logger, random_seed_bytes }
455         }
456 }
457
458 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
459 where L::Target: Logger {
460         fn find_route(
461                 &self, payer: &PublicKey, params: &RouteParameters, _payment_hash: &PaymentHash,
462                 first_hops: Option<&[&ChannelDetails]>, scorer: &S
463         ) -> Result<Route, LightningError> {
464                 let network_graph = self.network_graph.read_only();
465                 let random_seed_bytes = {
466                         let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
467                         *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
468                         *locked_random_seed_bytes
469                 };
470                 find_route(payer, params, &network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
471         }
472 }
473
474 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
475 where
476         M::Target: chain::Watch<Signer>,
477         T::Target: BroadcasterInterface,
478         K::Target: KeysInterface<Signer = Signer>,
479         F::Target: FeeEstimator,
480         L::Target: Logger,
481 {
482         fn node_id(&self) -> PublicKey {
483                 self.get_our_node_id()
484         }
485
486         fn first_hops(&self) -> Vec<ChannelDetails> {
487                 self.list_usable_channels()
488         }
489
490         fn send_payment(
491                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
492         ) -> Result<PaymentId, PaymentSendFailure> {
493                 self.send_payment(route, payment_hash, payment_secret)
494         }
495
496         fn send_spontaneous_payment(
497                 &self, route: &Route, payment_preimage: PaymentPreimage,
498         ) -> Result<PaymentId, PaymentSendFailure> {
499                 self.send_spontaneous_payment(route, Some(payment_preimage))
500                         .map(|(_, payment_id)| payment_id)
501         }
502
503         fn retry_payment(
504                 &self, route: &Route, payment_id: PaymentId
505         ) -> Result<(), PaymentSendFailure> {
506                 self.retry_payment(route, payment_id)
507         }
508
509         fn abandon_payment(&self, payment_id: PaymentId) {
510                 self.abandon_payment(payment_id)
511         }
512 }
513
514 #[cfg(test)]
515 mod test {
516         use core::time::Duration;
517         use {Currency, Description, InvoiceDescription};
518         use bitcoin_hashes::Hash;
519         use bitcoin_hashes::sha256::Hash as Sha256;
520         use lightning::chain::keysinterface::PhantomKeysManager;
521         use lightning::ln::{PaymentPreimage, PaymentHash};
522         use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY};
523         use lightning::ln::functional_test_utils::*;
524         use lightning::ln::features::InitFeatures;
525         use lightning::ln::msgs::ChannelMessageHandler;
526         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
527         use lightning::util::enforcing_trait_impls::EnforcingSigner;
528         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
529         use lightning::util::test_utils;
530         use lightning::util::config::UserConfig;
531         use lightning::chain::keysinterface::KeysInterface;
532         use utils::create_invoice_from_channelmanager_and_duration_since_epoch;
533         use std::collections::HashSet;
534
535         #[test]
536         fn test_from_channelmanager() {
537                 let chanmon_cfgs = create_chanmon_cfgs(2);
538                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
539                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
540                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
541                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
542                 let non_default_invoice_expiry_secs = 4200;
543                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
544                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000), "test".to_string(),
545                         Duration::from_secs(1234567), non_default_invoice_expiry_secs).unwrap();
546                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
547                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
548                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
549                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
550
551                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
552                 // available.
553                 let chan = &nodes[1].node.list_usable_channels()[0];
554                 assert_eq!(invoice.route_hints().len(), 1);
555                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
556                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
557
558                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
559                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
560
561                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
562                         .with_features(invoice.features().unwrap().clone())
563                         .with_route_hints(invoice.route_hints());
564                 let route_params = RouteParameters {
565                         payment_params,
566                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
567                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
568                 };
569                 let first_hops = nodes[0].node.list_usable_channels();
570                 let network_graph = &node_cfgs[0].network_graph;
571                 let logger = test_utils::TestLogger::new();
572                 let scorer = test_utils::TestScorer::with_penalty(0);
573                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
574                 let route = find_route(
575                         &nodes[0].node.get_our_node_id(), &route_params, &network_graph.read_only(),
576                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
577                 ).unwrap();
578
579                 let payment_event = {
580                         let mut payment_hash = PaymentHash([0; 32]);
581                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
582                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
583                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
584                         assert_eq!(added_monitors.len(), 1);
585                         added_monitors.clear();
586
587                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
588                         assert_eq!(events.len(), 1);
589                         SendEvent::from_event(events.remove(0))
590
591                 };
592                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
593                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
594                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
595                 assert_eq!(added_monitors.len(), 1);
596                 added_monitors.clear();
597                 let events = nodes[1].node.get_and_clear_pending_msg_events();
598                 assert_eq!(events.len(), 2);
599         }
600
601         #[test]
602         fn test_create_invoice_with_description_hash() {
603                 let chanmon_cfgs = create_chanmon_cfgs(2);
604                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
605                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
606                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
607                 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
608                 let invoice = ::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
609                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000),
610                         description_hash, Duration::from_secs(1234567), 3600
611                 ).unwrap();
612                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
613                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
614                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
615         }
616
617         #[test]
618         fn test_hints_includes_single_channels_to_nodes() {
619                 let chanmon_cfgs = create_chanmon_cfgs(3);
620                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
621                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
622                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
623
624                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
625                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
626
627                 let mut scid_aliases = HashSet::new();
628                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
629                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
630
631                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
632         }
633
634         #[test]
635         fn test_hints_has_only_highest_inbound_capacity_channel() {
636                 let chanmon_cfgs = create_chanmon_cfgs(2);
637                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
638                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
639                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
640                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
641                 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());
642                 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());
643
644                 let mut scid_aliases = HashSet::new();
645                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
646
647                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
648         }
649
650         #[test]
651         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
652                 let chanmon_cfgs = create_chanmon_cfgs(3);
653                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
654                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
655                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
656                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
657
658                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
659                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
660                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
661                 let mut private_chan_cfg = UserConfig::default();
662                 private_chan_cfg.channel_options.announced_channel = false;
663                 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();
664                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
665                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &open_channel);
666                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
667                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
668
669                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
670
671                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
672                 confirm_transaction_at(&nodes[2], &tx, conf_height);
673                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
674                 confirm_transaction_at(&nodes[0], &tx, conf_height);
675                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
676                 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
677                 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()));
678                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
679                 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
680                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
681
682                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
683                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
684                 // Therefore only `chan_1_0` should be included in the hints.
685                 let mut scid_aliases = HashSet::new();
686                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
687                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
688         }
689
690         #[test]
691         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
692                 let chanmon_cfgs = create_chanmon_cfgs(3);
693                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
694                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
695                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
696                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
697
698                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
699                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
700                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
701
702                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
703                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
704                 // public channel between `nodes[2]` and `nodes[0]`
705                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
706         }
707
708         #[test]
709         fn test_only_public_channels_includes_no_channels_in_hints() {
710                 let chanmon_cfgs = create_chanmon_cfgs(3);
711                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
712                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
713                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
714                 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
715                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
716                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
717
718                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
719                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
720                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
721
722                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
723                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
724         }
725
726         #[test]
727         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
728                 let chanmon_cfgs = create_chanmon_cfgs(3);
729                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
730                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
731                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
732                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
733                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
734
735                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
736                 let mut scid_aliases_99_000_001_msat = HashSet::new();
737                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
738
739                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
740
741                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
742                 let mut scid_aliases_99_000_000_msat = HashSet::new();
743                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
744                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
745
746                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
747
748                 // As the invoice amt is above all channels' inbound capacity, they will still be included
749                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
750                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
751                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
752
753                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
754
755                 // An invoice with no specified amount should include all channels in the route hints.
756                 let mut scid_aliases_no_specified_amount = HashSet::new();
757                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
758                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
759
760                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
761         }
762
763         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
764                 invoice_amt: Option<u64>,
765                 invoice_node: &Node<'a, 'b, 'c>,
766                 mut chan_ids_to_match: HashSet<u64>
767         ) {
768                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
769                         &invoice_node.node, invoice_node.keys_manager, Currency::BitcoinTestnet, invoice_amt, "test".to_string(),
770                         Duration::from_secs(1234567), 3600).unwrap();
771                 let hints = invoice.private_routes();
772
773                 for hint in hints {
774                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
775                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
776                 }
777                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
778         }
779
780         #[test]
781         #[cfg(feature = "std")]
782         fn test_multi_node_receive() {
783                 do_test_multi_node_receive(true);
784                 do_test_multi_node_receive(false);
785         }
786
787         #[cfg(feature = "std")]
788         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
789                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
790                 let seed_1 = [42 as u8; 32];
791                 let seed_2 = [43 as u8; 32];
792                 let cross_node_seed = [44 as u8; 32];
793                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
794                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
795                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
796                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
797                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
798                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
799                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
800                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
801                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
802                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
803                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
804
805                 let payment_amt = 10_000;
806                 let route_hints = vec![
807                         nodes[1].node.get_phantom_route_hints(),
808                         nodes[2].node.get_phantom_route_hints(),
809                 ];
810
811                 let user_payment_preimage = PaymentPreimage([1; 32]);
812                 let payment_hash = if user_generated_pmt_hash {
813                         Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
814                 } else {
815                         None
816                 };
817                 let non_default_invoice_expiry_secs = 4200;
818
819                 let invoice =
820                         ::utils::create_phantom_invoice::<EnforcingSigner, &test_utils::TestKeysInterface>(
821                                 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
822                                 route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet
823                         ).unwrap();
824                 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
825                 let payment_preimage = if user_generated_pmt_hash {
826                         user_payment_preimage
827                 } else {
828                         nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
829                 };
830
831                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
832                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
833                 assert_eq!(invoice.route_hints().len(), 2);
834                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
835                 assert!(!invoice.features().unwrap().supports_basic_mpp());
836
837                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
838                         .with_features(invoice.features().unwrap().clone())
839                         .with_route_hints(invoice.route_hints());
840                 let params = RouteParameters {
841                         payment_params,
842                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
843                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
844                 };
845                 let first_hops = nodes[0].node.list_usable_channels();
846                 let network_graph = &node_cfgs[0].network_graph;
847                 let logger = test_utils::TestLogger::new();
848                 let scorer = test_utils::TestScorer::with_penalty(0);
849                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
850                 let route = find_route(
851                         &nodes[0].node.get_our_node_id(), &params, &network_graph.read_only(),
852                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
853                 ).unwrap();
854                 let (payment_event, fwd_idx) = {
855                         let mut payment_hash = PaymentHash([0; 32]);
856                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
857                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
858                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
859                         assert_eq!(added_monitors.len(), 1);
860                         added_monitors.clear();
861
862                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
863                         assert_eq!(events.len(), 1);
864                         let fwd_idx = match events[0] {
865                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
866                                         if node_id == nodes[1].node.get_our_node_id() {
867                                                 1
868                                         } else { 2 }
869                                 },
870                                 _ => panic!("Unexpected event")
871                         };
872                         (SendEvent::from_event(events.remove(0)), fwd_idx)
873                 };
874                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
875                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
876
877                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
878                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
879                 // payments "look real" by taking more time.
880                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
881                 nodes[fwd_idx].node.process_pending_htlc_forwards();
882                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
883                 nodes[fwd_idx].node.process_pending_htlc_forwards();
884
885                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
886                 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
887                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
888                 let events = nodes[0].node.get_and_clear_pending_events();
889                 assert_eq!(events.len(), 2);
890                 match events[0] {
891                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
892                                 assert_eq!(payment_preimage, *ev_preimage);
893                                 assert_eq!(payment_hash, *ev_hash);
894                                 assert_eq!(fee_paid_msat, &Some(0));
895                         },
896                         _ => panic!("Unexpected event")
897                 }
898                 match events[1] {
899                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
900                                 assert_eq!(hash, Some(payment_hash));
901                         },
902                         _ => panic!("Unexpected event")
903                 }
904         }
905
906         #[test]
907         #[cfg(feature = "std")]
908         fn test_multi_node_hints_has_htlc_min_max_values() {
909                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
910                 let seed_1 = [42 as u8; 32];
911                 let seed_2 = [43 as u8; 32];
912                 let cross_node_seed = [44 as u8; 32];
913                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
914                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
915                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
916                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
917                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
918
919                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
920                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
921
922                 let payment_amt = 20_000;
923                 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
924                 let route_hints = vec![
925                         nodes[1].node.get_phantom_route_hints(),
926                         nodes[2].node.get_phantom_route_hints(),
927                 ];
928
929                 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();
930
931                 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
932                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
933                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
934
935                 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
936                 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
937                 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
938         }
939
940         #[test]
941         #[cfg(feature = "std")]
942         fn create_phantom_invoice_with_description_hash() {
943                 let chanmon_cfgs = create_chanmon_cfgs(3);
944                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
945                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
946                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
947
948                 let payment_amt = 20_000;
949                 let route_hints = vec![
950                         nodes[1].node.get_phantom_route_hints(),
951                         nodes[2].node.get_phantom_route_hints(),
952                 ];
953
954                 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
955                 let non_default_invoice_expiry_secs = 4200;
956                 let invoice = ::utils::create_phantom_invoice_with_description_hash::<
957                         EnforcingSigner, &test_utils::TestKeysInterface,
958                 >(
959                         Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
960                         route_hints, &nodes[1].keys_manager, Currency::BitcoinTestnet
961                 )
962                 .unwrap();
963                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
964                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
965                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
966                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
967         }
968
969         #[test]
970         #[cfg(feature = "std")]
971         fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
972                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
973                 let seed_1 = [42 as u8; 32];
974                 let seed_2 = [43 as u8; 32];
975                 let cross_node_seed = [44 as u8; 32];
976                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
977                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
978                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
979                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
980                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
981
982                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
983                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
984
985                 let mut scid_aliases = HashSet::new();
986                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
987                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
988
989                 match_multi_node_invoice_routes(
990                         Some(10_000),
991                         &nodes[1],
992                         vec![&nodes[1], &nodes[2],],
993                         scid_aliases,
994                         false
995                 );
996         }
997
998         #[test]
999         #[cfg(feature = "std")]
1000         fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1001                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1002                 let seed_1 = [42 as u8; 32];
1003                 let seed_2 = [43 as u8; 32];
1004                 let cross_node_seed = [44 as u8; 32];
1005                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1006                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1007                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1008                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1009                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1010
1011                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1012                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
1013                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005, InitFeatures::known(), InitFeatures::known());
1014
1015                 let mut scid_aliases = HashSet::new();
1016                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1017                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1018                 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1019
1020                 match_multi_node_invoice_routes(
1021                         Some(10_000),
1022                         &nodes[2],
1023                         vec![&nodes[2], &nodes[3],],
1024                         scid_aliases,
1025                         false
1026                 );
1027         }
1028
1029         #[test]
1030         #[cfg(feature = "std")]
1031         fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1032                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1033                 let seed_1 = [42 as u8; 32];
1034                 let seed_2 = [43 as u8; 32];
1035                 let cross_node_seed = [44 as u8; 32];
1036                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1037                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1038                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1039                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1040                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1041
1042                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1043                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
1044
1045                 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1046                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1047                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1048                 let mut private_chan_cfg = UserConfig::default();
1049                 private_chan_cfg.channel_options.announced_channel = false;
1050                 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();
1051                 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1052                 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
1053                 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1054                 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
1055
1056                 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1057
1058                 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1059                 confirm_transaction_at(&nodes[1], &tx, conf_height);
1060                 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1061                 confirm_transaction_at(&nodes[3], &tx, conf_height);
1062                 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1063                 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1064                 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()));
1065                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1066                 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1067                 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1068
1069                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1070                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1071                 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1072                 let mut scid_aliases = HashSet::new();
1073                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1074                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1075
1076                 match_multi_node_invoice_routes(
1077                         Some(10_000),
1078                         &nodes[2],
1079                         vec![&nodes[2], &nodes[3],],
1080                         scid_aliases,
1081                         false
1082                 );
1083         }
1084
1085         #[test]
1086         #[cfg(feature = "std")]
1087         fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1088                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1089                 let seed_1 = [42 as u8; 32];
1090                 let seed_2 = [43 as u8; 32];
1091                 let cross_node_seed = [44 as u8; 32];
1092                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1093                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1094                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1095                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1096                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1097
1098                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1099
1100                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1101                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1102                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1103
1104                 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1105                 // `chan_0_2` as `nodes[2]` only has public channels.
1106                 let mut scid_aliases = HashSet::new();
1107                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1108
1109                 match_multi_node_invoice_routes(
1110                         Some(10_000),
1111                         &nodes[1],
1112                         vec![&nodes[1], &nodes[2],],
1113                         scid_aliases,
1114                         true
1115                 );
1116         }
1117
1118         #[test]
1119         #[cfg(feature = "std")]
1120         fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1121                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1122                 let seed_1 = [42 as u8; 32];
1123                 let seed_2 = [43 as u8; 32];
1124                 let cross_node_seed = [44 as u8; 32];
1125                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1126                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1127                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1128                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1129                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1130
1131                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1132                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1133                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1134                 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1135
1136                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1137
1138                 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1139                 // channels for `nodes[2]` as it contains a mix of public and private channels.
1140                 let mut scid_aliases = HashSet::new();
1141                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1142
1143                 match_multi_node_invoice_routes(
1144                         Some(10_000),
1145                         &nodes[2],
1146                         vec![&nodes[2], &nodes[3],],
1147                         scid_aliases,
1148                         true
1149                 );
1150         }
1151
1152         #[test]
1153         #[cfg(feature = "std")]
1154         fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1155                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1156                 let seed_1 = [42 as u8; 32];
1157                 let seed_2 = [43 as u8; 32];
1158                 let cross_node_seed = [44 as u8; 32];
1159                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1160                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1161                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1162                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1163                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1164
1165                 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1166                 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, InitFeatures::known(), InitFeatures::known());
1167                 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1168                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1169
1170                 let mut scid_aliases = HashSet::new();
1171                 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1172                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1173
1174                 match_multi_node_invoice_routes(
1175                         Some(10_000),
1176                         &nodes[1],
1177                         vec![&nodes[1], &nodes[2],],
1178                         scid_aliases,
1179                         false
1180                 );
1181         }
1182
1183         #[test]
1184         #[cfg(feature = "std")]
1185         fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1186                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1187                 let seed_1 = [42 as u8; 32];
1188                 let seed_2 = [43 as u8; 32];
1189                 let cross_node_seed = [44 as u8; 32];
1190                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1191                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1192                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1193                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1194                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1195
1196                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1197                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1198                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0, InitFeatures::known(), InitFeatures::known());
1199
1200                 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1201                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1202                 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1203                 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1204
1205                 match_multi_node_invoice_routes(
1206                         Some(99_000_001),
1207                         &nodes[2],
1208                         vec![&nodes[2], &nodes[3],],
1209                         scid_aliases_99_000_001_msat,
1210                         false
1211                 );
1212
1213                 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1214                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1215                 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1216                 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1217                 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1218
1219                 match_multi_node_invoice_routes(
1220                         Some(99_000_000),
1221                         &nodes[2],
1222                         vec![&nodes[2], &nodes[3],],
1223                         scid_aliases_99_000_000_msat,
1224                         false
1225                 );
1226
1227                 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1228                 // `nodes[2]` them should be included.
1229                 let mut scid_aliases_300_000_000_msat = HashSet::new();
1230                 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1231                 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1232                 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1233
1234                 match_multi_node_invoice_routes(
1235                         Some(300_000_000),
1236                         &nodes[2],
1237                         vec![&nodes[2], &nodes[3],],
1238                         scid_aliases_300_000_000_msat,
1239                         false
1240                 );
1241
1242                 // Since the no specified amount, all channels should included.
1243                 let mut scid_aliases_no_specified_amount = HashSet::new();
1244                 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1245                 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1246                 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1247
1248                 match_multi_node_invoice_routes(
1249                         None,
1250                         &nodes[2],
1251                         vec![&nodes[2], &nodes[3],],
1252                         scid_aliases_no_specified_amount,
1253                         false
1254                 );
1255         }
1256
1257         #[cfg(feature = "std")]
1258         fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1259                 invoice_amt: Option<u64>,
1260                 invoice_node: &Node<'a, 'b, 'c>,
1261                 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1262                 mut chan_ids_to_match: HashSet<u64>,
1263                 nodes_contains_public_channels: bool
1264         ){
1265                 let phantom_route_hints = network_multi_nodes.iter()
1266                         .map(|node| node.node.get_phantom_route_hints())
1267                         .collect::<Vec<PhantomRouteHints>>();
1268                 let phantom_scids = phantom_route_hints.iter()
1269                         .map(|route_hint| route_hint.phantom_scid)
1270                         .collect::<HashSet<u64>>();
1271
1272                 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();
1273
1274                 let invoice_hints = invoice.private_routes();
1275
1276                 for hint in invoice_hints {
1277                         let hints = &(hint.0).0;
1278                         match hints.len() {
1279                                 1 => {
1280                                         assert!(nodes_contains_public_channels);
1281                                         let phantom_scid = hints[0].short_channel_id;
1282                                         assert!(phantom_scids.contains(&phantom_scid));
1283                                 },
1284                                 2 => {
1285                                         let hint_short_chan_id = hints[0].short_channel_id;
1286                                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1287                                         let phantom_scid = hints[1].short_channel_id;
1288                                         assert!(phantom_scids.contains(&phantom_scid));
1289                                 },
1290                                 _ => panic!("Incorrect hint length generated")
1291                         }
1292                 }
1293                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1294         }
1295 }