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