1 //! Convenient utilities to create an invoice.
3 use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
5 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
7 use bitcoin_hashes::Hash;
9 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
10 use lightning::chain::keysinterface::{Recipient, NodeSigner, SignerProvider, EntropySource};
11 use lightning::ln::{PaymentHash, PaymentSecret};
12 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, MIN_FINAL_CLTV_EXPIRY_DELTA};
13 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
14 use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
15 use lightning::routing::gossip::RoutingFees;
16 use lightning::routing::router::{RouteHint, RouteHintHop, Router};
17 use lightning::util::logger::Logger;
18 use secp256k1::PublicKey;
20 use core::time::Duration;
22 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
23 /// See [`PhantomKeysManager`] for more information on phantom node payments.
25 /// `phantom_route_hints` parameter:
26 /// * Contains channel info for all nodes participating in the phantom invoice
27 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
28 /// participating node
29 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
30 /// updated when a channel becomes disabled or closes
31 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
32 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
35 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
36 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
37 /// If `None` is provided for `payment_hash`, then one will be created.
39 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
40 /// in excess of the current time.
42 /// `duration_since_epoch` is the current time since epoch in seconds.
44 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
45 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3.
46 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
47 /// confirmations during routing.
49 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
50 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
53 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
54 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
55 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
56 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
57 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
58 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
60 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
61 /// available and the current time is supplied by the caller.
62 pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
63 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
64 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
65 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
66 ) -> Result<Invoice, SignOrCreationError<()>>
68 ES::Target: EntropySource,
69 NS::Target: NodeSigner,
72 let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
73 let description = InvoiceDescription::Direct(&description,);
74 _create_phantom_invoice::<ES, NS, L>(
75 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
76 entropy_source, node_signer, logger, network, min_final_cltv_expiry_delta, duration_since_epoch,
80 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
81 /// See [`PhantomKeysManager`] for more information on phantom node payments.
83 /// `phantom_route_hints` parameter:
84 /// * Contains channel info for all nodes participating in the phantom invoice
85 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
86 /// participating node
87 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
88 /// updated when a channel becomes disabled or closes
89 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
90 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
93 /// `description_hash` is a SHA-256 hash of the description text
95 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
96 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
97 /// If `None` is provided for `payment_hash`, then one will be created.
99 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
100 /// in excess of the current time.
102 /// `duration_since_epoch` is the current time since epoch in seconds.
104 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
105 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
108 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
109 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
110 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
111 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
112 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
114 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
115 /// available and the current time is supplied by the caller.
116 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
117 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
118 description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
119 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
120 ) -> Result<Invoice, SignOrCreationError<()>>
122 ES::Target: EntropySource,
123 NS::Target: NodeSigner,
126 _create_phantom_invoice::<ES, NS, L>(
127 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
128 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
129 min_final_cltv_expiry_delta, duration_since_epoch,
133 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
134 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
135 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
136 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
137 ) -> Result<Invoice, SignOrCreationError<()>>
139 ES::Target: EntropySource,
140 NS::Target: NodeSigner,
144 if phantom_route_hints.is_empty() {
145 return Err(SignOrCreationError::CreationError(
146 CreationError::MissingRouteHints,
150 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
151 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
154 let invoice = match description {
155 InvoiceDescription::Direct(description) => {
156 InvoiceBuilder::new(network).description(description.0.clone())
158 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
161 // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
162 let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
163 let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
164 let payment_secret = create_from_hash(
168 invoice_expiry_delta_secs,
171 min_final_cltv_expiry_delta,
173 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
174 (payment_hash, payment_secret)
179 invoice_expiry_delta_secs,
183 min_final_cltv_expiry_delta,
185 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
188 log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
189 phantom_route_hints.len(), log_bytes!(payment_hash.0));
191 let mut invoice = invoice
192 .duration_since_epoch(duration_since_epoch)
193 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
194 .payment_secret(payment_secret)
195 .min_final_cltv_expiry_delta(
196 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
197 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
198 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
199 if let Some(amt) = amt_msat {
200 invoice = invoice.amount_milli_satoshis(amt);
203 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
204 log_trace!(logger, "Generating phantom route hints for node {}",
205 log_pubkey!(real_node_pubkey));
206 let mut route_hints = filter_channels(channels, amt_msat, &logger);
208 // If we have any public channel, the route hints from `filter_channels` will be empty.
209 // In that case we create a RouteHint on which we will push a single hop with the phantom
210 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
211 // node by looking at our public channels.
212 if route_hints.is_empty() {
213 route_hints.push(RouteHint(vec![]))
215 for mut route_hint in route_hints {
216 route_hint.0.push(RouteHintHop {
217 src_node_id: real_node_pubkey,
218 short_channel_id: phantom_scid,
221 proportional_millionths: 0,
223 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
224 htlc_minimum_msat: None,
225 htlc_maximum_msat: None,});
226 invoice = invoice.private_route(route_hint.clone());
230 let raw_invoice = match invoice.build_raw() {
232 Err(e) => return Err(SignOrCreationError::CreationError(e))
234 let hrp_str = raw_invoice.hrp.to_string();
235 let hrp_bytes = hrp_str.as_bytes();
236 let data_without_signature = raw_invoice.data.to_base32();
237 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
238 match signed_raw_invoice {
239 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
240 Err(e) => Err(SignOrCreationError::SignError(e))
244 #[cfg(feature = "std")]
245 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
246 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
247 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
248 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
249 /// that the payment secret is valid when the invoice is paid.
251 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
252 /// in excess of the current time.
254 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
255 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
256 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
257 /// confirmations during routing.
259 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
260 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
261 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
262 network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
263 min_final_cltv_expiry_delta: Option<u16>,
264 ) -> Result<Invoice, SignOrCreationError<()>>
266 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
267 T::Target: BroadcasterInterface,
268 ES::Target: EntropySource,
269 NS::Target: NodeSigner,
270 SP::Target: SignerProvider,
271 F::Target: FeeEstimator,
275 use std::time::SystemTime;
276 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
277 .expect("for the foreseeable future this shouldn't happen");
278 create_invoice_from_channelmanager_and_duration_since_epoch(
279 channelmanager, node_signer, logger, network, amt_msat,
280 description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
284 #[cfg(feature = "std")]
285 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
286 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
287 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
288 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
289 /// that the payment secret is valid when the invoice is paid.
290 /// Use this variant if you want to pass the `description_hash` to the invoice.
292 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
293 /// in excess of the current time.
295 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
296 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
297 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
298 /// confirmations during routing.
300 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
301 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>(
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 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
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 use std::time::SystemTime;
318 let duration = SystemTime::now()
319 .duration_since(SystemTime::UNIX_EPOCH)
320 .expect("for the foreseeable future this shouldn't happen");
322 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
323 channelmanager, node_signer, logger, network, amt_msat,
324 description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
328 /// See [`create_invoice_from_channelmanager_with_description_hash`]
329 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
330 /// available and the current time is supplied by the caller.
331 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>(
332 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
333 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
334 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
335 ) -> Result<Invoice, SignOrCreationError<()>>
337 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
338 T::Target: BroadcasterInterface,
339 ES::Target: EntropySource,
340 NS::Target: NodeSigner,
341 SP::Target: SignerProvider,
342 F::Target: FeeEstimator,
346 _create_invoice_from_channelmanager_and_duration_since_epoch(
347 channelmanager, node_signer, logger, network, amt_msat,
348 InvoiceDescription::Hash(&description_hash),
349 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
353 /// See [`create_invoice_from_channelmanager`]
354 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
355 /// available and the current time is supplied by the caller.
356 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>(
357 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
358 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
359 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
360 ) -> Result<Invoice, SignOrCreationError<()>>
362 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
363 T::Target: BroadcasterInterface,
364 ES::Target: EntropySource,
365 NS::Target: NodeSigner,
366 SP::Target: SignerProvider,
367 F::Target: FeeEstimator,
371 _create_invoice_from_channelmanager_and_duration_since_epoch(
372 channelmanager, node_signer, logger, network, amt_msat,
373 InvoiceDescription::Direct(
374 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
376 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
380 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>(
381 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
382 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
383 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
384 ) -> Result<Invoice, SignOrCreationError<()>>
386 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
387 T::Target: BroadcasterInterface,
388 ES::Target: EntropySource,
389 NS::Target: NodeSigner,
390 SP::Target: SignerProvider,
391 F::Target: FeeEstimator,
395 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
396 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
399 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
401 let (payment_hash, payment_secret) = channelmanager
402 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs, min_final_cltv_expiry_delta)
403 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
404 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
405 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch,
406 invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta)
409 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
410 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
411 /// This may be useful if you're building an on-chain swap or involving another protocol where
412 /// the payment hash is also involved outside the scope of lightning.
413 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>(
414 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
415 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
416 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
417 ) -> Result<Invoice, SignOrCreationError<()>>
419 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
420 T::Target: BroadcasterInterface,
421 ES::Target: EntropySource,
422 NS::Target: NodeSigner,
423 SP::Target: SignerProvider,
424 F::Target: FeeEstimator,
428 let payment_secret = channelmanager
429 .create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs,
430 min_final_cltv_expiry_delta)
431 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
432 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
433 channelmanager, node_signer, logger, network, amt_msat,
434 InvoiceDescription::Direct(
435 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
437 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret,
438 min_final_cltv_expiry_delta,
442 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>(
443 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
444 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
445 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
446 min_final_cltv_expiry_delta: Option<u16>,
447 ) -> Result<Invoice, SignOrCreationError<()>>
449 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
450 T::Target: BroadcasterInterface,
451 ES::Target: EntropySource,
452 NS::Target: NodeSigner,
453 SP::Target: SignerProvider,
454 F::Target: FeeEstimator,
458 let our_node_pubkey = channelmanager.get_our_node_id();
459 let channels = channelmanager.list_channels();
461 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
462 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
465 log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
467 let invoice = match description {
468 InvoiceDescription::Direct(description) => {
469 InvoiceBuilder::new(network).description(description.0.clone())
471 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
474 let mut invoice = invoice
475 .duration_since_epoch(duration_since_epoch)
476 .payee_pub_key(our_node_pubkey)
477 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
478 .payment_secret(payment_secret)
480 .min_final_cltv_expiry_delta(
481 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
482 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
483 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
484 if let Some(amt) = amt_msat {
485 invoice = invoice.amount_milli_satoshis(amt);
488 let route_hints = filter_channels(channels, amt_msat, &logger);
489 for hint in route_hints {
490 invoice = invoice.private_route(hint);
493 let raw_invoice = match invoice.build_raw() {
495 Err(e) => return Err(SignOrCreationError::CreationError(e))
497 let hrp_str = raw_invoice.hrp.to_string();
498 let hrp_bytes = hrp_str.as_bytes();
499 let data_without_signature = raw_invoice.data.to_base32();
500 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
501 match signed_raw_invoice {
502 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
503 Err(e) => Err(SignOrCreationError::SignError(e))
507 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
510 /// The filtering is based on the following criteria:
511 /// * Only one channel per counterparty node
512 /// * If the counterparty has a channel that is above the `min_inbound_capacity_msat` + 10% scaling
513 /// factor (to allow some margin for change in inbound), select the channel with the lowest
514 /// inbound capacity that is above this threshold.
515 /// * If no `min_inbound_capacity_msat` is specified, or the counterparty has no channels above the
516 /// minimum + 10% scaling factor, select the channel with the highest inbound capacity per counterparty.
517 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
518 /// `is_usable` (i.e. the peer is connected).
519 /// * If any public channel exists, only public [`RouteHint`]s will be returned.
520 /// * If any public, announced, channel exists (i.e. a channel with 7+ confs, to ensure the
521 /// announcement has had a chance to propagate), no [`RouteHint`]s will be returned, as the
522 /// sender is expected to find the path by looking at the public channels instead.
523 fn filter_channels<L: Deref>(
524 channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
525 ) -> Vec<RouteHint> where L::Target: Logger {
526 let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
527 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
528 let mut min_capacity_channel_exists = false;
529 let mut online_channel_exists = false;
530 let mut online_min_capacity_channel_exists = false;
531 let mut has_pub_unconf_chan = false;
533 log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
534 for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
535 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
536 log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
540 if channel.is_public {
541 if channel.confirmations.is_some() && channel.confirmations < Some(7) {
542 // If we have a public channel, but it doesn't have enough confirmations to (yet)
543 // be in the public network graph (and have gotten a chance to propagate), include
544 // route hints but only for public channels to protect private channel privacy.
545 has_pub_unconf_chan = true;
547 // If any public channel exists, return no hints and let the sender
548 // look at the public channels instead.
549 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
550 log_bytes!(channel.channel_id));
555 if channel.inbound_capacity_msat >= min_inbound_capacity {
556 if !min_capacity_channel_exists {
557 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
558 min_capacity_channel_exists = true;
561 if channel.is_usable {
562 online_min_capacity_channel_exists = true;
566 if channel.is_usable && !online_channel_exists {
567 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
568 online_channel_exists = true;
571 match filtered_channels.entry(channel.counterparty.node_id) {
572 hash_map::Entry::Occupied(mut entry) => {
573 let current_max_capacity = entry.get().inbound_capacity_msat;
574 // If this channel is public and the previous channel is not, ensure we replace the
575 // previous channel to avoid announcing non-public channels.
576 let new_now_public = channel.is_public && !entry.get().is_public;
577 // Decide whether we prefer the currently selected channel with the node to the new one,
578 // based on their inbound capacity.
579 let prefer_current = prefer_current_channel(min_inbound_capacity_msat, current_max_capacity,
580 channel.inbound_capacity_msat);
581 // If the public-ness of the channel has not changed (in which case simply defer to
582 // `new_now_public), and this channel has more desirable inbound than the incumbent,
583 // prefer to include this channel.
584 let new_channel_preferable = channel.is_public == entry.get().is_public && !prefer_current;
586 if new_now_public || new_channel_preferable {
588 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
589 log_pubkey!(channel.counterparty.node_id),
590 log_bytes!(channel.channel_id), channel.short_channel_id,
591 channel.inbound_capacity_msat,
592 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
593 current_max_capacity);
594 entry.insert(channel);
597 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
598 log_pubkey!(channel.counterparty.node_id),
599 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
600 current_max_capacity,
601 log_bytes!(channel.channel_id), channel.short_channel_id,
602 channel.inbound_capacity_msat);
605 hash_map::Entry::Vacant(entry) => {
606 entry.insert(channel);
611 let route_hint_from_channel = |channel: ChannelDetails| {
612 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
613 RouteHint(vec![RouteHintHop {
614 src_node_id: channel.counterparty.node_id,
615 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
617 base_msat: forwarding_info.fee_base_msat,
618 proportional_millionths: forwarding_info.fee_proportional_millionths,
620 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
621 htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
622 htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
624 // If all channels are private, prefer to return route hints which have a higher capacity than
625 // the payment value and where we're currently connected to the channel counterparty.
626 // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
627 // those which meet at least one criteria.
630 .map(|(_, channel)| channel)
632 let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
633 let include_channel = if has_pub_unconf_chan {
634 // If we have a public channel, but it doesn't have enough confirmations to (yet)
635 // be in the public network graph (and have gotten a chance to propagate), include
636 // route hints but only for public channels to protect private channel privacy.
638 } else if online_min_capacity_channel_exists {
639 has_enough_capacity && channel.is_usable
640 } else if min_capacity_channel_exists && online_channel_exists {
641 // If there are some online channels and some min_capacity channels, but no
642 // online-and-min_capacity channels, just include the min capacity ones and ignore
645 } else if min_capacity_channel_exists {
647 } else if online_channel_exists {
652 log_trace!(logger, "Including channel {} in invoice route hints",
653 log_bytes!(channel.channel_id));
654 } else if !has_enough_capacity {
655 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
656 log_bytes!(channel.channel_id));
658 debug_assert!(!channel.is_usable || (has_pub_unconf_chan && !channel.is_public));
659 log_trace!(logger, "Ignoring channel {} with disconnected peer",
660 log_bytes!(channel.channel_id));
665 .map(route_hint_from_channel)
666 .collect::<Vec<RouteHint>>()
669 /// prefer_current_channel chooses a channel to use for route hints between a currently selected and candidate
670 /// channel based on the inbound capacity of each channel and the minimum inbound capacity requested for the hints,
671 /// returning true if the current channel should be preferred over the candidate channel.
672 /// * If no minimum amount is requested, the channel with the most inbound is chosen to maximize the chances that a
673 /// payment of any size will succeed.
674 /// * If we have channels with inbound above our minimum requested inbound (plus a 10% scaling factor, expressed as a
675 /// percentage) then we choose the lowest inbound channel with above this amount. If we have sufficient inbound
676 /// channels, we don't want to deplete our larger channels with small payments (the off-chain version of "grinding
678 /// * If no channel above our minimum amount exists, then we just prefer the channel with the most inbound to give
679 /// payments the best chance of succeeding in multiple parts.
680 fn prefer_current_channel(min_inbound_capacity_msat: Option<u64>, current_channel: u64,
681 candidate_channel: u64) -> bool {
683 // If no min amount is given for the hints, err of the side of caution and choose the largest channel inbound to
684 // maximize chances of any payment succeeding.
685 if min_inbound_capacity_msat.is_none() {
686 return current_channel > candidate_channel
689 let scaled_min_inbound = min_inbound_capacity_msat.unwrap() * 110;
690 let current_sufficient = current_channel * 100 >= scaled_min_inbound;
691 let candidate_sufficient = candidate_channel * 100 >= scaled_min_inbound;
693 if current_sufficient && candidate_sufficient {
694 return current_channel < candidate_channel
695 } else if current_sufficient {
697 } else if candidate_sufficient {
701 current_channel > candidate_channel
706 use core::time::Duration;
707 use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
708 use bitcoin_hashes::{Hash, sha256};
709 use bitcoin_hashes::sha256::Hash as Sha256;
710 use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
711 use lightning::events::{MessageSendEvent, MessageSendEventsProvider, Event};
712 use lightning::ln::{PaymentPreimage, PaymentHash};
713 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
714 use lightning::ln::functional_test_utils::*;
715 use lightning::ln::msgs::ChannelMessageHandler;
716 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
717 use lightning::util::test_utils;
718 use lightning::util::config::UserConfig;
719 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
720 use std::collections::HashSet;
723 fn test_prefer_current_channel() {
724 // No minimum, prefer larger candidate channel.
725 assert_eq!(crate::utils::prefer_current_channel(None, 100, 200), false);
727 // No minimum, prefer larger current channel.
728 assert_eq!(crate::utils::prefer_current_channel(None, 200, 100), true);
730 // Minimum set, prefer current channel over minimum + buffer.
731 assert_eq!(crate::utils::prefer_current_channel(Some(100), 115, 100), true);
733 // Minimum set, prefer candidate channel over minimum + buffer.
734 assert_eq!(crate::utils::prefer_current_channel(Some(100), 105, 125), false);
736 // Minimum set, both channels sufficient, prefer smaller current channel.
737 assert_eq!(crate::utils::prefer_current_channel(Some(100), 115, 125), true);
739 // Minimum set, both channels sufficient, prefer smaller candidate channel.
740 assert_eq!(crate::utils::prefer_current_channel(Some(100), 200, 160), false);
742 // Minimum set, neither sufficient, prefer larger current channel.
743 assert_eq!(crate::utils::prefer_current_channel(Some(200), 100, 50), true);
745 // Minimum set, neither sufficient, prefer larger candidate channel.
746 assert_eq!(crate::utils::prefer_current_channel(Some(200), 100, 150), false);
751 fn test_from_channelmanager() {
752 let chanmon_cfgs = create_chanmon_cfgs(2);
753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
755 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
756 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
757 let non_default_invoice_expiry_secs = 4200;
758 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
759 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
760 Some(10_000), "test".to_string(), Duration::from_secs(1234567),
761 non_default_invoice_expiry_secs, None).unwrap();
762 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
763 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
764 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
765 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
766 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
768 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
770 let chan = &nodes[1].node.list_usable_channels()[0];
771 assert_eq!(invoice.route_hints().len(), 1);
772 assert_eq!(invoice.route_hints()[0].0.len(), 1);
773 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
775 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
776 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
778 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
779 invoice.min_final_cltv_expiry_delta() as u32)
780 .with_features(invoice.features().unwrap().clone())
781 .with_route_hints(invoice.route_hints());
782 let route_params = RouteParameters {
784 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
786 let first_hops = nodes[0].node.list_usable_channels();
787 let network_graph = &node_cfgs[0].network_graph;
788 let logger = test_utils::TestLogger::new();
789 let scorer = test_utils::TestScorer::new();
790 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
791 let route = find_route(
792 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
793 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
796 let payment_event = {
797 let mut payment_hash = PaymentHash([0; 32]);
798 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
799 nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
800 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
801 assert_eq!(added_monitors.len(), 1);
802 added_monitors.clear();
804 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
805 assert_eq!(events.len(), 1);
806 SendEvent::from_event(events.remove(0))
809 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
810 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
811 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
812 assert_eq!(added_monitors.len(), 1);
813 added_monitors.clear();
814 let events = nodes[1].node.get_and_clear_pending_msg_events();
815 assert_eq!(events.len(), 2);
818 fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
819 let chanmon_cfgs = create_chanmon_cfgs(2);
820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
823 let custom_min_final_cltv_expiry_delta = Some(50);
825 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
826 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
827 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
828 if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
830 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
831 custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
835 fn test_create_invoice_custom_min_final_cltv_delta() {
836 do_create_invoice_min_final_cltv_delta(true);
837 do_create_invoice_min_final_cltv_delta(false);
841 fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
842 let chanmon_cfgs = create_chanmon_cfgs(2);
843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
846 let custom_min_final_cltv_expiry_delta = Some(21);
848 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
849 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
850 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
851 custom_min_final_cltv_expiry_delta,
853 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
857 fn test_create_invoice_with_description_hash() {
858 let chanmon_cfgs = create_chanmon_cfgs(2);
859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
862 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
863 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
864 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
865 Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
867 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
868 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
869 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
873 fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
874 let chanmon_cfgs = create_chanmon_cfgs(2);
875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
877 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
878 let payment_hash = PaymentHash([0; 32]);
879 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
880 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
881 Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
884 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
885 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
886 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
887 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
891 fn test_hints_has_only_public_confd_channels() {
892 let chanmon_cfgs = create_chanmon_cfgs(2);
893 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
894 let mut config = test_default_channel_config();
895 config.channel_handshake_config.minimum_depth = 1;
896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
899 // Create a private channel with lots of capacity and a lower value public channel (without
900 // confirming the funding tx yet).
901 let unannounced_scid = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
902 let conf_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 10_000, 0);
904 // Before the channel is available, we should include the unannounced_scid.
905 let mut scid_aliases = HashSet::new();
906 scid_aliases.insert(unannounced_scid.0.short_channel_id_alias.unwrap());
907 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
909 // However after we mine the funding tx and exchange channel_ready messages for the public
910 // channel we'll immediately switch to including it as a route hint, even though it isn't
912 let pub_channel_scid = mine_transaction(&nodes[0], &conf_tx);
913 let node_a_pub_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
914 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &node_a_pub_channel_ready);
916 assert_eq!(mine_transaction(&nodes[1], &conf_tx), pub_channel_scid);
917 let events = nodes[1].node.get_and_clear_pending_msg_events();
918 assert_eq!(events.len(), 2);
919 if let MessageSendEvent::SendChannelReady { msg, .. } = &events[0] {
920 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), msg);
922 if let MessageSendEvent::SendChannelUpdate { msg, .. } = &events[1] {
923 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), msg);
926 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id()));
928 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
929 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
931 scid_aliases.clear();
932 scid_aliases.insert(node_a_pub_channel_ready.short_channel_id_alias.unwrap());
933 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
934 // This also applies even if the amount is more than the payment amount, to ensure users
935 // dont screw up their privacy.
936 match_invoice_routes(Some(50_000_000), &nodes[1], scid_aliases.clone());
938 // The same remains true until the channel has 7 confirmations, at which point we include
940 connect_blocks(&nodes[1], 5);
941 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
942 connect_blocks(&nodes[1], 1);
943 get_event_msg!(nodes[1], MessageSendEvent::SendAnnouncementSignatures, nodes[0].node.get_our_node_id());
944 match_invoice_routes(Some(5000), &nodes[1], HashSet::new());
948 fn test_hints_includes_single_channels_to_nodes() {
949 let chanmon_cfgs = create_chanmon_cfgs(3);
950 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
951 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
952 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
954 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
955 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
957 let mut scid_aliases = HashSet::new();
958 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
959 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
961 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
965 fn test_hints_has_only_lowest_inbound_capacity_channel_above_minimum() {
966 let chanmon_cfgs = create_chanmon_cfgs(2);
967 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
968 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
969 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
971 let _chan_1_0_inbound_below_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000, 0);
972 let _chan_1_0_large_inbound_above_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 500_000, 0);
973 let chan_1_0_low_inbound_above_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 200_000, 0);
975 let mut scid_aliases = HashSet::new();
976 scid_aliases.insert(chan_1_0_low_inbound_above_amt.0.short_channel_id_alias.unwrap());
977 match_invoice_routes(Some(100_000_000), &nodes[0], scid_aliases);
981 fn test_hints_has_only_online_channels() {
982 let chanmon_cfgs = create_chanmon_cfgs(4);
983 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
984 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
985 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
986 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
987 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
988 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
990 // With all peers connected we should get all hints that have sufficient value
991 let mut scid_aliases = HashSet::new();
992 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
993 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
995 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
997 // With only one sufficient-value peer connected we should only get its hint
998 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
999 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
1000 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1002 // If we don't have any sufficient-value peers connected we should get all hints with
1003 // sufficient value, even though there is a connected insufficient-value peer.
1004 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
1005 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1006 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
1010 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
1011 let chanmon_cfgs = create_chanmon_cfgs(3);
1012 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1013 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1014 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1017 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
1018 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1019 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1020 let mut private_chan_cfg = UserConfig::default();
1021 private_chan_cfg.channel_handshake_config.announced_channel = false;
1022 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();
1023 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
1024 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
1025 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
1026 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
1028 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
1030 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
1031 confirm_transaction_at(&nodes[2], &tx, conf_height);
1032 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
1033 confirm_transaction_at(&nodes[0], &tx, conf_height);
1034 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
1035 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
1036 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()));
1037 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
1038 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
1039 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
1040 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
1041 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
1043 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
1044 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1045 // Therefore only `chan_1_0` should be included in the hints.
1046 let mut scid_aliases = HashSet::new();
1047 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1048 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
1052 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
1053 let chanmon_cfgs = create_chanmon_cfgs(3);
1054 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1055 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1056 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1057 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1059 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1060 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1061 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1063 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
1064 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
1065 // public channel between `nodes[2]` and `nodes[0]`
1066 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1070 fn test_only_public_channels_includes_no_channels_in_hints() {
1071 let chanmon_cfgs = create_chanmon_cfgs(3);
1072 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1073 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1074 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1075 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1076 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
1077 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
1079 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1080 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1081 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1083 // As all of `nodes[0]` channels are public, no channels should be included in the hints
1084 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1088 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
1089 let chanmon_cfgs = create_chanmon_cfgs(3);
1090 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1091 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1092 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1093 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1094 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
1096 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
1097 let mut scid_aliases_99_000_001_msat = HashSet::new();
1098 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1100 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
1102 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
1103 let mut scid_aliases_99_000_000_msat = HashSet::new();
1104 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1105 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1107 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
1109 // As the invoice amt is above all channels' inbound capacity, they will still be included
1110 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
1111 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1112 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1114 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1116 // An invoice with no specified amount should include all channels in the route hints.
1117 let mut scid_aliases_no_specified_amount = HashSet::new();
1118 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1119 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1121 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1124 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1125 invoice_amt: Option<u64>,
1126 invoice_node: &Node<'a, 'b, 'c>,
1127 mut chan_ids_to_match: HashSet<u64>
1129 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
1130 invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
1131 Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
1132 3600, None).unwrap();
1133 let hints = invoice.private_routes();
1136 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
1137 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1139 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1143 #[cfg(feature = "std")]
1144 fn test_multi_node_receive() {
1145 do_test_multi_node_receive(true);
1146 do_test_multi_node_receive(false);
1149 #[cfg(feature = "std")]
1150 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1151 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1152 let seed_1 = [42u8; 32];
1153 let seed_2 = [43u8; 32];
1154 let cross_node_seed = [44u8; 32];
1155 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1156 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1157 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1158 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1159 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1160 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1161 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1162 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1163 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1164 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1165 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1167 let payment_amt = 10_000;
1168 let route_hints = vec![
1169 nodes[1].node.get_phantom_route_hints(),
1170 nodes[2].node.get_phantom_route_hints(),
1173 let user_payment_preimage = PaymentPreimage([1; 32]);
1174 let payment_hash = if user_generated_pmt_hash {
1175 Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1179 let non_default_invoice_expiry_secs = 4200;
1182 crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1183 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1184 route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1185 Currency::BitcoinTestnet, None, Duration::from_secs(1234567)
1187 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1188 let payment_preimage = if user_generated_pmt_hash {
1189 user_payment_preimage
1191 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1194 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1195 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1196 assert_eq!(invoice.route_hints().len(), 2);
1197 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1198 assert!(!invoice.features().unwrap().supports_basic_mpp());
1200 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
1201 invoice.min_final_cltv_expiry_delta() as u32)
1202 .with_features(invoice.features().unwrap().clone())
1203 .with_route_hints(invoice.route_hints());
1204 let params = RouteParameters {
1206 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1208 let first_hops = nodes[0].node.list_usable_channels();
1209 let network_graph = &node_cfgs[0].network_graph;
1210 let logger = test_utils::TestLogger::new();
1211 let scorer = test_utils::TestScorer::new();
1212 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1213 let route = find_route(
1214 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
1215 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1217 let (payment_event, fwd_idx) = {
1218 let mut payment_hash = PaymentHash([0; 32]);
1219 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1220 nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
1221 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1222 assert_eq!(added_monitors.len(), 1);
1223 added_monitors.clear();
1225 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1226 assert_eq!(events.len(), 1);
1227 let fwd_idx = match events[0] {
1228 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1229 if node_id == nodes[1].node.get_our_node_id() {
1233 _ => panic!("Unexpected event")
1235 (SendEvent::from_event(events.remove(0)), fwd_idx)
1237 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1238 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1240 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1241 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1242 // payments "look real" by taking more time.
1243 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1244 nodes[fwd_idx].node.process_pending_htlc_forwards();
1245 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1246 nodes[fwd_idx].node.process_pending_htlc_forwards();
1248 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1249 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1250 do_claim_payment_along_route(&nodes[0], &[&vec!(&nodes[fwd_idx])[..]], false, payment_preimage);
1251 let events = nodes[0].node.get_and_clear_pending_events();
1252 assert_eq!(events.len(), 2);
1254 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1255 assert_eq!(payment_preimage, *ev_preimage);
1256 assert_eq!(payment_hash, *ev_hash);
1257 assert_eq!(fee_paid_msat, &Some(0));
1259 _ => panic!("Unexpected event")
1262 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1263 assert_eq!(hash, Some(payment_hash));
1265 _ => panic!("Unexpected event")
1270 #[cfg(feature = "std")]
1271 fn test_multi_node_hints_has_htlc_min_max_values() {
1272 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1273 let seed_1 = [42u8; 32];
1274 let seed_2 = [43u8; 32];
1275 let cross_node_seed = [44u8; 32];
1276 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1277 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1278 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1279 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1280 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1282 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1283 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1285 let payment_amt = 20_000;
1286 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1287 let route_hints = vec![
1288 nodes[1].node.get_phantom_route_hints(),
1289 nodes[2].node.get_phantom_route_hints(),
1292 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1293 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1294 "test".to_string(), 3600, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1295 nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1297 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1298 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1299 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1301 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1302 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1303 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1307 #[cfg(feature = "std")]
1308 fn create_phantom_invoice_with_description_hash() {
1309 let chanmon_cfgs = create_chanmon_cfgs(3);
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 payment_amt = 20_000;
1315 let route_hints = vec![
1316 nodes[1].node.get_phantom_route_hints(),
1317 nodes[2].node.get_phantom_route_hints(),
1320 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1321 let non_default_invoice_expiry_secs = 4200;
1322 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1323 &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1325 Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1326 route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1327 Currency::BitcoinTestnet, None, Duration::from_secs(1234567),
1330 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1331 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1332 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1333 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1337 #[cfg(feature = "std")]
1338 fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1339 let chanmon_cfgs = create_chanmon_cfgs(3);
1340 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1341 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1342 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1344 let payment_amt = 20_000;
1345 let route_hints = vec![
1346 nodes[1].node.get_phantom_route_hints(),
1347 nodes[2].node.get_phantom_route_hints(),
1349 let user_payment_preimage = PaymentPreimage([1; 32]);
1350 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1351 let non_default_invoice_expiry_secs = 4200;
1352 let min_final_cltv_expiry_delta = Some(100);
1353 let duration_since_epoch = Duration::from_secs(1234567);
1354 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1355 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1356 "".to_string(), non_default_invoice_expiry_secs, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1357 nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap();
1358 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1359 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1360 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1364 #[cfg(feature = "std")]
1365 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1366 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1367 let seed_1 = [42u8; 32];
1368 let seed_2 = [43u8; 32];
1369 let cross_node_seed = [44u8; 32];
1370 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1371 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1372 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1373 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1374 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1376 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1377 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1379 let mut scid_aliases = HashSet::new();
1380 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1381 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1383 match_multi_node_invoice_routes(
1386 vec![&nodes[1], &nodes[2],],
1393 #[cfg(feature = "std")]
1394 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1395 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1396 let seed_1 = [42u8; 32];
1397 let seed_2 = [43u8; 32];
1398 let cross_node_seed = [44u8; 32];
1399 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1400 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1401 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1402 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1403 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1405 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1406 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1407 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1409 let mut scid_aliases = HashSet::new();
1410 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1411 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1412 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1414 match_multi_node_invoice_routes(
1417 vec![&nodes[2], &nodes[3],],
1424 #[cfg(feature = "std")]
1425 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1426 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1427 let seed_1 = [42u8; 32];
1428 let seed_2 = [43u8; 32];
1429 let cross_node_seed = [44u8; 32];
1430 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1431 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1432 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1433 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1434 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1436 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1437 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1439 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1440 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1441 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1442 let mut private_chan_cfg = UserConfig::default();
1443 private_chan_cfg.channel_handshake_config.announced_channel = false;
1444 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();
1445 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1446 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1447 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1448 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1450 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1452 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1453 confirm_transaction_at(&nodes[1], &tx, conf_height);
1454 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1455 confirm_transaction_at(&nodes[3], &tx, conf_height);
1456 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1457 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1458 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()));
1459 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1460 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1461 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1462 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1463 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1465 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1466 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1467 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1468 let mut scid_aliases = HashSet::new();
1469 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1470 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1472 match_multi_node_invoice_routes(
1475 vec![&nodes[2], &nodes[3],],
1482 #[cfg(feature = "std")]
1483 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1484 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1485 let seed_1 = [42u8; 32];
1486 let seed_2 = [43u8; 32];
1487 let cross_node_seed = [44u8; 32];
1488 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1489 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1490 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1491 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1492 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1494 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1496 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1497 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1498 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1500 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1501 // `chan_0_2` as `nodes[2]` only has public channels.
1502 let mut scid_aliases = HashSet::new();
1503 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1505 match_multi_node_invoice_routes(
1508 vec![&nodes[1], &nodes[2],],
1515 #[cfg(feature = "std")]
1516 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1517 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1518 let seed_1 = [42u8; 32];
1519 let seed_2 = [43u8; 32];
1520 let cross_node_seed = [44u8; 32];
1521 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1522 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1523 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1524 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1525 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1527 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1528 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1529 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1530 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1532 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1534 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1535 // channels for `nodes[2]` as it contains a mix of public and private channels.
1536 let mut scid_aliases = HashSet::new();
1537 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1539 match_multi_node_invoice_routes(
1542 vec![&nodes[2], &nodes[3],],
1549 #[cfg(feature = "std")]
1550 fn test_multi_node_hints_has_only_lowest_inbound_channel_above_minimum() {
1551 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1552 let seed_1 = [42u8; 32];
1553 let seed_2 = [43u8; 32];
1554 let cross_node_seed = [44u8; 32];
1555 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1556 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1557 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1558 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1559 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1561 let _chan_0_1_below_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1562 let _chan_0_1_above_amt_high_inbound = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 500_000, 0);
1563 let chan_0_1_above_amt_low_inbound = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 180_000, 0);
1564 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1566 let mut scid_aliases = HashSet::new();
1567 scid_aliases.insert(chan_0_1_above_amt_low_inbound.0.short_channel_id_alias.unwrap());
1568 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1570 match_multi_node_invoice_routes(
1573 vec![&nodes[1], &nodes[2],],
1580 #[cfg(feature = "std")]
1581 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1582 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1583 let seed_1 = [42u8; 32];
1584 let seed_2 = [43u8; 32];
1585 let cross_node_seed = [44u8; 32];
1586 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1587 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1588 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1589 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1590 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1592 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1593 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1594 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1596 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1597 let mut scid_aliases_99_000_001_msat = HashSet::new();
1598 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1599 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1601 match_multi_node_invoice_routes(
1604 vec![&nodes[2], &nodes[3],],
1605 scid_aliases_99_000_001_msat,
1609 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1610 let mut scid_aliases_99_000_000_msat = HashSet::new();
1611 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1612 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1613 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1615 match_multi_node_invoice_routes(
1618 vec![&nodes[2], &nodes[3],],
1619 scid_aliases_99_000_000_msat,
1623 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1624 // `nodes[2]` them should be included.
1625 let mut scid_aliases_300_000_000_msat = HashSet::new();
1626 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1627 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1628 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1630 match_multi_node_invoice_routes(
1633 vec![&nodes[2], &nodes[3],],
1634 scid_aliases_300_000_000_msat,
1638 // Since the no specified amount, all channels should included.
1639 let mut scid_aliases_no_specified_amount = HashSet::new();
1640 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1641 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1642 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1644 match_multi_node_invoice_routes(
1647 vec![&nodes[2], &nodes[3],],
1648 scid_aliases_no_specified_amount,
1653 #[cfg(feature = "std")]
1654 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1655 invoice_amt: Option<u64>,
1656 invoice_node: &Node<'a, 'b, 'c>,
1657 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1658 mut chan_ids_to_match: HashSet<u64>,
1659 nodes_contains_public_channels: bool
1661 let phantom_route_hints = network_multi_nodes.iter()
1662 .map(|node| node.node.get_phantom_route_hints())
1663 .collect::<Vec<PhantomRouteHints>>();
1664 let phantom_scids = phantom_route_hints.iter()
1665 .map(|route_hint| route_hint.phantom_scid)
1666 .collect::<HashSet<u64>>();
1668 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1669 &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1670 3600, phantom_route_hints, invoice_node.keys_manager, invoice_node.keys_manager,
1671 invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1673 let invoice_hints = invoice.private_routes();
1675 for hint in invoice_hints {
1676 let hints = &(hint.0).0;
1679 assert!(nodes_contains_public_channels);
1680 let phantom_scid = hints[0].short_channel_id;
1681 assert!(phantom_scids.contains(&phantom_scid));
1684 let hint_short_chan_id = hints[0].short_channel_id;
1685 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1686 let phantom_scid = hints[1].short_channel_id;
1687 assert!(phantom_scids.contains(&phantom_scid));
1689 _ => panic!("Incorrect hint length generated")
1692 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1696 fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1697 let chanmon_cfgs = create_chanmon_cfgs(2);
1698 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1699 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1700 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1701 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1702 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1703 Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1706 Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},