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