1 //! Convenient utilities to create an invoice.
3 use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
4 use crate::payment::Payer;
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};
12 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
13 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY};
14 #[cfg(feature = "std")]
15 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
16 use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
17 use lightning::ln::msgs::LightningError;
18 use lightning::routing::gossip::{NetworkGraph, RoutingFees};
19 use lightning::routing::router::{InFlightHtlcs, Route, RouteHint, RouteHintHop, RouteParameters, find_route, RouteHop, Router, ScorerAccountingForInFlightHtlcs};
20 use lightning::routing::scoring::{LockableScore, Score};
21 use lightning::util::logger::Logger;
22 use secp256k1::PublicKey;
24 use core::time::Duration;
25 use crate::sync::Mutex;
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.
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
41 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
42 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
43 /// If `None` is provided for `payment_hash`, then one will be created.
45 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
46 /// in excess of the current time.
48 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
49 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
52 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
53 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
54 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
55 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
56 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
57 pub fn create_phantom_invoice<K: Deref, L: Deref>(
58 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
59 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K,
60 logger: L, network: Currency,
61 ) -> Result<Invoice, SignOrCreationError<()>>
63 K::Target: KeysInterface,
66 let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
67 let description = InvoiceDescription::Direct(&description,);
68 _create_phantom_invoice::<K, L>(
69 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
70 keys_manager, logger, network,
74 #[cfg(feature = "std")]
75 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
76 /// See [`PhantomKeysManager`] for more information on phantom node payments.
78 /// `phantom_route_hints` parameter:
79 /// * Contains channel info for all nodes participating in the phantom invoice
80 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
81 /// participating node
82 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
83 /// updated when a channel becomes disabled or closes
84 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
85 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
88 /// `description_hash` is a SHA-256 hash of the description text
90 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
91 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
92 /// If `None` is provided for `payment_hash`, then one will be created.
94 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
95 /// in excess of the current time.
97 /// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom
98 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
101 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
102 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
103 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
104 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
105 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
106 pub fn create_phantom_invoice_with_description_hash<K: Deref, L: Deref>(
107 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
108 description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K,
109 logger: L, network: Currency
110 ) -> Result<Invoice, SignOrCreationError<()>>
112 K::Target: KeysInterface,
115 _create_phantom_invoice::<K, L>(
116 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
117 invoice_expiry_delta_secs, phantom_route_hints, keys_manager, logger, network,
121 #[cfg(feature = "std")]
122 fn _create_phantom_invoice<K: Deref, L: Deref>(
123 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
124 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, keys_manager: K,
125 logger: L, network: Currency,
126 ) -> Result<Invoice, SignOrCreationError<()>>
128 K::Target: KeysInterface,
131 use std::time::{SystemTime, UNIX_EPOCH};
133 if phantom_route_hints.len() == 0 {
134 return Err(SignOrCreationError::CreationError(
135 CreationError::MissingRouteHints,
139 let invoice = match description {
140 InvoiceDescription::Direct(description) => {
141 InvoiceBuilder::new(network).description(description.0.clone())
143 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
146 // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
147 let keys = ExpandedKey::new(&keys_manager.get_inbound_payment_key_material());
148 let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
149 let payment_secret = create_from_hash(
153 invoice_expiry_delta_secs,
155 .duration_since(UNIX_EPOCH)
156 .expect("Time must be > 1970")
159 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
160 (payment_hash, payment_secret)
165 invoice_expiry_delta_secs,
168 .duration_since(UNIX_EPOCH)
169 .expect("Time must be > 1970")
172 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
175 log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
176 phantom_route_hints.len(), log_bytes!(payment_hash.0));
178 let mut invoice = invoice
180 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
181 .payment_secret(payment_secret)
182 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into())
183 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
184 if let Some(amt) = amt_msat {
185 invoice = invoice.amount_milli_satoshis(amt);
188 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
189 log_trace!(logger, "Generating phantom route hints for node {}",
190 log_pubkey!(real_node_pubkey));
191 let mut route_hints = filter_channels(channels, amt_msat, &logger);
193 // If we have any public channel, the route hints from `filter_channels` will be empty.
194 // In that case we create a RouteHint on which we will push a single hop with the phantom
195 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
196 // node by looking at our public channels.
197 if route_hints.is_empty() {
198 route_hints.push(RouteHint(vec![]))
200 for mut route_hint in route_hints {
201 route_hint.0.push(RouteHintHop {
202 src_node_id: real_node_pubkey,
203 short_channel_id: phantom_scid,
206 proportional_millionths: 0,
208 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
209 htlc_minimum_msat: None,
210 htlc_maximum_msat: None,});
211 invoice = invoice.private_route(route_hint.clone());
215 let raw_invoice = match invoice.build_raw() {
217 Err(e) => return Err(SignOrCreationError::CreationError(e))
219 let hrp_str = raw_invoice.hrp.to_string();
220 let hrp_bytes = hrp_str.as_bytes();
221 let data_without_signature = raw_invoice.data.to_base32();
222 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
223 match signed_raw_invoice {
224 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
225 Err(e) => Err(SignOrCreationError::SignError(e))
229 #[cfg(feature = "std")]
230 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
231 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
232 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
233 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
234 /// that the payment secret is valid when the invoice is paid.
236 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
237 /// in excess of the current time.
238 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
239 channelmanager: &ChannelManager<M, T, K, F, L>, keys_manager: K, logger: L,
240 network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32
241 ) -> Result<Invoice, SignOrCreationError<()>>
243 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
244 T::Target: BroadcasterInterface,
245 K::Target: KeysInterface,
246 F::Target: FeeEstimator,
249 use std::time::SystemTime;
250 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
251 .expect("for the foreseeable future this shouldn't happen");
252 create_invoice_from_channelmanager_and_duration_since_epoch(
253 channelmanager, keys_manager, logger, network, amt_msat, description, duration,
254 invoice_expiry_delta_secs
258 #[cfg(feature = "std")]
259 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
260 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
261 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
262 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
263 /// that the payment secret is valid when the invoice is paid.
264 /// Use this variant if you want to pass the `description_hash` to the invoice.
266 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
267 /// in excess of the current time.
268 pub fn create_invoice_from_channelmanager_with_description_hash<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
269 channelmanager: &ChannelManager<M, T, K, F, L>, keys_manager: K, logger: L,
270 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
271 invoice_expiry_delta_secs: u32
272 ) -> Result<Invoice, SignOrCreationError<()>>
274 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
275 T::Target: BroadcasterInterface,
276 K::Target: KeysInterface,
277 F::Target: FeeEstimator,
280 use std::time::SystemTime;
282 let duration = SystemTime::now()
283 .duration_since(SystemTime::UNIX_EPOCH)
284 .expect("for the foreseeable future this shouldn't happen");
286 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
287 channelmanager, keys_manager, logger, network, amt_msat,
288 description_hash, duration, invoice_expiry_delta_secs
292 /// See [`create_invoice_from_channelmanager_with_description_hash`]
293 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
294 /// available and the current time is supplied by the caller.
295 pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
296 channelmanager: &ChannelManager<M, T, K, F, L>, keys_manager: K, logger: L,
297 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
298 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32
299 ) -> Result<Invoice, SignOrCreationError<()>>
301 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
302 T::Target: BroadcasterInterface,
303 K::Target: KeysInterface,
304 F::Target: FeeEstimator,
307 _create_invoice_from_channelmanager_and_duration_since_epoch(
308 channelmanager, keys_manager, logger, network, amt_msat,
309 InvoiceDescription::Hash(&description_hash),
310 duration_since_epoch, invoice_expiry_delta_secs
314 /// See [`create_invoice_from_channelmanager`]
315 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
316 /// available and the current time is supplied by the caller.
317 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
318 channelmanager: &ChannelManager<M, T, K, F, L>, keys_manager: K, logger: L,
319 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
320 invoice_expiry_delta_secs: u32
321 ) -> Result<Invoice, SignOrCreationError<()>>
323 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
324 T::Target: BroadcasterInterface,
325 K::Target: KeysInterface,
326 F::Target: FeeEstimator,
329 _create_invoice_from_channelmanager_and_duration_since_epoch(
330 channelmanager, keys_manager, logger, network, amt_msat,
331 InvoiceDescription::Direct(
332 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
334 duration_since_epoch, invoice_expiry_delta_secs
338 fn _create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>(
339 channelmanager: &ChannelManager<M, T, K, F, L>, keys_manager: K, logger: L,
340 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
341 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32
342 ) -> Result<Invoice, SignOrCreationError<()>>
344 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
345 T::Target: BroadcasterInterface,
346 K::Target: KeysInterface,
347 F::Target: FeeEstimator,
350 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
352 let (payment_hash, payment_secret) = channelmanager
353 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs)
354 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
355 let our_node_pubkey = channelmanager.get_our_node_id();
356 let channels = channelmanager.list_channels();
358 log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
360 let invoice = match description {
361 InvoiceDescription::Direct(description) => {
362 InvoiceBuilder::new(network).description(description.0.clone())
364 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
367 let mut invoice = invoice
368 .duration_since_epoch(duration_since_epoch)
369 .payee_pub_key(our_node_pubkey)
370 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
371 .payment_secret(payment_secret)
373 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into())
374 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
375 if let Some(amt) = amt_msat {
376 invoice = invoice.amount_milli_satoshis(amt);
379 let route_hints = filter_channels(channels, amt_msat, &logger);
380 for hint in route_hints {
381 invoice = invoice.private_route(hint);
384 let raw_invoice = match invoice.build_raw() {
386 Err(e) => return Err(SignOrCreationError::CreationError(e))
388 let hrp_str = raw_invoice.hrp.to_string();
389 let hrp_bytes = hrp_str.as_bytes();
390 let data_without_signature = raw_invoice.data.to_base32();
391 let signed_raw_invoice = raw_invoice.sign(|_| keys_manager.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
392 match signed_raw_invoice {
393 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
394 Err(e) => Err(SignOrCreationError::SignError(e))
398 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
401 /// The filtering is based on the following criteria:
402 /// * Only one channel per counterparty node
403 /// * Always select the channel with the highest inbound capacity per counterparty node
404 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
405 /// `is_usable` (i.e. the peer is connected).
406 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
407 /// need to find the path by looking at the public channels instead
408 fn filter_channels<L: Deref>(
409 channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
410 ) -> Vec<RouteHint> where L::Target: Logger {
411 let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
412 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
413 let mut min_capacity_channel_exists = false;
414 let mut online_channel_exists = false;
415 let mut online_min_capacity_channel_exists = false;
417 log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
418 for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
419 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
420 log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
424 if channel.is_public {
425 // If any public channel exists, return no hints and let the sender
426 // look at the public channels instead.
427 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
428 log_bytes!(channel.channel_id));
432 if channel.inbound_capacity_msat >= min_inbound_capacity {
433 if !min_capacity_channel_exists {
434 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
435 min_capacity_channel_exists = true;
438 if channel.is_usable {
439 online_min_capacity_channel_exists = true;
443 if channel.is_usable {
444 if !online_channel_exists {
445 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
446 online_channel_exists = true;
450 match filtered_channels.entry(channel.counterparty.node_id) {
451 hash_map::Entry::Occupied(mut entry) => {
452 let current_max_capacity = entry.get().inbound_capacity_msat;
453 if channel.inbound_capacity_msat < current_max_capacity {
455 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
456 log_pubkey!(channel.counterparty.node_id),
457 log_bytes!(entry.get().channel_id), current_max_capacity,
458 log_bytes!(channel.channel_id), channel.inbound_capacity_msat);
462 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
463 log_pubkey!(channel.counterparty.node_id),
464 log_bytes!(channel.channel_id), channel.inbound_capacity_msat,
465 log_bytes!(entry.get().channel_id), current_max_capacity);
466 entry.insert(channel);
468 hash_map::Entry::Vacant(entry) => {
469 entry.insert(channel);
474 let route_hint_from_channel = |channel: ChannelDetails| {
475 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
476 RouteHint(vec![RouteHintHop {
477 src_node_id: channel.counterparty.node_id,
478 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
480 base_msat: forwarding_info.fee_base_msat,
481 proportional_millionths: forwarding_info.fee_proportional_millionths,
483 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
484 htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
485 htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
487 // If all channels are private, prefer to return route hints which have a higher capacity than
488 // the payment value and where we're currently connected to the channel counterparty.
489 // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
490 // those which meet at least one criteria.
493 .map(|(_, channel)| channel)
495 let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
496 let include_channel = if online_min_capacity_channel_exists {
497 has_enough_capacity && channel.is_usable
498 } else if min_capacity_channel_exists && online_channel_exists {
499 // If there are some online channels and some min_capacity channels, but no
500 // online-and-min_capacity channels, just include the min capacity ones and ignore
503 } else if min_capacity_channel_exists {
505 } else if online_channel_exists {
510 log_trace!(logger, "Including channel {} in invoice route hints",
511 log_bytes!(channel.channel_id));
512 } else if !has_enough_capacity {
513 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
514 log_bytes!(channel.channel_id));
516 debug_assert!(!channel.is_usable);
517 log_trace!(logger, "Ignoring channel {} with disconnected peer",
518 log_bytes!(channel.channel_id));
523 .map(route_hint_from_channel)
524 .collect::<Vec<RouteHint>>()
527 /// A [`Router`] implemented using [`find_route`].
528 pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
530 S::Target: for <'a> LockableScore<'a>,
534 random_seed_bytes: Mutex<[u8; 32]>,
538 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
540 S::Target: for <'a> LockableScore<'a>,
542 /// Creates a new router using the given [`NetworkGraph`], a [`Logger`], and a randomness source
543 /// `random_seed_bytes`.
544 pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
545 let random_seed_bytes = Mutex::new(random_seed_bytes);
546 Self { network_graph, logger, random_seed_bytes, scorer }
550 impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
552 S::Target: for <'a> LockableScore<'a>,
555 &self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
556 inflight_htlcs: InFlightHtlcs
557 ) -> Result<Route, LightningError> {
558 let random_seed_bytes = {
559 let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
560 *locked_random_seed_bytes = sha256::Hash::hash(&*locked_random_seed_bytes).into_inner();
561 *locked_random_seed_bytes
565 payer, params, &self.network_graph, first_hops, &*self.logger,
566 &ScorerAccountingForInFlightHtlcs::new(&mut self.scorer.lock(), inflight_htlcs),
571 fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
572 self.scorer.lock().payment_path_failed(path, short_channel_id);
575 fn notify_payment_path_successful(&self, path: &[&RouteHop]) {
576 self.scorer.lock().payment_path_successful(path);
579 fn notify_payment_probe_successful(&self, path: &[&RouteHop]) {
580 self.scorer.lock().probe_successful(path);
583 fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) {
584 self.scorer.lock().probe_failed(path, short_channel_id);
588 impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Payer for ChannelManager<M, T, K, F, L>
590 M::Target: chain::Watch<<K::Target as KeysInterface>::Signer>,
591 T::Target: BroadcasterInterface,
592 K::Target: KeysInterface,
593 F::Target: FeeEstimator,
596 fn node_id(&self) -> PublicKey {
597 self.get_our_node_id()
600 fn first_hops(&self) -> Vec<ChannelDetails> {
601 self.list_usable_channels()
605 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
606 payment_id: PaymentId
607 ) -> Result<(), PaymentSendFailure> {
608 self.send_payment(route, payment_hash, payment_secret, payment_id)
611 fn send_spontaneous_payment(
612 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
613 ) -> Result<(), PaymentSendFailure> {
614 self.send_spontaneous_payment(route, Some(payment_preimage), payment_id).map(|_| ())
618 &self, route: &Route, payment_id: PaymentId
619 ) -> Result<(), PaymentSendFailure> {
620 self.retry_payment(route, payment_id)
623 fn abandon_payment(&self, payment_id: PaymentId) {
624 self.abandon_payment(payment_id)
627 fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() }
632 use core::time::Duration;
633 use crate::{Currency, Description, InvoiceDescription};
634 use bitcoin_hashes::Hash;
635 use bitcoin_hashes::sha256::Hash as Sha256;
636 use lightning::chain::keysinterface::PhantomKeysManager;
637 use lightning::ln::{PaymentPreimage, PaymentHash};
638 use lightning::ln::channelmanager::{self, PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY, PaymentId};
639 use lightning::ln::functional_test_utils::*;
640 use lightning::ln::msgs::ChannelMessageHandler;
641 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
642 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
643 use lightning::util::test_utils;
644 use lightning::util::config::UserConfig;
645 use lightning::chain::keysinterface::KeysInterface;
646 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
647 use std::collections::HashSet;
650 fn test_from_channelmanager() {
651 let chanmon_cfgs = create_chanmon_cfgs(2);
652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
654 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
655 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
656 let non_default_invoice_expiry_secs = 4200;
657 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
658 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
659 Some(10_000), "test".to_string(), Duration::from_secs(1234567),
660 non_default_invoice_expiry_secs).unwrap();
661 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
662 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
663 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
664 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
666 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
668 let chan = &nodes[1].node.list_usable_channels()[0];
669 assert_eq!(invoice.route_hints().len(), 1);
670 assert_eq!(invoice.route_hints()[0].0.len(), 1);
671 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
673 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
674 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
676 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
677 .with_features(invoice.features().unwrap().clone())
678 .with_route_hints(invoice.route_hints());
679 let route_params = RouteParameters {
681 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
682 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
684 let first_hops = nodes[0].node.list_usable_channels();
685 let network_graph = &node_cfgs[0].network_graph;
686 let logger = test_utils::TestLogger::new();
687 let scorer = test_utils::TestScorer::with_penalty(0);
688 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
689 let route = find_route(
690 &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
691 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
694 let payment_event = {
695 let mut payment_hash = PaymentHash([0; 32]);
696 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
697 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
698 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
699 assert_eq!(added_monitors.len(), 1);
700 added_monitors.clear();
702 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
703 assert_eq!(events.len(), 1);
704 SendEvent::from_event(events.remove(0))
707 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
708 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
709 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
710 assert_eq!(added_monitors.len(), 1);
711 added_monitors.clear();
712 let events = nodes[1].node.get_and_clear_pending_msg_events();
713 assert_eq!(events.len(), 2);
717 fn test_create_invoice_with_description_hash() {
718 let chanmon_cfgs = create_chanmon_cfgs(2);
719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
722 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
723 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
724 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
725 Some(10_000), description_hash, Duration::from_secs(1234567), 3600
727 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
728 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
729 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
733 fn test_hints_includes_single_channels_to_nodes() {
734 let chanmon_cfgs = create_chanmon_cfgs(3);
735 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
736 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
737 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
739 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
740 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
742 let mut scid_aliases = HashSet::new();
743 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
744 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
746 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
750 fn test_hints_has_only_highest_inbound_capacity_channel() {
751 let chanmon_cfgs = create_chanmon_cfgs(2);
752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
755 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
756 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
757 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
759 let mut scid_aliases = HashSet::new();
760 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
762 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
766 fn test_hints_has_only_online_channels() {
767 let chanmon_cfgs = create_chanmon_cfgs(4);
768 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
769 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
770 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
771 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
772 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
773 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
775 // With all peers connected we should get all hints that have sufficient value
776 let mut scid_aliases = HashSet::new();
777 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
778 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
780 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
782 // With only one sufficient-value peer connected we should only get its hint
783 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
784 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
785 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
787 // If we don't have any sufficient-value peers connected we should get all hints with
788 // sufficient value, even though there is a connected insufficient-value peer.
789 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
790 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
791 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
795 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
796 let chanmon_cfgs = create_chanmon_cfgs(3);
797 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
798 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
799 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
800 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
802 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
803 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
804 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
805 let mut private_chan_cfg = UserConfig::default();
806 private_chan_cfg.channel_handshake_config.announced_channel = false;
807 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();
808 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
809 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
810 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
811 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
813 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
815 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
816 confirm_transaction_at(&nodes[2], &tx, conf_height);
817 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
818 confirm_transaction_at(&nodes[0], &tx, conf_height);
819 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
820 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
821 nodes[2].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[2].node.get_our_node_id()));
822 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
823 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
824 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
825 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
826 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
828 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
829 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
830 // Therefore only `chan_1_0` should be included in the hints.
831 let mut scid_aliases = HashSet::new();
832 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
833 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
837 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
838 let chanmon_cfgs = create_chanmon_cfgs(3);
839 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
840 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
841 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
842 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
844 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
845 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
846 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
848 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
849 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
850 // public channel between `nodes[2]` and `nodes[0]`
851 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
855 fn test_only_public_channels_includes_no_channels_in_hints() {
856 let chanmon_cfgs = create_chanmon_cfgs(3);
857 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
861 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
862 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
864 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
865 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
866 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
868 // As all of `nodes[0]` channels are public, no channels should be included in the hints
869 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
873 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
874 let chanmon_cfgs = create_chanmon_cfgs(3);
875 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
876 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
877 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
878 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
879 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
881 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
882 let mut scid_aliases_99_000_001_msat = HashSet::new();
883 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
885 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
887 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
888 let mut scid_aliases_99_000_000_msat = HashSet::new();
889 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
890 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
892 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
894 // As the invoice amt is above all channels' inbound capacity, they will still be included
895 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
896 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
897 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
899 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
901 // An invoice with no specified amount should include all channels in the route hints.
902 let mut scid_aliases_no_specified_amount = HashSet::new();
903 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
904 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
906 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
909 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
910 invoice_amt: Option<u64>,
911 invoice_node: &Node<'a, 'b, 'c>,
912 mut chan_ids_to_match: HashSet<u64>
914 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
915 &invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
916 Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
918 let hints = invoice.private_routes();
921 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
922 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
924 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
928 #[cfg(feature = "std")]
929 fn test_multi_node_receive() {
930 do_test_multi_node_receive(true);
931 do_test_multi_node_receive(false);
934 #[cfg(feature = "std")]
935 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
936 let mut chanmon_cfgs = create_chanmon_cfgs(3);
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[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
941 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
942 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
943 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
944 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
945 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
946 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
947 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
948 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
949 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
950 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
952 let payment_amt = 10_000;
953 let route_hints = vec![
954 nodes[1].node.get_phantom_route_hints(),
955 nodes[2].node.get_phantom_route_hints(),
958 let user_payment_preimage = PaymentPreimage([1; 32]);
959 let payment_hash = if user_generated_pmt_hash {
960 Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
964 let non_default_invoice_expiry_secs = 4200;
967 crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>(
968 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
969 route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet
971 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
972 let payment_preimage = if user_generated_pmt_hash {
973 user_payment_preimage
975 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
978 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
979 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
980 assert_eq!(invoice.route_hints().len(), 2);
981 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
982 assert!(!invoice.features().unwrap().supports_basic_mpp());
984 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
985 .with_features(invoice.features().unwrap().clone())
986 .with_route_hints(invoice.route_hints());
987 let params = RouteParameters {
989 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
990 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
992 let first_hops = nodes[0].node.list_usable_channels();
993 let network_graph = &node_cfgs[0].network_graph;
994 let logger = test_utils::TestLogger::new();
995 let scorer = test_utils::TestScorer::with_penalty(0);
996 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
997 let route = find_route(
998 &nodes[0].node.get_our_node_id(), ¶ms, &network_graph,
999 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1001 let (payment_event, fwd_idx) = {
1002 let mut payment_hash = PaymentHash([0; 32]);
1003 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1004 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
1005 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1006 assert_eq!(added_monitors.len(), 1);
1007 added_monitors.clear();
1009 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1010 assert_eq!(events.len(), 1);
1011 let fwd_idx = match events[0] {
1012 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1013 if node_id == nodes[1].node.get_our_node_id() {
1017 _ => panic!("Unexpected event")
1019 (SendEvent::from_event(events.remove(0)), fwd_idx)
1021 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1022 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1024 // Note that we have to "forward pending HTLCs" twice before we see the PaymentReceived as
1025 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1026 // payments "look real" by taking more time.
1027 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1028 nodes[fwd_idx].node.process_pending_htlc_forwards();
1029 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1030 nodes[fwd_idx].node.process_pending_htlc_forwards();
1032 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1033 expect_payment_received!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt);
1034 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
1035 let events = nodes[0].node.get_and_clear_pending_events();
1036 assert_eq!(events.len(), 2);
1038 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1039 assert_eq!(payment_preimage, *ev_preimage);
1040 assert_eq!(payment_hash, *ev_hash);
1041 assert_eq!(fee_paid_msat, &Some(0));
1043 _ => panic!("Unexpected event")
1046 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1047 assert_eq!(hash, Some(payment_hash));
1049 _ => panic!("Unexpected event")
1054 #[cfg(feature = "std")]
1055 fn test_multi_node_hints_has_htlc_min_max_values() {
1056 let mut chanmon_cfgs = create_chanmon_cfgs(3);
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(3, &chanmon_cfgs);
1063 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1064 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1066 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1067 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1069 let payment_amt = 20_000;
1070 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
1071 let route_hints = vec![
1072 nodes[1].node.get_phantom_route_hints(),
1073 nodes[2].node.get_phantom_route_hints(),
1076 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).unwrap();
1078 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1079 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1080 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1082 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1083 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1084 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1088 #[cfg(feature = "std")]
1089 fn create_phantom_invoice_with_description_hash() {
1090 let chanmon_cfgs = create_chanmon_cfgs(3);
1091 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1092 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1093 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1095 let payment_amt = 20_000;
1096 let route_hints = vec![
1097 nodes[1].node.get_phantom_route_hints(),
1098 nodes[2].node.get_phantom_route_hints(),
1101 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1102 let non_default_invoice_expiry_secs = 4200;
1103 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1104 &test_utils::TestKeysInterface, &test_utils::TestLogger,
1106 Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1107 route_hints, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet
1110 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1111 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
1112 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1113 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1117 #[cfg(feature = "std")]
1118 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1119 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1120 let seed_1 = [42 as u8; 32];
1121 let seed_2 = [43 as u8; 32];
1122 let cross_node_seed = [44 as u8; 32];
1123 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1124 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1125 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1126 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1127 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1129 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1130 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1132 let mut scid_aliases = HashSet::new();
1133 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1134 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1136 match_multi_node_invoice_routes(
1139 vec![&nodes[1], &nodes[2],],
1146 #[cfg(feature = "std")]
1147 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1148 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1149 let seed_1 = [42 as u8; 32];
1150 let seed_2 = [43 as u8; 32];
1151 let cross_node_seed = [44 as u8; 32];
1152 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1153 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1154 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1155 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1156 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1158 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1159 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1160 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1162 let mut scid_aliases = HashSet::new();
1163 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1164 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1165 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1167 match_multi_node_invoice_routes(
1170 vec![&nodes[2], &nodes[3],],
1177 #[cfg(feature = "std")]
1178 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1179 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1180 let seed_1 = [42 as u8; 32];
1181 let seed_2 = [43 as u8; 32];
1182 let cross_node_seed = [44 as u8; 32];
1183 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1184 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1185 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1186 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1187 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1189 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1190 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1192 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1193 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1194 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1195 let mut private_chan_cfg = UserConfig::default();
1196 private_chan_cfg.channel_handshake_config.announced_channel = false;
1197 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();
1198 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1199 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), channelmanager::provided_init_features(), &open_channel);
1200 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1201 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), channelmanager::provided_init_features(), &accept_channel);
1203 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1205 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1206 confirm_transaction_at(&nodes[1], &tx, conf_height);
1207 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1208 confirm_transaction_at(&nodes[3], &tx, conf_height);
1209 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1210 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1211 nodes[1].node.handle_channel_ready(&nodes[3].node.get_our_node_id(), &get_event_msg!(nodes[3], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
1212 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1213 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1214 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1215 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1216 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1218 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1219 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1220 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1221 let mut scid_aliases = HashSet::new();
1222 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1223 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1225 match_multi_node_invoice_routes(
1228 vec![&nodes[2], &nodes[3],],
1235 #[cfg(feature = "std")]
1236 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1237 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1238 let seed_1 = [42 as u8; 32];
1239 let seed_2 = [43 as u8; 32];
1240 let cross_node_seed = [44 as u8; 32];
1241 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1242 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1245 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1247 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1249 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1250 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1251 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1253 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1254 // `chan_0_2` as `nodes[2]` only has public channels.
1255 let mut scid_aliases = HashSet::new();
1256 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1258 match_multi_node_invoice_routes(
1261 vec![&nodes[1], &nodes[2],],
1268 #[cfg(feature = "std")]
1269 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1270 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1271 let seed_1 = [42 as u8; 32];
1272 let seed_2 = [43 as u8; 32];
1273 let cross_node_seed = [44 as u8; 32];
1274 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1275 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1276 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1277 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1278 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1280 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1281 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1282 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1283 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1285 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1287 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1288 // channels for `nodes[2]` as it contains a mix of public and private channels.
1289 let mut scid_aliases = HashSet::new();
1290 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1292 match_multi_node_invoice_routes(
1295 vec![&nodes[2], &nodes[3],],
1302 #[cfg(feature = "std")]
1303 fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1304 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1305 let seed_1 = [42 as u8; 32];
1306 let seed_2 = [43 as u8; 32];
1307 let cross_node_seed = [44 as u8; 32];
1308 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1309 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1310 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1311 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1312 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1314 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1315 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1316 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1317 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1319 let mut scid_aliases = HashSet::new();
1320 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1321 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1323 match_multi_node_invoice_routes(
1326 vec![&nodes[1], &nodes[2],],
1333 #[cfg(feature = "std")]
1334 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1335 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1336 let seed_1 = [42 as u8; 32];
1337 let seed_2 = [43 as u8; 32];
1338 let cross_node_seed = [44 as u8; 32];
1339 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1340 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1341 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1342 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1343 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1345 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1346 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1347 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0, channelmanager::provided_init_features(), channelmanager::provided_init_features());
1349 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1350 let mut scid_aliases_99_000_001_msat = HashSet::new();
1351 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1352 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1354 match_multi_node_invoice_routes(
1357 vec![&nodes[2], &nodes[3],],
1358 scid_aliases_99_000_001_msat,
1362 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1363 let mut scid_aliases_99_000_000_msat = HashSet::new();
1364 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1365 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1366 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1368 match_multi_node_invoice_routes(
1371 vec![&nodes[2], &nodes[3],],
1372 scid_aliases_99_000_000_msat,
1376 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1377 // `nodes[2]` them should be included.
1378 let mut scid_aliases_300_000_000_msat = HashSet::new();
1379 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1380 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1381 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1383 match_multi_node_invoice_routes(
1386 vec![&nodes[2], &nodes[3],],
1387 scid_aliases_300_000_000_msat,
1391 // Since the no specified amount, all channels should included.
1392 let mut scid_aliases_no_specified_amount = HashSet::new();
1393 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1394 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1395 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1397 match_multi_node_invoice_routes(
1400 vec![&nodes[2], &nodes[3],],
1401 scid_aliases_no_specified_amount,
1406 #[cfg(feature = "std")]
1407 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1408 invoice_amt: Option<u64>,
1409 invoice_node: &Node<'a, 'b, 'c>,
1410 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1411 mut chan_ids_to_match: HashSet<u64>,
1412 nodes_contains_public_channels: bool
1414 let phantom_route_hints = network_multi_nodes.iter()
1415 .map(|node| node.node.get_phantom_route_hints())
1416 .collect::<Vec<PhantomRouteHints>>();
1417 let phantom_scids = phantom_route_hints.iter()
1418 .map(|route_hint| route_hint.phantom_scid)
1419 .collect::<HashSet<u64>>();
1421 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap();
1423 let invoice_hints = invoice.private_routes();
1425 for hint in invoice_hints {
1426 let hints = &(hint.0).0;
1429 assert!(nodes_contains_public_channels);
1430 let phantom_scid = hints[0].short_channel_id;
1431 assert!(phantom_scids.contains(&phantom_scid));
1434 let hint_short_chan_id = hints[0].short_channel_id;
1435 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1436 let phantom_scid = hints[1].short_channel_id;
1437 assert!(phantom_scids.contains(&phantom_scid));
1439 _ => panic!("Incorrect hint length generated")
1442 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);