1 //! Convenient utilities to create an invoice.
3 use {CreationError, Currency, DEFAULT_EXPIRY_TIME, Invoice, InvoiceBuilder, SignOrCreationError};
4 use payment::{Payer, Router};
6 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
8 use bitcoin_hashes::{Hash, sha256};
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;
25 use core::time::Duration;
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.
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
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.
46 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
47 /// in excess of the current time.
49 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
50 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
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,
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.
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
83 /// `description_hash` is a SHA-256 hash of the description text
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.
89 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
90 /// in excess of the current time.
92 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
93 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
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
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,
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
118 use std::time::{SystemTime, UNIX_EPOCH};
120 if phantom_route_hints.len() == 0 {
121 return Err(SignOrCreationError::CreationError(
122 CreationError::MissingRouteHints,
125 let invoice = match description {
126 InvoiceDescription::Direct(description) => {
127 InvoiceBuilder::new(network).description(description.0.clone())
129 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
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(
139 invoice_expiry_delta_secs,
141 .duration_since(UNIX_EPOCH)
142 .expect("Time must be > 1970")
145 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
146 (payment_hash, payment_secret)
151 invoice_expiry_delta_secs,
154 .duration_since(UNIX_EPOCH)
155 .expect("Time must be > 1970")
158 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
161 let mut invoice = invoice
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);
170 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
171 let mut route_hints = filter_channels(channels, amt_msat);
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![]))
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,
186 proportional_millionths: 0,
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());
195 let raw_invoice = match invoice.build_raw() {
197 Err(e) => return Err(SignOrCreationError::CreationError(e))
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))
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<()>>
220 M::Target: chain::Watch<Signer>,
221 T::Target: BroadcasterInterface,
222 K::Target: KeysInterface<Signer = Signer>,
223 F::Target: FeeEstimator,
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
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<()>>
246 M::Target: chain::Watch<Signer>,
247 T::Target: BroadcasterInterface,
248 K::Target: KeysInterface<Signer = Signer>,
249 F::Target: FeeEstimator,
252 use std::time::SystemTime;
254 let duration = SystemTime::now()
255 .duration_since(SystemTime::UNIX_EPOCH)
256 .expect("for the foreseeable future this shouldn't happen");
258 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
259 channelmanager, keys_manager, network, amt_msat, description_hash, duration,
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<()>>
271 M::Target: chain::Watch<Signer>,
272 T::Target: BroadcasterInterface,
273 K::Target: KeysInterface<Signer = Signer>,
274 F::Target: FeeEstimator,
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,
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<()>>
292 M::Target: chain::Watch<Signer>,
293 T::Target: BroadcasterInterface,
294 K::Target: KeysInterface<Signer = Signer>,
295 F::Target: FeeEstimator,
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)?,
303 duration_since_epoch,
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<()>>
312 M::Target: chain::Watch<Signer>,
313 T::Target: BroadcasterInterface,
314 K::Target: KeysInterface<Signer = Signer>,
315 F::Target: FeeEstimator,
318 let route_hints = filter_channels(channelmanager.list_usable_channels(), amt_msat);
320 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
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();
327 let invoice = match description {
328 InvoiceDescription::Direct(description) => {
329 InvoiceBuilder::new(network).description(description.0.clone())
331 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
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)
340 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into());
341 if let Some(amt) = amt_msat {
342 invoice = invoice.amount_milli_satoshis(amt);
344 for hint in route_hints {
345 invoice = invoice.private_route(hint);
348 let raw_invoice = match invoice.build_raw() {
350 Err(e) => return Err(SignOrCreationError::CreationError(e))
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))
362 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
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;
377 for channel in channels.iter() {
378 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
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.
388 if channel.inbound_capacity_msat >= min_inbound_capacity {
389 min_capacity_channel_exists = true;
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 {
397 entry.insert(channel);
399 hash_map::Entry::Vacant(entry) => {
400 entry.insert(channel);
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(),
411 base_msat: forwarding_info.fee_base_msat,
412 proportional_millionths: forwarding_info.fee_proportional_millionths,
414 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
415 htlc_minimum_msat: None,
416 htlc_maximum_msat: None,}])
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
426 .map(|(_counterparty_id, channel)| route_hint_from_channel(&channel))
427 .collect::<Vec<RouteHint>>()
430 /// A [`Router`] implemented using [`find_route`].
431 pub struct DefaultRouter<G: Deref<Target = NetworkGraph>, L: Deref> where L::Target: Logger {
434 random_seed_bytes: Mutex<[u8; 32]>,
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 }
446 impl<G: Deref<Target = NetworkGraph>, L: Deref, S: Score> Router<S> for DefaultRouter<G, L>
447 where L::Target: Logger {
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
457 find_route(payer, params, &*self.network_graph, first_hops, &*self.logger, scorer, &random_seed_bytes)
461 impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<Signer, M, T, K, F, L>
463 M::Target: chain::Watch<Signer>,
464 T::Target: BroadcasterInterface,
465 K::Target: KeysInterface<Signer = Signer>,
466 F::Target: FeeEstimator,
469 fn node_id(&self) -> PublicKey {
470 self.get_our_node_id()
473 fn first_hops(&self) -> Vec<ChannelDetails> {
474 self.list_usable_channels()
478 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>
479 ) -> Result<PaymentId, PaymentSendFailure> {
480 self.send_payment(route, payment_hash, payment_secret)
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)
491 &self, route: &Route, payment_id: PaymentId
492 ) -> Result<(), PaymentSendFailure> {
493 self.retry_payment(route, payment_id)
496 fn abandon_payment(&self, payment_id: PaymentId) {
497 self.abandon_payment(payment_id)
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;
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())));
536 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
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());
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 {
548 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
549 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
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
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();
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))
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);
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),
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()))));
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);
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());
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());
613 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
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());
626 let mut scid_aliases = HashSet::new();
627 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
629 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
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());
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);
651 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
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());
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);
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());
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);
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());
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);
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);
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());
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());
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());
721 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
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());
728 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
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());
735 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
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());
742 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
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>
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();
756 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
757 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
759 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
763 #[cfg(feature = "std")]
764 fn test_multi_node_receive() {
765 do_test_multi_node_receive(true);
766 do_test_multi_node_receive(false);
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);
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(),
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()))
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
805 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
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());
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 {
818 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
819 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
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(), ¶ms, network_graph,
828 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
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();
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() {
846 _ => panic!("Unexpected event")
848 (SendEvent::from_event(events.remove(0)), fwd_idx)
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);
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();
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);
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));
872 _ => panic!("Unexpected event")
875 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
876 assert_eq!(hash, Some(payment_hash));
878 _ => panic!("Unexpected event")
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);
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(),
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();
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()))));
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);
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());
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());
924 match_multi_node_invoice_routes(
927 vec![&nodes[1], &nodes[2],],
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);
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());
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());
955 match_multi_node_invoice_routes(
958 vec![&nodes[2], &nodes[3],],
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);
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());
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);
991 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
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());
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());
1011 match_multi_node_invoice_routes(
1014 vec![&nodes[2], &nodes[3],],
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);
1033 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
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);
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());
1044 match_multi_node_invoice_routes(
1047 vec![&nodes[1], &nodes[2],],
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);
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());
1071 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, InitFeatures::known(), InitFeatures::known());
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());
1078 match_multi_node_invoice_routes(
1081 vec![&nodes[2], &nodes[3],],
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);
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());
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());
1109 match_multi_node_invoice_routes(
1112 vec![&nodes[1], &nodes[2],],
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);
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());
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());
1140 match_multi_node_invoice_routes(
1143 vec![&nodes[2], &nodes[3],],
1144 scid_aliases_99_000_001_msat,
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());
1154 match_multi_node_invoice_routes(
1157 vec![&nodes[2], &nodes[3],],
1158 scid_aliases_99_000_000_msat,
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());
1169 match_multi_node_invoice_routes(
1172 vec![&nodes[2], &nodes[3],],
1173 scid_aliases_300_000_000_msat,
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());
1183 match_multi_node_invoice_routes(
1186 vec![&nodes[2], &nodes[3],],
1187 scid_aliases_no_specified_amount,
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
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>>();
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();
1209 let invoice_hints = invoice.private_routes();
1211 for hint in invoice_hints {
1212 let hints = &(hint.0).0;
1215 assert!(nodes_contains_public_channels);
1216 let phantom_scid = hints[0].short_channel_id;
1217 assert!(phantom_scids.contains(&phantom_scid));
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));
1225 _ => panic!("Incorrect hint length generated")
1228 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);