Merge pull request #1417 from johncantrell97/generic-persist
[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: None,
416                         htlc_maximum_msat: None,}])
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                 assert_eq!(invoice.route_hints().len(), 1);
539                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
540                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id,
541                         nodes[1].node.list_usable_channels()[0].inbound_scid_alias.unwrap());
542
543                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
544                         .with_features(invoice.features().unwrap().clone())
545                         .with_route_hints(invoice.route_hints());
546                 let route_params = RouteParameters {
547                         payment_params,
548                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
549                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
550                 };
551                 let first_hops = nodes[0].node.list_usable_channels();
552                 let network_graph = node_cfgs[0].network_graph;
553                 let logger = test_utils::TestLogger::new();
554                 let scorer = test_utils::TestScorer::with_penalty(0);
555                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
556                 let route = find_route(
557                         &nodes[0].node.get_our_node_id(), &route_params, network_graph,
558                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
559                 ).unwrap();
560
561                 let payment_event = {
562                         let mut payment_hash = PaymentHash([0; 32]);
563                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
564                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
565                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
566                         assert_eq!(added_monitors.len(), 1);
567                         added_monitors.clear();
568
569                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
570                         assert_eq!(events.len(), 1);
571                         SendEvent::from_event(events.remove(0))
572
573                 };
574                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
575                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
576                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
577                 assert_eq!(added_monitors.len(), 1);
578                 added_monitors.clear();
579                 let events = nodes[1].node.get_and_clear_pending_msg_events();
580                 assert_eq!(events.len(), 2);
581         }
582
583         #[test]
584         fn test_create_invoice_with_description_hash() {
585                 let chanmon_cfgs = create_chanmon_cfgs(2);
586                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
587                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
588                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
589                 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
590                 let invoice = ::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
591                         &nodes[1].node, nodes[1].keys_manager, Currency::BitcoinTestnet, Some(10_000),
592                         description_hash, Duration::from_secs(1234567),
593                 ).unwrap();
594                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
595                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
596                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
597         }
598
599         #[test]
600         fn test_hints_includes_single_channels_to_nodes() {
601                 let chanmon_cfgs = create_chanmon_cfgs(3);
602                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
603                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
604                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
605
606                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
607                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
608
609                 let mut scid_aliases = HashSet::new();
610                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
611                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
612
613                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
614         }
615
616         #[test]
617         fn test_hints_has_only_highest_inbound_capacity_channel() {
618                 let chanmon_cfgs = create_chanmon_cfgs(2);
619                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
620                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
621                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
622                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
623                 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());
624                 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());
625
626                 let mut scid_aliases = HashSet::new();
627                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
628
629                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
630         }
631
632         #[test]
633         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
634                 let chanmon_cfgs = create_chanmon_cfgs(3);
635                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
636                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
637                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
638                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
639
640                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
641                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
642                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
643                 let mut private_chan_cfg = UserConfig::default();
644                 private_chan_cfg.channel_options.announced_channel = false;
645                 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();
646                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
647                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &open_channel);
648                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
649                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
650
651                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
652
653                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
654                 confirm_transaction_at(&nodes[2], &tx, conf_height);
655                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
656                 confirm_transaction_at(&nodes[0], &tx, conf_height);
657                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
658                 let as_funding_locked = get_event_msg!(nodes[2], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id());
659                 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()));
660                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
661                 nodes[0].node.handle_funding_locked(&nodes[2].node.get_our_node_id(), &as_funding_locked);
662                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
663
664                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
665                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
666                 // Therefore only `chan_1_0` should be included in the hints.
667                 let mut scid_aliases = HashSet::new();
668                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
669                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
670         }
671
672         #[test]
673         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
674                 let chanmon_cfgs = create_chanmon_cfgs(3);
675                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
676                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
677                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
678                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
679
680                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
681                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
682                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
683
684                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
685                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
686                 // public channel between `nodes[2]` and `nodes[0]`
687                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
688         }
689
690         #[test]
691         fn test_only_public_channels_includes_no_channels_in_hints() {
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_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
697                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
698                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
699
700                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
701                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
702                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
703
704                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
705                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
706         }
707
708         #[test]
709         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
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_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, InitFeatures::known(), InitFeatures::known());
715                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
716
717                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
718                 let mut scid_aliases_99_000_001_msat = HashSet::new();
719                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
720
721                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
722
723                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
724                 let mut scid_aliases_99_000_000_msat = HashSet::new();
725                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
726                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
727
728                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
729
730                 // As the invoice amt is above all channels' inbound capacity, they will still be included
731                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
732                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
733                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
734
735                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
736
737                 // An invoice with no specified amount should include all channels in the route hints.
738                 let mut scid_aliases_no_specified_amount = HashSet::new();
739                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
740                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
741
742                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
743         }
744
745         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
746                 invoice_amt: Option<u64>,
747                 invoice_node: &Node<'a, 'b, 'c>,
748                 mut chan_ids_to_match: HashSet<u64>
749         ) {
750                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
751                         &invoice_node.node, invoice_node.keys_manager, Currency::BitcoinTestnet, invoice_amt, "test".to_string(),
752                         Duration::from_secs(1234567)).unwrap();
753                 let hints = invoice.private_routes();
754
755                 for hint in hints {
756                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
757                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
758                 }
759                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
760         }
761
762         #[test]
763         #[cfg(feature = "std")]
764         fn test_multi_node_receive() {
765                 do_test_multi_node_receive(true);
766                 do_test_multi_node_receive(false);
767         }
768
769         #[cfg(feature = "std")]
770         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
771                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
772                 let seed_1 = [42 as u8; 32];
773                 let seed_2 = [43 as u8; 32];
774                 let cross_node_seed = [44 as u8; 32];
775                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
776                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
777                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
778                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
779                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
780                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
781                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
782                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
783                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
784                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
785                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
786
787                 let payment_amt = 10_000;
788                 let route_hints = vec![
789                         nodes[1].node.get_phantom_route_hints(),
790                         nodes[2].node.get_phantom_route_hints(),
791                 ];
792
793                 let user_payment_preimage = PaymentPreimage([1; 32]);
794                 let payment_hash = if user_generated_pmt_hash {
795                         Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
796                 } else {
797                         None
798                 };
799
800                 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();
801                 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
802                 let payment_preimage = if user_generated_pmt_hash {
803                         user_payment_preimage
804                 } else {
805                         nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
806                 };
807
808                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
809                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
810                 assert_eq!(invoice.route_hints().len(), 2);
811                 assert!(!invoice.features().unwrap().supports_basic_mpp());
812
813                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
814                         .with_features(invoice.features().unwrap().clone())
815                         .with_route_hints(invoice.route_hints());
816                 let params = RouteParameters {
817                         payment_params,
818                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
819                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
820                 };
821                 let first_hops = nodes[0].node.list_usable_channels();
822                 let network_graph = node_cfgs[0].network_graph;
823                 let logger = test_utils::TestLogger::new();
824                 let scorer = test_utils::TestScorer::with_penalty(0);
825                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
826                 let route = find_route(
827                         &nodes[0].node.get_our_node_id(), &params, network_graph,
828                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
829                 ).unwrap();
830                 let (payment_event, fwd_idx) = {
831                         let mut payment_hash = PaymentHash([0; 32]);
832                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
833                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone())).unwrap();
834                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
835                         assert_eq!(added_monitors.len(), 1);
836                         added_monitors.clear();
837
838                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
839                         assert_eq!(events.len(), 1);
840                         let fwd_idx = match events[0] {
841                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
842                                         if node_id == nodes[1].node.get_our_node_id() {
843                                                 1
844                                         } else { 2 }
845                                 },
846                                 _ => panic!("Unexpected event")
847                         };
848                         (SendEvent::from_event(events.remove(0)), fwd_idx)
849                 };
850                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
851                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
852
853                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
854                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
855                 // payments "look real" by taking more time.
856                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
857                 nodes[fwd_idx].node.process_pending_htlc_forwards();
858                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
859                 nodes[fwd_idx].node.process_pending_htlc_forwards();
860
861                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
862                 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
863                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
864                 let events = nodes[0].node.get_and_clear_pending_events();
865                 assert_eq!(events.len(), 2);
866                 match events[0] {
867                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
868                                 assert_eq!(payment_preimage, *ev_preimage);
869                                 assert_eq!(payment_hash, *ev_hash);
870                                 assert_eq!(fee_paid_msat, &Some(0));
871                         },
872                         _ => panic!("Unexpected event")
873                 }
874                 match events[1] {
875                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
876                                 assert_eq!(hash, Some(payment_hash));
877                         },
878                         _ => panic!("Unexpected event")
879                 }
880         }
881
882         #[test]
883         #[cfg(feature = "std")]
884         fn create_phantom_invoice_with_description_hash() {
885                 let chanmon_cfgs = create_chanmon_cfgs(3);
886                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
887                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
888                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
889
890                 let payment_amt = 20_000;
891                 let route_hints = vec![
892                         nodes[1].node.get_phantom_route_hints(),
893                         nodes[2].node.get_phantom_route_hints(),
894                 ];
895
896                 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
897                 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();
898
899                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
900                 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
901                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
902         }
903
904         #[test]
905         #[cfg(feature = "std")]
906         fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
907                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
908                 let seed_1 = [42 as u8; 32];
909                 let seed_2 = [43 as u8; 32];
910                 let cross_node_seed = [44 as u8; 32];
911                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
912                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
913                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
914                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
915                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
916
917                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
918                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
919
920                 let mut scid_aliases = HashSet::new();
921                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
922                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
923
924                 match_multi_node_invoice_routes(
925                         Some(10_000),
926                         &nodes[1],
927                         vec![&nodes[1], &nodes[2],],
928                         scid_aliases,
929                         false
930                 );
931         }
932
933         #[test]
934         #[cfg(feature = "std")]
935         fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
936                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
937                 let seed_1 = [42 as u8; 32];
938                 let seed_2 = [43 as u8; 32];
939                 let cross_node_seed = [44 as u8; 32];
940                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
941                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
942                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
943                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
944                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
945
946                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
947                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
948                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005, InitFeatures::known(), InitFeatures::known());
949
950                 let mut scid_aliases = HashSet::new();
951                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
952                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
953                 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
954
955                 match_multi_node_invoice_routes(
956                         Some(10_000),
957                         &nodes[2],
958                         vec![&nodes[2], &nodes[3],],
959                         scid_aliases,
960                         false
961                 );
962         }
963
964         #[test]
965         #[cfg(feature = "std")]
966         fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
967                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
968                 let seed_1 = [42 as u8; 32];
969                 let seed_2 = [43 as u8; 32];
970                 let cross_node_seed = [44 as u8; 32];
971                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
972                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
973                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
974                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
975                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
976
977                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
978                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, InitFeatures::known(), InitFeatures::known());
979
980                 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
981                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
982                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
983                 let mut private_chan_cfg = UserConfig::default();
984                 private_chan_cfg.channel_options.announced_channel = false;
985                 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();
986                 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
987                 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
988                 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
989                 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
990
991                 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
992
993                 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
994                 confirm_transaction_at(&nodes[1], &tx, conf_height);
995                 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
996                 confirm_transaction_at(&nodes[3], &tx, conf_height);
997                 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
998                 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[3].node.get_our_node_id());
999                 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()));
1000                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1001                 nodes[3].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
1002                 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1003
1004                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1005                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1006                 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1007                 let mut scid_aliases = HashSet::new();
1008                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1009                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1010
1011                 match_multi_node_invoice_routes(
1012                         Some(10_000),
1013                         &nodes[2],
1014                         vec![&nodes[2], &nodes[3],],
1015                         scid_aliases,
1016                         false
1017                 );
1018         }
1019
1020         #[test]
1021         #[cfg(feature = "std")]
1022         fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1023                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1024                 let seed_1 = [42 as u8; 32];
1025                 let seed_2 = [43 as u8; 32];
1026                 let cross_node_seed = [44 as u8; 32];
1027                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1028                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1029                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1030                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1031                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1032
1033                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1034
1035                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1036                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1037                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1038
1039                 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1040                 // `chan_0_2` as `nodes[2]` only has public channels.
1041                 let mut scid_aliases = HashSet::new();
1042                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1043
1044                 match_multi_node_invoice_routes(
1045                         Some(10_000),
1046                         &nodes[1],
1047                         vec![&nodes[1], &nodes[2],],
1048                         scid_aliases,
1049                         true
1050                 );
1051         }
1052
1053         #[test]
1054         #[cfg(feature = "std")]
1055         fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1056                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1057                 let seed_1 = [42 as u8; 32];
1058                 let seed_2 = [43 as u8; 32];
1059                 let cross_node_seed = [44 as u8; 32];
1060                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1061                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1062                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1063                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1064                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1065
1066                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1067                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1068                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1069                 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1070
1071                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1072
1073                 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1074                 // channels for `nodes[2]` as it contains a mix of public and private channels.
1075                 let mut scid_aliases = HashSet::new();
1076                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1077
1078                 match_multi_node_invoice_routes(
1079                         Some(10_000),
1080                         &nodes[2],
1081                         vec![&nodes[2], &nodes[3],],
1082                         scid_aliases,
1083                         true
1084                 );
1085         }
1086
1087         #[test]
1088         #[cfg(feature = "std")]
1089         fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1090                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1091                 let seed_1 = [42 as u8; 32];
1092                 let seed_2 = [43 as u8; 32];
1093                 let cross_node_seed = [44 as u8; 32];
1094                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1095                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1096                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1097                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1098                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1099
1100                 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1101                 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());
1102                 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());
1103                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
1104
1105                 let mut scid_aliases = HashSet::new();
1106                 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1107                 scid_aliases.insert(chan_0_2.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                         false
1115                 );
1116         }
1117
1118         #[test]
1119         #[cfg(feature = "std")]
1120         fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
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_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0, InitFeatures::known(), InitFeatures::known());
1132                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0, InitFeatures::known(), InitFeatures::known());
1133                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0, InitFeatures::known(), InitFeatures::known());
1134
1135                 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1136                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1137                 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1138                 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1139
1140                 match_multi_node_invoice_routes(
1141                         Some(99_000_001),
1142                         &nodes[2],
1143                         vec![&nodes[2], &nodes[3],],
1144                         scid_aliases_99_000_001_msat,
1145                         false
1146                 );
1147
1148                 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1149                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1150                 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1151                 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1152                 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1153
1154                 match_multi_node_invoice_routes(
1155                         Some(99_000_000),
1156                         &nodes[2],
1157                         vec![&nodes[2], &nodes[3],],
1158                         scid_aliases_99_000_000_msat,
1159                         false
1160                 );
1161
1162                 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1163                 // `nodes[2]` them should be included.
1164                 let mut scid_aliases_300_000_000_msat = HashSet::new();
1165                 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1166                 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1167                 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1168
1169                 match_multi_node_invoice_routes(
1170                         Some(300_000_000),
1171                         &nodes[2],
1172                         vec![&nodes[2], &nodes[3],],
1173                         scid_aliases_300_000_000_msat,
1174                         false
1175                 );
1176
1177                 // Since the no specified amount, all channels should included.
1178                 let mut scid_aliases_no_specified_amount = HashSet::new();
1179                 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1180                 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1181                 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1182
1183                 match_multi_node_invoice_routes(
1184                         None,
1185                         &nodes[2],
1186                         vec![&nodes[2], &nodes[3],],
1187                         scid_aliases_no_specified_amount,
1188                         false
1189                 );
1190         }
1191
1192         #[cfg(feature = "std")]
1193         fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1194                 invoice_amt: Option<u64>,
1195                 invoice_node: &Node<'a, 'b, 'c>,
1196                 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1197                 mut chan_ids_to_match: HashSet<u64>,
1198                 nodes_contains_public_channels: bool
1199         ){
1200                 let phantom_route_hints = network_multi_nodes.iter()
1201                         .map(|node| node.node.get_phantom_route_hints())
1202                         .collect::<Vec<PhantomRouteHints>>();
1203                 let phantom_scids = phantom_route_hints.iter()
1204                         .map(|route_hint| route_hint.phantom_scid)
1205                         .collect::<HashSet<u64>>();
1206
1207                 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();
1208
1209                 let invoice_hints = invoice.private_routes();
1210
1211                 for hint in invoice_hints {
1212                         let hints = &(hint.0).0;
1213                         match hints.len() {
1214                                 1 => {
1215                                         assert!(nodes_contains_public_channels);
1216                                         let phantom_scid = hints[0].short_channel_id;
1217                                         assert!(phantom_scids.contains(&phantom_scid));
1218                                 },
1219                                 2 => {
1220                                         let hint_short_chan_id = hints[0].short_channel_id;
1221                                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1222                                         let phantom_scid = hints[1].short_channel_id;
1223                                         assert!(phantom_scids.contains(&phantom_scid));
1224                                 },
1225                                 _ => panic!("Incorrect hint length generated")
1226                         }
1227                 }
1228                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1229         }
1230 }