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_DELTA};
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 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
46 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3.
47 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
48 /// confirmations during routing.
50 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
51 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
54 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
55 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
56 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
57 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
58 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
59 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
60 pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
61 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
62 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
63 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>,
64 ) -> Result<Invoice, SignOrCreationError<()>>
66 ES::Target: EntropySource,
67 NS::Target: NodeSigner,
70 let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
71 let description = InvoiceDescription::Direct(&description,);
72 _create_phantom_invoice::<ES, NS, L>(
73 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
74 entropy_source, node_signer, logger, network, min_final_cltv_expiry_delta,
78 #[cfg(feature = "std")]
79 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
80 /// See [`PhantomKeysManager`] for more information on phantom node payments.
82 /// `phantom_route_hints` parameter:
83 /// * Contains channel info for all nodes participating in the phantom invoice
84 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
85 /// participating node
86 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
87 /// updated when a channel becomes disabled or closes
88 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
89 /// may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
92 /// `description_hash` is a SHA-256 hash of the description text
94 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
95 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
96 /// If `None` is provided for `payment_hash`, then one will be created.
98 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
99 /// in excess of the current time.
101 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
102 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
105 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
106 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
107 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
108 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
109 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
110 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
111 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
112 description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
113 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>,
114 ) -> Result<Invoice, SignOrCreationError<()>>
116 ES::Target: EntropySource,
117 NS::Target: NodeSigner,
120 _create_phantom_invoice::<ES, NS, L>(
121 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
122 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
123 min_final_cltv_expiry_delta,
127 #[cfg(feature = "std")]
128 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
129 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
130 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
131 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>,
132 ) -> Result<Invoice, SignOrCreationError<()>>
134 ES::Target: EntropySource,
135 NS::Target: NodeSigner,
138 use std::time::{SystemTime, UNIX_EPOCH};
140 if phantom_route_hints.len() == 0 {
141 return Err(SignOrCreationError::CreationError(
142 CreationError::MissingRouteHints,
146 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
147 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
150 let invoice = match description {
151 InvoiceDescription::Direct(description) => {
152 InvoiceBuilder::new(network).description(description.0.clone())
154 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
157 // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
158 let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
159 let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
160 let payment_secret = create_from_hash(
164 invoice_expiry_delta_secs,
166 .duration_since(UNIX_EPOCH)
167 .expect("Time must be > 1970")
170 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
171 (payment_hash, payment_secret)
176 invoice_expiry_delta_secs,
179 .duration_since(UNIX_EPOCH)
180 .expect("Time must be > 1970")
183 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
186 log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
187 phantom_route_hints.len(), log_bytes!(payment_hash.0));
189 let mut invoice = invoice
191 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
192 .payment_secret(payment_secret)
193 .min_final_cltv_expiry_delta(
194 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
195 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
196 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
197 if let Some(amt) = amt_msat {
198 invoice = invoice.amount_milli_satoshis(amt);
201 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
202 log_trace!(logger, "Generating phantom route hints for node {}",
203 log_pubkey!(real_node_pubkey));
204 let mut route_hints = filter_channels(channels, amt_msat, &logger);
206 // If we have any public channel, the route hints from `filter_channels` will be empty.
207 // In that case we create a RouteHint on which we will push a single hop with the phantom
208 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
209 // node by looking at our public channels.
210 if route_hints.is_empty() {
211 route_hints.push(RouteHint(vec![]))
213 for mut route_hint in route_hints {
214 route_hint.0.push(RouteHintHop {
215 src_node_id: real_node_pubkey,
216 short_channel_id: phantom_scid,
219 proportional_millionths: 0,
221 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
222 htlc_minimum_msat: None,
223 htlc_maximum_msat: None,});
224 invoice = invoice.private_route(route_hint.clone());
228 let raw_invoice = match invoice.build_raw() {
230 Err(e) => return Err(SignOrCreationError::CreationError(e))
232 let hrp_str = raw_invoice.hrp.to_string();
233 let hrp_bytes = hrp_str.as_bytes();
234 let data_without_signature = raw_invoice.data.to_base32();
235 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
236 match signed_raw_invoice {
237 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
238 Err(e) => Err(SignOrCreationError::SignError(e))
242 #[cfg(feature = "std")]
243 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
244 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
245 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
246 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
247 /// that the payment secret is valid when the invoice is paid.
249 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
250 /// in excess of the current time.
252 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
253 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
254 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
255 /// confirmations during routing.
257 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
258 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
259 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
260 network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
261 min_final_cltv_expiry_delta: Option<u16>,
262 ) -> Result<Invoice, SignOrCreationError<()>>
264 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
265 T::Target: BroadcasterInterface,
266 ES::Target: EntropySource,
267 NS::Target: NodeSigner,
268 SP::Target: SignerProvider,
269 F::Target: FeeEstimator,
273 use std::time::SystemTime;
274 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
275 .expect("for the foreseeable future this shouldn't happen");
276 create_invoice_from_channelmanager_and_duration_since_epoch(
277 channelmanager, node_signer, logger, network, amt_msat,
278 description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
282 #[cfg(feature = "std")]
283 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
284 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
285 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
286 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
287 /// that the payment secret is valid when the invoice is paid.
288 /// Use this variant if you want to pass the `description_hash` to the invoice.
290 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
291 /// in excess of the current time.
293 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
294 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
295 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
296 /// confirmations during routing.
298 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
299 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>(
300 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
301 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
302 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
303 ) -> Result<Invoice, SignOrCreationError<()>>
305 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
306 T::Target: BroadcasterInterface,
307 ES::Target: EntropySource,
308 NS::Target: NodeSigner,
309 SP::Target: SignerProvider,
310 F::Target: FeeEstimator,
314 use std::time::SystemTime;
316 let duration = SystemTime::now()
317 .duration_since(SystemTime::UNIX_EPOCH)
318 .expect("for the foreseeable future this shouldn't happen");
320 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
321 channelmanager, node_signer, logger, network, amt_msat,
322 description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
326 /// See [`create_invoice_from_channelmanager_with_description_hash`]
327 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
328 /// available and the current time is supplied by the caller.
329 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>(
330 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
331 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
332 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
333 ) -> Result<Invoice, SignOrCreationError<()>>
335 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
336 T::Target: BroadcasterInterface,
337 ES::Target: EntropySource,
338 NS::Target: NodeSigner,
339 SP::Target: SignerProvider,
340 F::Target: FeeEstimator,
344 _create_invoice_from_channelmanager_and_duration_since_epoch(
345 channelmanager, node_signer, logger, network, amt_msat,
346 InvoiceDescription::Hash(&description_hash),
347 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
351 /// See [`create_invoice_from_channelmanager`]
352 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
353 /// available and the current time is supplied by the caller.
354 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>(
355 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
356 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
357 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
358 ) -> Result<Invoice, SignOrCreationError<()>>
360 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
361 T::Target: BroadcasterInterface,
362 ES::Target: EntropySource,
363 NS::Target: NodeSigner,
364 SP::Target: SignerProvider,
365 F::Target: FeeEstimator,
369 _create_invoice_from_channelmanager_and_duration_since_epoch(
370 channelmanager, node_signer, logger, network, amt_msat,
371 InvoiceDescription::Direct(
372 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
374 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
378 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>(
379 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
380 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
381 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
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 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
394 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
397 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
399 let (payment_hash, payment_secret) = channelmanager
400 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs)
401 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
402 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
403 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch,
404 invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta)
407 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
408 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
409 /// This may be useful if you're building an on-chain swap or involving another protocol where
410 /// the payment hash is also involved outside the scope of lightning.
411 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>(
412 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
413 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
414 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
415 ) -> Result<Invoice, SignOrCreationError<()>>
417 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
418 T::Target: BroadcasterInterface,
419 ES::Target: EntropySource,
420 NS::Target: NodeSigner,
421 SP::Target: SignerProvider,
422 F::Target: FeeEstimator,
426 let payment_secret = channelmanager
427 .create_inbound_payment_for_hash(payment_hash,amt_msat, invoice_expiry_delta_secs)
428 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
429 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
430 channelmanager, node_signer, logger, network, amt_msat,
431 InvoiceDescription::Direct(
432 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
434 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret,
435 min_final_cltv_expiry_delta,
439 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>(
440 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
441 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
442 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
443 min_final_cltv_expiry_delta: Option<u16>,
444 ) -> Result<Invoice, SignOrCreationError<()>>
446 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
447 T::Target: BroadcasterInterface,
448 ES::Target: EntropySource,
449 NS::Target: NodeSigner,
450 SP::Target: SignerProvider,
451 F::Target: FeeEstimator,
455 let our_node_pubkey = channelmanager.get_our_node_id();
456 let channels = channelmanager.list_channels();
458 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
459 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
462 log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
464 let invoice = match description {
465 InvoiceDescription::Direct(description) => {
466 InvoiceBuilder::new(network).description(description.0.clone())
468 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
471 let mut invoice = invoice
472 .duration_since_epoch(duration_since_epoch)
473 .payee_pub_key(our_node_pubkey)
474 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
475 .payment_secret(payment_secret)
477 .min_final_cltv_expiry_delta(
478 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
479 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
480 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
481 if let Some(amt) = amt_msat {
482 invoice = invoice.amount_milli_satoshis(amt);
485 let route_hints = filter_channels(channels, amt_msat, &logger);
486 for hint in route_hints {
487 invoice = invoice.private_route(hint);
490 let raw_invoice = match invoice.build_raw() {
492 Err(e) => return Err(SignOrCreationError::CreationError(e))
494 let hrp_str = raw_invoice.hrp.to_string();
495 let hrp_bytes = hrp_str.as_bytes();
496 let data_without_signature = raw_invoice.data.to_base32();
497 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
498 match signed_raw_invoice {
499 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
500 Err(e) => Err(SignOrCreationError::SignError(e))
504 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
507 /// The filtering is based on the following criteria:
508 /// * Only one channel per counterparty node
509 /// * Always select the channel with the highest inbound capacity per counterparty node
510 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
511 /// `is_usable` (i.e. the peer is connected).
512 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
513 /// need to find the path by looking at the public channels instead
514 fn filter_channels<L: Deref>(
515 channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
516 ) -> Vec<RouteHint> where L::Target: Logger {
517 let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
518 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
519 let mut min_capacity_channel_exists = false;
520 let mut online_channel_exists = false;
521 let mut online_min_capacity_channel_exists = false;
523 log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
524 for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
525 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
526 log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
530 if channel.is_public {
531 // If any public channel exists, return no hints and let the sender
532 // look at the public channels instead.
533 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
534 log_bytes!(channel.channel_id));
538 if channel.inbound_capacity_msat >= min_inbound_capacity {
539 if !min_capacity_channel_exists {
540 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
541 min_capacity_channel_exists = true;
544 if channel.is_usable {
545 online_min_capacity_channel_exists = true;
549 if channel.is_usable {
550 if !online_channel_exists {
551 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
552 online_channel_exists = true;
556 match filtered_channels.entry(channel.counterparty.node_id) {
557 hash_map::Entry::Occupied(mut entry) => {
558 let current_max_capacity = entry.get().inbound_capacity_msat;
559 if channel.inbound_capacity_msat < current_max_capacity {
561 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
562 log_pubkey!(channel.counterparty.node_id),
563 log_bytes!(entry.get().channel_id), current_max_capacity,
564 log_bytes!(channel.channel_id), channel.inbound_capacity_msat);
568 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
569 log_pubkey!(channel.counterparty.node_id),
570 log_bytes!(channel.channel_id), channel.inbound_capacity_msat,
571 log_bytes!(entry.get().channel_id), current_max_capacity);
572 entry.insert(channel);
574 hash_map::Entry::Vacant(entry) => {
575 entry.insert(channel);
580 let route_hint_from_channel = |channel: ChannelDetails| {
581 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
582 RouteHint(vec![RouteHintHop {
583 src_node_id: channel.counterparty.node_id,
584 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
586 base_msat: forwarding_info.fee_base_msat,
587 proportional_millionths: forwarding_info.fee_proportional_millionths,
589 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
590 htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
591 htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
593 // If all channels are private, prefer to return route hints which have a higher capacity than
594 // the payment value and where we're currently connected to the channel counterparty.
595 // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
596 // those which meet at least one criteria.
599 .map(|(_, channel)| channel)
601 let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
602 let include_channel = if online_min_capacity_channel_exists {
603 has_enough_capacity && channel.is_usable
604 } else if min_capacity_channel_exists && online_channel_exists {
605 // If there are some online channels and some min_capacity channels, but no
606 // online-and-min_capacity channels, just include the min capacity ones and ignore
609 } else if min_capacity_channel_exists {
611 } else if online_channel_exists {
616 log_trace!(logger, "Including channel {} in invoice route hints",
617 log_bytes!(channel.channel_id));
618 } else if !has_enough_capacity {
619 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
620 log_bytes!(channel.channel_id));
622 debug_assert!(!channel.is_usable);
623 log_trace!(logger, "Ignoring channel {} with disconnected peer",
624 log_bytes!(channel.channel_id));
629 .map(route_hint_from_channel)
630 .collect::<Vec<RouteHint>>()
633 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>
635 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
636 T::Target: BroadcasterInterface,
637 ES::Target: EntropySource,
638 NS::Target: NodeSigner,
639 SP::Target: SignerProvider,
640 F::Target: FeeEstimator,
644 fn node_id(&self) -> PublicKey {
645 self.get_our_node_id()
648 fn first_hops(&self) -> Vec<ChannelDetails> {
649 self.list_usable_channels()
653 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
654 payment_id: PaymentId
655 ) -> Result<(), PaymentSendFailure> {
656 self.send_payment(route, payment_hash, payment_secret, payment_id)
659 fn send_spontaneous_payment(
660 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
661 ) -> Result<(), PaymentSendFailure> {
662 self.send_spontaneous_payment(route, Some(payment_preimage), payment_id).map(|_| ())
666 &self, route: &Route, payment_id: PaymentId
667 ) -> Result<(), PaymentSendFailure> {
668 self.retry_payment(route, payment_id)
671 fn abandon_payment(&self, payment_id: PaymentId) {
672 self.abandon_payment(payment_id)
675 fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() }
680 use core::time::Duration;
681 use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
682 use bitcoin_hashes::{Hash, sha256};
683 use bitcoin_hashes::sha256::Hash as Sha256;
684 use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
685 use lightning::ln::{PaymentPreimage, PaymentHash};
686 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
687 use lightning::ln::functional_test_utils::*;
688 use lightning::ln::msgs::ChannelMessageHandler;
689 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
690 use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
691 use lightning::util::test_utils;
692 use lightning::util::config::UserConfig;
693 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
694 use std::collections::HashSet;
697 fn test_from_channelmanager() {
698 let chanmon_cfgs = create_chanmon_cfgs(2);
699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
702 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
703 let non_default_invoice_expiry_secs = 4200;
704 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
705 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
706 Some(10_000), "test".to_string(), Duration::from_secs(1234567),
707 non_default_invoice_expiry_secs, None).unwrap();
708 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
709 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
710 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
711 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
712 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
714 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
716 let chan = &nodes[1].node.list_usable_channels()[0];
717 assert_eq!(invoice.route_hints().len(), 1);
718 assert_eq!(invoice.route_hints()[0].0.len(), 1);
719 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
721 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
722 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
724 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
725 .with_features(invoice.features().unwrap().clone())
726 .with_route_hints(invoice.route_hints());
727 let route_params = RouteParameters {
729 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
730 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
732 let first_hops = nodes[0].node.list_usable_channels();
733 let network_graph = &node_cfgs[0].network_graph;
734 let logger = test_utils::TestLogger::new();
735 let scorer = test_utils::TestScorer::with_penalty(0);
736 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
737 let route = find_route(
738 &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
739 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
742 let payment_event = {
743 let mut payment_hash = PaymentHash([0; 32]);
744 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
745 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
746 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
747 assert_eq!(added_monitors.len(), 1);
748 added_monitors.clear();
750 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
751 assert_eq!(events.len(), 1);
752 SendEvent::from_event(events.remove(0))
755 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
756 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
757 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
758 assert_eq!(added_monitors.len(), 1);
759 added_monitors.clear();
760 let events = nodes[1].node.get_and_clear_pending_msg_events();
761 assert_eq!(events.len(), 2);
764 fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
765 let chanmon_cfgs = create_chanmon_cfgs(2);
766 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
767 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
768 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
769 let custom_min_final_cltv_expiry_delta = Some(50);
771 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
772 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
773 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
774 if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
776 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
777 custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
781 fn test_create_invoice_custom_min_final_cltv_delta() {
782 do_create_invoice_min_final_cltv_delta(true);
783 do_create_invoice_min_final_cltv_delta(false);
787 fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
788 let chanmon_cfgs = create_chanmon_cfgs(2);
789 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
790 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
791 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
792 let custom_min_final_cltv_expiry_delta = Some(21);
794 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
795 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
796 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
797 custom_min_final_cltv_expiry_delta,
799 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
803 fn test_create_invoice_with_description_hash() {
804 let chanmon_cfgs = create_chanmon_cfgs(2);
805 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
806 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
807 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
808 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
809 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
810 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
811 Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
813 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
814 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
815 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
819 fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
820 let chanmon_cfgs = create_chanmon_cfgs(2);
821 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
822 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
823 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
824 let payment_hash = PaymentHash([0; 32]);
825 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
826 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
827 Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
830 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
831 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
832 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
833 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
837 fn test_hints_includes_single_channels_to_nodes() {
838 let chanmon_cfgs = create_chanmon_cfgs(3);
839 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
840 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
841 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
843 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
844 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
846 let mut scid_aliases = HashSet::new();
847 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
848 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
850 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
854 fn test_hints_has_only_highest_inbound_capacity_channel() {
855 let chanmon_cfgs = create_chanmon_cfgs(2);
856 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
857 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
858 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
859 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
860 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
861 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0);
862 let mut scid_aliases = HashSet::new();
863 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
864 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
868 fn test_hints_has_only_online_channels() {
869 let chanmon_cfgs = create_chanmon_cfgs(4);
870 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
871 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
872 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
873 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
874 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
875 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
877 // With all peers connected we should get all hints that have sufficient value
878 let mut scid_aliases = HashSet::new();
879 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
880 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
882 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
884 // With only one sufficient-value peer connected we should only get its hint
885 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
886 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
887 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
889 // If we don't have any sufficient-value peers connected we should get all hints with
890 // sufficient value, even though there is a connected insufficient-value peer.
891 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
892 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
893 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
897 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
898 let chanmon_cfgs = create_chanmon_cfgs(3);
899 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
900 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
901 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
902 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
904 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
905 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
906 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
907 let mut private_chan_cfg = UserConfig::default();
908 private_chan_cfg.channel_handshake_config.announced_channel = false;
909 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();
910 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
911 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
912 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
913 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
915 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
917 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
918 confirm_transaction_at(&nodes[2], &tx, conf_height);
919 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
920 confirm_transaction_at(&nodes[0], &tx, conf_height);
921 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
922 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
923 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()));
924 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
925 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
926 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
927 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
928 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
930 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
931 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
932 // Therefore only `chan_1_0` should be included in the hints.
933 let mut scid_aliases = HashSet::new();
934 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
935 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
939 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
940 let chanmon_cfgs = create_chanmon_cfgs(3);
941 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
942 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
943 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
944 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
946 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
947 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
948 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
950 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
951 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
952 // public channel between `nodes[2]` and `nodes[0]`
953 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
957 fn test_only_public_channels_includes_no_channels_in_hints() {
958 let chanmon_cfgs = create_chanmon_cfgs(3);
959 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
960 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
961 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
962 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
963 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
964 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
966 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
967 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
968 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
970 // As all of `nodes[0]` channels are public, no channels should be included in the hints
971 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
975 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
976 let chanmon_cfgs = create_chanmon_cfgs(3);
977 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
978 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
979 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
980 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
981 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
983 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
984 let mut scid_aliases_99_000_001_msat = HashSet::new();
985 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
987 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
989 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
990 let mut scid_aliases_99_000_000_msat = HashSet::new();
991 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
992 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
994 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
996 // As the invoice amt is above all channels' inbound capacity, they will still be included
997 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
998 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
999 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1001 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1003 // An invoice with no specified amount should include all channels in the route hints.
1004 let mut scid_aliases_no_specified_amount = HashSet::new();
1005 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1006 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1008 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1011 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1012 invoice_amt: Option<u64>,
1013 invoice_node: &Node<'a, 'b, 'c>,
1014 mut chan_ids_to_match: HashSet<u64>
1016 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
1017 &invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
1018 Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
1019 3600, None).unwrap();
1020 let hints = invoice.private_routes();
1023 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
1024 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1026 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1030 #[cfg(feature = "std")]
1031 fn test_multi_node_receive() {
1032 do_test_multi_node_receive(true);
1033 do_test_multi_node_receive(false);
1036 #[cfg(feature = "std")]
1037 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1038 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1039 let seed_1 = [42 as u8; 32];
1040 let seed_2 = [43 as u8; 32];
1041 let cross_node_seed = [44 as u8; 32];
1042 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1043 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1044 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1045 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1046 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1047 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1048 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1049 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1050 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1051 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1052 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1054 let payment_amt = 10_000;
1055 let route_hints = vec![
1056 nodes[1].node.get_phantom_route_hints(),
1057 nodes[2].node.get_phantom_route_hints(),
1060 let user_payment_preimage = PaymentPreimage([1; 32]);
1061 let payment_hash = if user_generated_pmt_hash {
1062 Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1066 let non_default_invoice_expiry_secs = 4200;
1069 crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1070 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1071 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1072 Currency::BitcoinTestnet, None,
1074 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1075 let payment_preimage = if user_generated_pmt_hash {
1076 user_payment_preimage
1078 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1081 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1082 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1083 assert_eq!(invoice.route_hints().len(), 2);
1084 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1085 assert!(!invoice.features().unwrap().supports_basic_mpp());
1087 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key())
1088 .with_features(invoice.features().unwrap().clone())
1089 .with_route_hints(invoice.route_hints());
1090 let params = RouteParameters {
1092 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1093 final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
1095 let first_hops = nodes[0].node.list_usable_channels();
1096 let network_graph = &node_cfgs[0].network_graph;
1097 let logger = test_utils::TestLogger::new();
1098 let scorer = test_utils::TestScorer::with_penalty(0);
1099 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1100 let route = find_route(
1101 &nodes[0].node.get_our_node_id(), ¶ms, &network_graph,
1102 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1104 let (payment_event, fwd_idx) = {
1105 let mut payment_hash = PaymentHash([0; 32]);
1106 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1107 nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
1108 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1109 assert_eq!(added_monitors.len(), 1);
1110 added_monitors.clear();
1112 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1113 assert_eq!(events.len(), 1);
1114 let fwd_idx = match events[0] {
1115 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1116 if node_id == nodes[1].node.get_our_node_id() {
1120 _ => panic!("Unexpected event")
1122 (SendEvent::from_event(events.remove(0)), fwd_idx)
1124 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1125 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1127 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1128 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1129 // payments "look real" by taking more time.
1130 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1131 nodes[fwd_idx].node.process_pending_htlc_forwards();
1132 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1133 nodes[fwd_idx].node.process_pending_htlc_forwards();
1135 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1136 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1137 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
1138 let events = nodes[0].node.get_and_clear_pending_events();
1139 assert_eq!(events.len(), 2);
1141 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1142 assert_eq!(payment_preimage, *ev_preimage);
1143 assert_eq!(payment_hash, *ev_hash);
1144 assert_eq!(fee_paid_msat, &Some(0));
1146 _ => panic!("Unexpected event")
1149 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1150 assert_eq!(hash, Some(payment_hash));
1152 _ => panic!("Unexpected event")
1157 #[cfg(feature = "std")]
1158 fn test_multi_node_hints_has_htlc_min_max_values() {
1159 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1160 let seed_1 = [42 as u8; 32];
1161 let seed_2 = [43 as u8; 32];
1162 let cross_node_seed = [44 as u8; 32];
1163 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1164 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1165 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1166 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1167 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1169 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1170 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1172 let payment_amt = 20_000;
1173 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600).unwrap();
1174 let route_hints = vec![
1175 nodes[1].node.get_phantom_route_hints(),
1176 nodes[2].node.get_phantom_route_hints(),
1179 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1180 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1181 "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1182 &nodes[1].logger, Currency::BitcoinTestnet, None).unwrap();
1184 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1185 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1186 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1188 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1189 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1190 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1194 #[cfg(feature = "std")]
1195 fn create_phantom_invoice_with_description_hash() {
1196 let chanmon_cfgs = create_chanmon_cfgs(3);
1197 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1198 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1199 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1201 let payment_amt = 20_000;
1202 let route_hints = vec![
1203 nodes[1].node.get_phantom_route_hints(),
1204 nodes[2].node.get_phantom_route_hints(),
1207 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1208 let non_default_invoice_expiry_secs = 4200;
1209 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1210 &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1212 Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1213 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1214 Currency::BitcoinTestnet, None,
1217 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1218 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1219 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1220 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1224 #[cfg(feature = "std")]
1225 fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1226 let chanmon_cfgs = create_chanmon_cfgs(3);
1227 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1228 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1229 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1231 let payment_amt = 20_000;
1232 let route_hints = vec![
1233 nodes[1].node.get_phantom_route_hints(),
1234 nodes[2].node.get_phantom_route_hints(),
1236 let user_payment_preimage = PaymentPreimage([1; 32]);
1237 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1238 let non_default_invoice_expiry_secs = 4200;
1239 let min_final_cltv_expiry_delta = Some(100);
1240 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1241 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1242 "".to_string(), non_default_invoice_expiry_secs, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1243 &nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta).unwrap();
1244 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1245 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1246 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1250 #[cfg(feature = "std")]
1251 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1252 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1253 let seed_1 = [42 as u8; 32];
1254 let seed_2 = [43 as u8; 32];
1255 let cross_node_seed = [44 as u8; 32];
1256 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1257 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1258 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1259 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1260 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1262 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1263 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1265 let mut scid_aliases = HashSet::new();
1266 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1267 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1269 match_multi_node_invoice_routes(
1272 vec![&nodes[1], &nodes[2],],
1279 #[cfg(feature = "std")]
1280 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1281 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1282 let seed_1 = [42 as u8; 32];
1283 let seed_2 = [43 as u8; 32];
1284 let cross_node_seed = [44 as u8; 32];
1285 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1286 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1287 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1288 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1289 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1291 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1292 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1293 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1295 let mut scid_aliases = HashSet::new();
1296 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1297 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1298 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1300 match_multi_node_invoice_routes(
1303 vec![&nodes[2], &nodes[3],],
1310 #[cfg(feature = "std")]
1311 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1312 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1313 let seed_1 = [42 as u8; 32];
1314 let seed_2 = [43 as u8; 32];
1315 let cross_node_seed = [44 as u8; 32];
1316 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1317 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1318 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1319 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1320 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1322 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1323 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1325 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1326 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1327 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1328 let mut private_chan_cfg = UserConfig::default();
1329 private_chan_cfg.channel_handshake_config.announced_channel = false;
1330 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();
1331 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1332 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1333 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1334 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1336 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1338 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1339 confirm_transaction_at(&nodes[1], &tx, conf_height);
1340 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1341 confirm_transaction_at(&nodes[3], &tx, conf_height);
1342 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1343 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1344 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()));
1345 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1346 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1347 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1348 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1349 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1351 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1352 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1353 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1354 let mut scid_aliases = HashSet::new();
1355 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1356 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1358 match_multi_node_invoice_routes(
1361 vec![&nodes[2], &nodes[3],],
1368 #[cfg(feature = "std")]
1369 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1370 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1371 let seed_1 = [42 as u8; 32];
1372 let seed_2 = [43 as u8; 32];
1373 let cross_node_seed = [44 as u8; 32];
1374 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1375 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1376 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1377 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1378 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1380 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1382 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1383 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1384 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1386 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1387 // `chan_0_2` as `nodes[2]` only has public channels.
1388 let mut scid_aliases = HashSet::new();
1389 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1391 match_multi_node_invoice_routes(
1394 vec![&nodes[1], &nodes[2],],
1401 #[cfg(feature = "std")]
1402 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1403 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1404 let seed_1 = [42 as u8; 32];
1405 let seed_2 = [43 as u8; 32];
1406 let cross_node_seed = [44 as u8; 32];
1407 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1408 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1409 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1410 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1411 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1413 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1414 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1415 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1416 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1418 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1420 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1421 // channels for `nodes[2]` as it contains a mix of public and private channels.
1422 let mut scid_aliases = HashSet::new();
1423 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1425 match_multi_node_invoice_routes(
1428 vec![&nodes[2], &nodes[3],],
1435 #[cfg(feature = "std")]
1436 fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1437 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1438 let seed_1 = [42 as u8; 32];
1439 let seed_2 = [43 as u8; 32];
1440 let cross_node_seed = [44 as u8; 32];
1441 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1442 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1443 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1444 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1445 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1447 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1448 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
1449 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1450 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1452 let mut scid_aliases = HashSet::new();
1453 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1454 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1456 match_multi_node_invoice_routes(
1459 vec![&nodes[1], &nodes[2],],
1466 #[cfg(feature = "std")]
1467 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1468 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1469 let seed_1 = [42 as u8; 32];
1470 let seed_2 = [43 as u8; 32];
1471 let cross_node_seed = [44 as u8; 32];
1472 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1473 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1474 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1475 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1476 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1478 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1479 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1480 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1482 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1483 let mut scid_aliases_99_000_001_msat = HashSet::new();
1484 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1485 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1487 match_multi_node_invoice_routes(
1490 vec![&nodes[2], &nodes[3],],
1491 scid_aliases_99_000_001_msat,
1495 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1496 let mut scid_aliases_99_000_000_msat = HashSet::new();
1497 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1498 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1499 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1501 match_multi_node_invoice_routes(
1504 vec![&nodes[2], &nodes[3],],
1505 scid_aliases_99_000_000_msat,
1509 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1510 // `nodes[2]` them should be included.
1511 let mut scid_aliases_300_000_000_msat = HashSet::new();
1512 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1513 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1514 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1516 match_multi_node_invoice_routes(
1519 vec![&nodes[2], &nodes[3],],
1520 scid_aliases_300_000_000_msat,
1524 // Since the no specified amount, all channels should included.
1525 let mut scid_aliases_no_specified_amount = HashSet::new();
1526 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1527 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1528 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1530 match_multi_node_invoice_routes(
1533 vec![&nodes[2], &nodes[3],],
1534 scid_aliases_no_specified_amount,
1539 #[cfg(feature = "std")]
1540 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1541 invoice_amt: Option<u64>,
1542 invoice_node: &Node<'a, 'b, 'c>,
1543 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1544 mut chan_ids_to_match: HashSet<u64>,
1545 nodes_contains_public_channels: bool
1547 let phantom_route_hints = network_multi_nodes.iter()
1548 .map(|node| node.node.get_phantom_route_hints())
1549 .collect::<Vec<PhantomRouteHints>>();
1550 let phantom_scids = phantom_route_hints.iter()
1551 .map(|route_hint| route_hint.phantom_scid)
1552 .collect::<HashSet<u64>>();
1554 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1555 &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1556 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.keys_manager,
1557 &invoice_node.logger, Currency::BitcoinTestnet, None).unwrap();
1559 let invoice_hints = invoice.private_routes();
1561 for hint in invoice_hints {
1562 let hints = &(hint.0).0;
1565 assert!(nodes_contains_public_channels);
1566 let phantom_scid = hints[0].short_channel_id;
1567 assert!(phantom_scids.contains(&phantom_scid));
1570 let hint_short_chan_id = hints[0].short_channel_id;
1571 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1572 let phantom_scid = hints[1].short_channel_id;
1573 assert!(phantom_scids.contains(&phantom_scid));
1575 _ => panic!("Incorrect hint length generated")
1578 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1582 fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1583 let chanmon_cfgs = create_chanmon_cfgs(2);
1584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1587 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1588 &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1589 Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1592 Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},