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;
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::keysinterface::{Recipient, NodeSigner, SignerProvider, EntropySource};
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::routing::gossip::RoutingFees;
18 use lightning::routing::router::{InFlightHtlcs, Route, RouteHint, RouteHintHop, Router};
19 use lightning::util::logger::Logger;
20 use secp256k1::PublicKey;
22 use core::time::Duration;
24 #[cfg(feature = "std")]
25 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
26 /// See [`PhantomKeysManager`] for more information on phantom node payments.
28 /// `phantom_route_hints` parameter:
29 /// * Contains channel info for all nodes participating in the phantom invoice
30 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
31 /// participating node
32 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
33 /// updated when a channel becomes disabled or closes
34 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
35 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
38 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
39 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
40 /// If `None` is provided for `payment_hash`, then one will be created.
42 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
43 /// in excess of the current time.
45 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
46 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
49 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
50 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
51 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
52 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
53 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
54 pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
55 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
56 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
57 node_signer: NS, logger: L, network: Currency,
58 ) -> Result<Invoice, SignOrCreationError<()>>
60 ES::Target: EntropySource,
61 NS::Target: NodeSigner,
64 let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
65 let description = InvoiceDescription::Direct(&description,);
66 _create_phantom_invoice::<ES, NS, L>(
67 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
68 entropy_source, node_signer, logger, network,
72 #[cfg(feature = "std")]
73 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
74 /// See [`PhantomKeysManager`] for more information on phantom node payments.
76 /// `phantom_route_hints` parameter:
77 /// * Contains channel info for all nodes participating in the phantom invoice
78 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
79 /// participating node
80 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
81 /// updated when a channel becomes disabled or closes
82 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
83 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
86 /// `description_hash` is a SHA-256 hash of the description text
88 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
89 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
90 /// If `None` is provided for `payment_hash`, then one will be created.
92 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
93 /// in excess of the current time.
95 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
96 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
99 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
100 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
101 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
102 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
103 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
104 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
105 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
106 description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
107 node_signer: NS, logger: L, network: Currency
108 ) -> Result<Invoice, SignOrCreationError<()>>
110 ES::Target: EntropySource,
111 NS::Target: NodeSigner,
114 _create_phantom_invoice::<ES, NS, L>(
115 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
116 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
120 #[cfg(feature = "std")]
121 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
122 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
123 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
124 node_signer: NS, logger: L, network: Currency,
125 ) -> Result<Invoice, SignOrCreationError<()>>
127 ES::Target: EntropySource,
128 NS::Target: NodeSigner,
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(&node_signer.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(|_| node_signer.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, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
239 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, 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<<SP::Target as SignerProvider>::Signer>,
244 T::Target: BroadcasterInterface,
245 ES::Target: EntropySource,
246 NS::Target: NodeSigner,
247 SP::Target: SignerProvider,
248 F::Target: FeeEstimator,
252 use std::time::SystemTime;
253 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
254 .expect("for the foreseeable future this shouldn't happen");
255 create_invoice_from_channelmanager_and_duration_since_epoch(
256 channelmanager, node_signer, logger, network, amt_msat,
257 description, duration, invoice_expiry_delta_secs
261 #[cfg(feature = "std")]
262 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
263 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
264 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
265 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
266 /// that the payment secret is valid when the invoice is paid.
267 /// Use this variant if you want to pass the `description_hash` to the invoice.
269 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
270 /// in excess of the current time.
271 pub fn create_invoice_from_channelmanager_with_description_hash<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
272 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
273 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
274 invoice_expiry_delta_secs: u32
275 ) -> Result<Invoice, SignOrCreationError<()>>
277 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
278 T::Target: BroadcasterInterface,
279 ES::Target: EntropySource,
280 NS::Target: NodeSigner,
281 SP::Target: SignerProvider,
282 F::Target: FeeEstimator,
286 use std::time::SystemTime;
288 let duration = SystemTime::now()
289 .duration_since(SystemTime::UNIX_EPOCH)
290 .expect("for the foreseeable future this shouldn't happen");
292 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
293 channelmanager, node_signer, logger, network, amt_msat,
294 description_hash, duration, invoice_expiry_delta_secs
298 /// See [`create_invoice_from_channelmanager_with_description_hash`]
299 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
300 /// available and the current time is supplied by the caller.
301 pub fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
302 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
303 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
304 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32
305 ) -> Result<Invoice, SignOrCreationError<()>>
307 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
308 T::Target: BroadcasterInterface,
309 ES::Target: EntropySource,
310 NS::Target: NodeSigner,
311 SP::Target: SignerProvider,
312 F::Target: FeeEstimator,
316 _create_invoice_from_channelmanager_and_duration_since_epoch(
317 channelmanager, node_signer, logger, network, amt_msat,
318 InvoiceDescription::Hash(&description_hash),
319 duration_since_epoch, invoice_expiry_delta_secs
323 /// See [`create_invoice_from_channelmanager`]
324 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
325 /// available and the current time is supplied by the caller.
326 pub fn create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
327 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
328 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
329 invoice_expiry_delta_secs: u32
330 ) -> Result<Invoice, SignOrCreationError<()>>
332 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
333 T::Target: BroadcasterInterface,
334 ES::Target: EntropySource,
335 NS::Target: NodeSigner,
336 SP::Target: SignerProvider,
337 F::Target: FeeEstimator,
341 _create_invoice_from_channelmanager_and_duration_since_epoch(
342 channelmanager, node_signer, logger, network, amt_msat,
343 InvoiceDescription::Direct(
344 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
346 duration_since_epoch, invoice_expiry_delta_secs
350 fn _create_invoice_from_channelmanager_and_duration_since_epoch<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
351 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
352 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
353 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32
354 ) -> Result<Invoice, SignOrCreationError<()>>
356 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
357 T::Target: BroadcasterInterface,
358 ES::Target: EntropySource,
359 NS::Target: NodeSigner,
360 SP::Target: SignerProvider,
361 F::Target: FeeEstimator,
365 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
367 let (payment_hash, payment_secret) = channelmanager
368 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs)
369 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
370 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
371 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret)
374 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
375 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
376 /// This may be useful if you're building an on-chain swap or involving another protocol where
377 /// the payment hash is also involved outside the scope of lightning.
378 pub fn create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
379 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
380 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
381 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash
382 ) -> Result<Invoice, SignOrCreationError<()>>
384 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
385 T::Target: BroadcasterInterface,
386 ES::Target: EntropySource,
387 NS::Target: NodeSigner,
388 SP::Target: SignerProvider,
389 F::Target: FeeEstimator,
393 let payment_secret = channelmanager
394 .create_inbound_payment_for_hash(payment_hash,amt_msat, invoice_expiry_delta_secs)
395 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
396 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
397 channelmanager, node_signer, logger, network, amt_msat,
398 InvoiceDescription::Direct(
399 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
401 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret
405 fn _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
406 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
407 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
408 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret
409 ) -> Result<Invoice, SignOrCreationError<()>>
411 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
412 T::Target: BroadcasterInterface,
413 ES::Target: EntropySource,
414 NS::Target: NodeSigner,
415 SP::Target: SignerProvider,
416 F::Target: FeeEstimator,
420 let our_node_pubkey = channelmanager.get_our_node_id();
421 let channels = channelmanager.list_channels();
423 log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
425 let invoice = match description {
426 InvoiceDescription::Direct(description) => {
427 InvoiceBuilder::new(network).description(description.0.clone())
429 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
432 let mut invoice = invoice
433 .duration_since_epoch(duration_since_epoch)
434 .payee_pub_key(our_node_pubkey)
435 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
436 .payment_secret(payment_secret)
438 .min_final_cltv_expiry(MIN_FINAL_CLTV_EXPIRY.into())
439 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
440 if let Some(amt) = amt_msat {
441 invoice = invoice.amount_milli_satoshis(amt);
444 let route_hints = filter_channels(channels, amt_msat, &logger);
445 for hint in route_hints {
446 invoice = invoice.private_route(hint);
449 let raw_invoice = match invoice.build_raw() {
451 Err(e) => return Err(SignOrCreationError::CreationError(e))
453 let hrp_str = raw_invoice.hrp.to_string();
454 let hrp_bytes = hrp_str.as_bytes();
455 let data_without_signature = raw_invoice.data.to_base32();
456 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
457 match signed_raw_invoice {
458 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
459 Err(e) => Err(SignOrCreationError::SignError(e))
463 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
466 /// The filtering is based on the following criteria:
467 /// * Only one channel per counterparty node
468 /// * Always select the channel with the highest inbound capacity per counterparty node
469 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
470 /// `is_usable` (i.e. the peer is connected).
471 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
472 /// need to find the path by looking at the public channels instead
473 fn filter_channels<L: Deref>(
474 channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
475 ) -> Vec<RouteHint> where L::Target: Logger {
476 let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
477 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
478 let mut min_capacity_channel_exists = false;
479 let mut online_channel_exists = false;
480 let mut online_min_capacity_channel_exists = false;
482 log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
483 for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
484 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
485 log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
489 if channel.is_public {
490 // If any public channel exists, return no hints and let the sender
491 // look at the public channels instead.
492 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
493 log_bytes!(channel.channel_id));
497 if channel.inbound_capacity_msat >= min_inbound_capacity {
498 if !min_capacity_channel_exists {
499 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
500 min_capacity_channel_exists = true;
503 if channel.is_usable {
504 online_min_capacity_channel_exists = true;
508 if channel.is_usable {
509 if !online_channel_exists {
510 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
511 online_channel_exists = true;
515 match filtered_channels.entry(channel.counterparty.node_id) {
516 hash_map::Entry::Occupied(mut entry) => {
517 let current_max_capacity = entry.get().inbound_capacity_msat;
518 if channel.inbound_capacity_msat < current_max_capacity {
520 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
521 log_pubkey!(channel.counterparty.node_id),
522 log_bytes!(entry.get().channel_id), current_max_capacity,
523 log_bytes!(channel.channel_id), channel.inbound_capacity_msat);
527 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
528 log_pubkey!(channel.counterparty.node_id),
529 log_bytes!(channel.channel_id), channel.inbound_capacity_msat,
530 log_bytes!(entry.get().channel_id), current_max_capacity);
531 entry.insert(channel);
533 hash_map::Entry::Vacant(entry) => {
534 entry.insert(channel);
539 let route_hint_from_channel = |channel: ChannelDetails| {
540 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
541 RouteHint(vec![RouteHintHop {
542 src_node_id: channel.counterparty.node_id,
543 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
545 base_msat: forwarding_info.fee_base_msat,
546 proportional_millionths: forwarding_info.fee_proportional_millionths,
548 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
549 htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
550 htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
552 // If all channels are private, prefer to return route hints which have a higher capacity than
553 // the payment value and where we're currently connected to the channel counterparty.
554 // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
555 // those which meet at least one criteria.
558 .map(|(_, channel)| channel)
560 let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
561 let include_channel = if online_min_capacity_channel_exists {
562 has_enough_capacity && channel.is_usable
563 } else if min_capacity_channel_exists && online_channel_exists {
564 // If there are some online channels and some min_capacity channels, but no
565 // online-and-min_capacity channels, just include the min capacity ones and ignore
568 } else if min_capacity_channel_exists {
570 } else if online_channel_exists {
575 log_trace!(logger, "Including channel {} in invoice route hints",
576 log_bytes!(channel.channel_id));
577 } else if !has_enough_capacity {
578 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
579 log_bytes!(channel.channel_id));
581 debug_assert!(!channel.is_usable);
582 log_trace!(logger, "Ignoring channel {} with disconnected peer",
583 log_bytes!(channel.channel_id));
588 .map(route_hint_from_channel)
589 .collect::<Vec<RouteHint>>()
592 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> Payer for ChannelManager<M, T, ES, NS, SP, F, R, L>
594 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
595 T::Target: BroadcasterInterface,
596 ES::Target: EntropySource,
597 NS::Target: NodeSigner,
598 SP::Target: SignerProvider,
599 F::Target: FeeEstimator,
603 fn node_id(&self) -> PublicKey {
604 self.get_our_node_id()
607 fn first_hops(&self) -> Vec<ChannelDetails> {
608 self.list_usable_channels()
612 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
613 payment_id: PaymentId
614 ) -> Result<(), PaymentSendFailure> {
615 self.send_payment(route, payment_hash, payment_secret, payment_id)
618 fn send_spontaneous_payment(
619 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
620 ) -> Result<(), PaymentSendFailure> {
621 self.send_spontaneous_payment(route, Some(payment_preimage), payment_id).map(|_| ())
625 &self, route: &Route, payment_id: PaymentId
626 ) -> Result<(), PaymentSendFailure> {
627 self.retry_payment(route, payment_id)
630 fn abandon_payment(&self, payment_id: PaymentId) {
631 self.abandon_payment(payment_id)
634 fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() }
639 use core::time::Duration;
640 use crate::{Currency, Description, InvoiceDescription};
641 use bitcoin_hashes::{Hash, sha256};
642 use bitcoin_hashes::sha256::Hash as Sha256;
643 use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
644 use lightning::ln::{PaymentPreimage, PaymentHash};
645 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY, PaymentId};
646 use lightning::ln::functional_test_utils::*;
647 use lightning::ln::msgs::ChannelMessageHandler;
648 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
649 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
650 use lightning::util::test_utils;
651 use lightning::util::config::UserConfig;
652 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
653 use std::collections::HashSet;
656 fn test_from_channelmanager() {
657 let chanmon_cfgs = create_chanmon_cfgs(2);
658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
660 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
661 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
662 let non_default_invoice_expiry_secs = 4200;
663 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
664 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
665 Some(10_000), "test".to_string(), Duration::from_secs(1234567),
666 non_default_invoice_expiry_secs).unwrap();
667 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
668 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
669 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
670 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
672 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
674 let chan = &nodes[1].node.list_usable_channels()[0];
675 assert_eq!(invoice.route_hints().len(), 1);
676 assert_eq!(invoice.route_hints()[0].0.len(), 1);
677 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
679 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
680 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
682 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
683 .with_features(invoice.features().unwrap().clone())
684 .with_route_hints(invoice.route_hints());
685 let route_params = RouteParameters {
687 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
688 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
690 let first_hops = nodes[0].node.list_usable_channels();
691 let network_graph = &node_cfgs[0].network_graph;
692 let logger = test_utils::TestLogger::new();
693 let scorer = test_utils::TestScorer::with_penalty(0);
694 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
695 let route = find_route(
696 &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
697 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
700 let payment_event = {
701 let mut payment_hash = PaymentHash([0; 32]);
702 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
703 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
704 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
705 assert_eq!(added_monitors.len(), 1);
706 added_monitors.clear();
708 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
709 assert_eq!(events.len(), 1);
710 SendEvent::from_event(events.remove(0))
713 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
714 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
715 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
716 assert_eq!(added_monitors.len(), 1);
717 added_monitors.clear();
718 let events = nodes[1].node.get_and_clear_pending_msg_events();
719 assert_eq!(events.len(), 2);
723 fn test_create_invoice_with_description_hash() {
724 let chanmon_cfgs = create_chanmon_cfgs(2);
725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
727 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
728 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
729 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
730 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
731 Some(10_000), description_hash, Duration::from_secs(1234567), 3600
733 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
734 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
735 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
739 fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
740 let chanmon_cfgs = create_chanmon_cfgs(2);
741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
743 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
744 let payment_hash = PaymentHash([0; 32]);
745 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
746 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
747 Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
750 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
751 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
752 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
753 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
757 fn test_hints_includes_single_channels_to_nodes() {
758 let chanmon_cfgs = create_chanmon_cfgs(3);
759 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
760 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
761 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
763 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
764 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
766 let mut scid_aliases = HashSet::new();
767 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
768 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
770 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
774 fn test_hints_has_only_highest_inbound_capacity_channel() {
775 let chanmon_cfgs = create_chanmon_cfgs(2);
776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
778 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
779 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
780 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
781 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0);
782 let mut scid_aliases = HashSet::new();
783 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
784 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
788 fn test_hints_has_only_online_channels() {
789 let chanmon_cfgs = create_chanmon_cfgs(4);
790 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
791 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
792 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
793 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
794 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
795 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
797 // With all peers connected we should get all hints that have sufficient value
798 let mut scid_aliases = HashSet::new();
799 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
800 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
802 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
804 // With only one sufficient-value peer connected we should only get its hint
805 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
806 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
807 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
809 // If we don't have any sufficient-value peers connected we should get all hints with
810 // sufficient value, even though there is a connected insufficient-value peer.
811 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
812 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
813 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
817 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
818 let chanmon_cfgs = create_chanmon_cfgs(3);
819 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
821 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
822 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
824 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
825 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
826 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
827 let mut private_chan_cfg = UserConfig::default();
828 private_chan_cfg.channel_handshake_config.announced_channel = false;
829 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();
830 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
831 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
832 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
833 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
835 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
837 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
838 confirm_transaction_at(&nodes[2], &tx, conf_height);
839 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
840 confirm_transaction_at(&nodes[0], &tx, conf_height);
841 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
842 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
843 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()));
844 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
845 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
846 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
847 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
848 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
850 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
851 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
852 // Therefore only `chan_1_0` should be included in the hints.
853 let mut scid_aliases = HashSet::new();
854 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
855 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
859 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
860 let chanmon_cfgs = create_chanmon_cfgs(3);
861 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
862 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
863 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
864 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
866 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
867 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
868 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
870 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
871 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
872 // public channel between `nodes[2]` and `nodes[0]`
873 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
877 fn test_only_public_channels_includes_no_channels_in_hints() {
878 let chanmon_cfgs = create_chanmon_cfgs(3);
879 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
880 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
881 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
882 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
883 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
884 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
886 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
887 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
888 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
890 // As all of `nodes[0]` channels are public, no channels should be included in the hints
891 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
895 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
896 let chanmon_cfgs = create_chanmon_cfgs(3);
897 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
898 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
899 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
900 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
901 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
903 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
904 let mut scid_aliases_99_000_001_msat = HashSet::new();
905 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
907 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
909 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
910 let mut scid_aliases_99_000_000_msat = HashSet::new();
911 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
912 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
914 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
916 // As the invoice amt is above all channels' inbound capacity, they will still be included
917 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
918 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
919 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
921 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
923 // An invoice with no specified amount should include all channels in the route hints.
924 let mut scid_aliases_no_specified_amount = HashSet::new();
925 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
926 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
928 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
931 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
932 invoice_amt: Option<u64>,
933 invoice_node: &Node<'a, 'b, 'c>,
934 mut chan_ids_to_match: HashSet<u64>
936 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
937 &invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
938 Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
940 let hints = invoice.private_routes();
943 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
944 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
946 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
950 #[cfg(feature = "std")]
951 fn test_multi_node_receive() {
952 do_test_multi_node_receive(true);
953 do_test_multi_node_receive(false);
956 #[cfg(feature = "std")]
957 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
958 let mut chanmon_cfgs = create_chanmon_cfgs(3);
959 let seed_1 = [42 as u8; 32];
960 let seed_2 = [43 as u8; 32];
961 let cross_node_seed = [44 as u8; 32];
962 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
963 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
964 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
965 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
966 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
967 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
968 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
969 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
970 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
971 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
972 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
974 let payment_amt = 10_000;
975 let route_hints = vec![
976 nodes[1].node.get_phantom_route_hints(),
977 nodes[2].node.get_phantom_route_hints(),
980 let user_payment_preimage = PaymentPreimage([1; 32]);
981 let payment_hash = if user_generated_pmt_hash {
982 Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
986 let non_default_invoice_expiry_secs = 4200;
989 crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
990 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
991 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet
993 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
994 let payment_preimage = if user_generated_pmt_hash {
995 user_payment_preimage
997 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1000 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
1001 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1002 assert_eq!(invoice.route_hints().len(), 2);
1003 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1004 assert!(!invoice.features().unwrap().supports_basic_mpp());
1006 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1007 .with_features(invoice.features().unwrap().clone())
1008 .with_route_hints(invoice.route_hints());
1009 let params = RouteParameters {
1011 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1012 final_cltv_expiry_delta: invoice.min_final_cltv_expiry() as u32,
1014 let first_hops = nodes[0].node.list_usable_channels();
1015 let network_graph = &node_cfgs[0].network_graph;
1016 let logger = test_utils::TestLogger::new();
1017 let scorer = test_utils::TestScorer::with_penalty(0);
1018 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1019 let route = find_route(
1020 &nodes[0].node.get_our_node_id(), ¶ms, &network_graph,
1021 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1023 let (payment_event, fwd_idx) = {
1024 let mut payment_hash = PaymentHash([0; 32]);
1025 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1026 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
1027 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1028 assert_eq!(added_monitors.len(), 1);
1029 added_monitors.clear();
1031 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1032 assert_eq!(events.len(), 1);
1033 let fwd_idx = match events[0] {
1034 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1035 if node_id == nodes[1].node.get_our_node_id() {
1039 _ => panic!("Unexpected event")
1041 (SendEvent::from_event(events.remove(0)), fwd_idx)
1043 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1044 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1046 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1047 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1048 // payments "look real" by taking more time.
1049 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1050 nodes[fwd_idx].node.process_pending_htlc_forwards();
1051 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1052 nodes[fwd_idx].node.process_pending_htlc_forwards();
1054 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1055 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1056 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
1057 let events = nodes[0].node.get_and_clear_pending_events();
1058 assert_eq!(events.len(), 2);
1060 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1061 assert_eq!(payment_preimage, *ev_preimage);
1062 assert_eq!(payment_hash, *ev_hash);
1063 assert_eq!(fee_paid_msat, &Some(0));
1065 _ => panic!("Unexpected event")
1068 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1069 assert_eq!(hash, Some(payment_hash));
1071 _ => panic!("Unexpected event")
1076 #[cfg(feature = "std")]
1077 fn test_multi_node_hints_has_htlc_min_max_values() {
1078 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1079 let seed_1 = [42 as u8; 32];
1080 let seed_2 = [43 as u8; 32];
1081 let cross_node_seed = [44 as u8; 32];
1082 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1083 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1084 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1085 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1086 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1088 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1089 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1091 let payment_amt = 20_000;
1092 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
1093 let route_hints = vec![
1094 nodes[1].node.get_phantom_route_hints(),
1095 nodes[2].node.get_phantom_route_hints(),
1098 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash), "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet).unwrap();
1100 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1101 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1102 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1104 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1105 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1106 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1110 #[cfg(feature = "std")]
1111 fn create_phantom_invoice_with_description_hash() {
1112 let chanmon_cfgs = create_chanmon_cfgs(3);
1113 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1114 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1115 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1117 let payment_amt = 20_000;
1118 let route_hints = vec![
1119 nodes[1].node.get_phantom_route_hints(),
1120 nodes[2].node.get_phantom_route_hints(),
1123 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1124 let non_default_invoice_expiry_secs = 4200;
1125 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1126 &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1128 Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1129 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger, Currency::BitcoinTestnet
1132 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1133 assert_eq!(invoice.min_final_cltv_expiry(), MIN_FINAL_CLTV_EXPIRY as u64);
1134 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1135 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1139 #[cfg(feature = "std")]
1140 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1141 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1142 let seed_1 = [42 as u8; 32];
1143 let seed_2 = [43 as u8; 32];
1144 let cross_node_seed = [44 as u8; 32];
1145 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1146 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1147 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1148 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1149 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1151 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1152 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1154 let mut scid_aliases = HashSet::new();
1155 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1156 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1158 match_multi_node_invoice_routes(
1161 vec![&nodes[1], &nodes[2],],
1168 #[cfg(feature = "std")]
1169 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1170 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1171 let seed_1 = [42 as u8; 32];
1172 let seed_2 = [43 as u8; 32];
1173 let cross_node_seed = [44 as u8; 32];
1174 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1175 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1176 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1177 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1178 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1180 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1181 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1182 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1184 let mut scid_aliases = HashSet::new();
1185 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1186 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1187 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1189 match_multi_node_invoice_routes(
1192 vec![&nodes[2], &nodes[3],],
1199 #[cfg(feature = "std")]
1200 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1201 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1202 let seed_1 = [42 as u8; 32];
1203 let seed_2 = [43 as u8; 32];
1204 let cross_node_seed = [44 as u8; 32];
1205 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1206 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1207 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1208 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1209 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1211 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1212 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1214 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1215 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1216 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1217 let mut private_chan_cfg = UserConfig::default();
1218 private_chan_cfg.channel_handshake_config.announced_channel = false;
1219 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();
1220 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1221 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1222 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1223 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1225 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1227 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1228 confirm_transaction_at(&nodes[1], &tx, conf_height);
1229 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1230 confirm_transaction_at(&nodes[3], &tx, conf_height);
1231 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1232 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1233 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()));
1234 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1235 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1236 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1237 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1238 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1240 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1241 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1242 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1243 let mut scid_aliases = HashSet::new();
1244 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1245 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1247 match_multi_node_invoice_routes(
1250 vec![&nodes[2], &nodes[3],],
1257 #[cfg(feature = "std")]
1258 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1259 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1260 let seed_1 = [42 as u8; 32];
1261 let seed_2 = [43 as u8; 32];
1262 let cross_node_seed = [44 as u8; 32];
1263 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1264 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1265 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1266 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1267 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1269 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1271 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1272 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1273 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1275 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1276 // `chan_0_2` as `nodes[2]` only has public channels.
1277 let mut scid_aliases = HashSet::new();
1278 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1280 match_multi_node_invoice_routes(
1283 vec![&nodes[1], &nodes[2],],
1290 #[cfg(feature = "std")]
1291 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1292 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1293 let seed_1 = [42 as u8; 32];
1294 let seed_2 = [43 as u8; 32];
1295 let cross_node_seed = [44 as u8; 32];
1296 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1297 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1298 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1299 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1300 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1302 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1303 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1304 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1305 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1307 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1309 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1310 // channels for `nodes[2]` as it contains a mix of public and private channels.
1311 let mut scid_aliases = HashSet::new();
1312 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1314 match_multi_node_invoice_routes(
1317 vec![&nodes[2], &nodes[3],],
1324 #[cfg(feature = "std")]
1325 fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1326 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1327 let seed_1 = [42 as u8; 32];
1328 let seed_2 = [43 as u8; 32];
1329 let cross_node_seed = [44 as u8; 32];
1330 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1331 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1332 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1333 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1334 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1336 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1337 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
1338 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1339 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1341 let mut scid_aliases = HashSet::new();
1342 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1343 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1345 match_multi_node_invoice_routes(
1348 vec![&nodes[1], &nodes[2],],
1355 #[cfg(feature = "std")]
1356 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1357 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1358 let seed_1 = [42 as u8; 32];
1359 let seed_2 = [43 as u8; 32];
1360 let cross_node_seed = [44 as u8; 32];
1361 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1362 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1363 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1364 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1365 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1367 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1368 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1369 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1371 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1372 let mut scid_aliases_99_000_001_msat = HashSet::new();
1373 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1374 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1376 match_multi_node_invoice_routes(
1379 vec![&nodes[2], &nodes[3],],
1380 scid_aliases_99_000_001_msat,
1384 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1385 let mut scid_aliases_99_000_000_msat = HashSet::new();
1386 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1387 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1388 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1390 match_multi_node_invoice_routes(
1393 vec![&nodes[2], &nodes[3],],
1394 scid_aliases_99_000_000_msat,
1398 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1399 // `nodes[2]` them should be included.
1400 let mut scid_aliases_300_000_000_msat = HashSet::new();
1401 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1402 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1403 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1405 match_multi_node_invoice_routes(
1408 vec![&nodes[2], &nodes[3],],
1409 scid_aliases_300_000_000_msat,
1413 // Since the no specified amount, all channels should included.
1414 let mut scid_aliases_no_specified_amount = HashSet::new();
1415 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1416 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1417 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1419 match_multi_node_invoice_routes(
1422 vec![&nodes[2], &nodes[3],],
1423 scid_aliases_no_specified_amount,
1428 #[cfg(feature = "std")]
1429 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1430 invoice_amt: Option<u64>,
1431 invoice_node: &Node<'a, 'b, 'c>,
1432 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1433 mut chan_ids_to_match: HashSet<u64>,
1434 nodes_contains_public_channels: bool
1436 let phantom_route_hints = network_multi_nodes.iter()
1437 .map(|node| node.node.get_phantom_route_hints())
1438 .collect::<Vec<PhantomRouteHints>>();
1439 let phantom_scids = phantom_route_hints.iter()
1440 .map(|route_hint| route_hint.phantom_scid)
1441 .collect::<HashSet<u64>>();
1443 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(), 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.keys_manager, &invoice_node.logger, Currency::BitcoinTestnet).unwrap();
1445 let invoice_hints = invoice.private_routes();
1447 for hint in invoice_hints {
1448 let hints = &(hint.0).0;
1451 assert!(nodes_contains_public_channels);
1452 let phantom_scid = hints[0].short_channel_id;
1453 assert!(phantom_scids.contains(&phantom_scid));
1456 let hint_short_chan_id = hints[0].short_channel_id;
1457 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1458 let phantom_scid = hints[1].short_channel_id;
1459 assert!(phantom_scids.contains(&phantom_scid));
1461 _ => panic!("Incorrect hint length generated")
1464 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);