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 the route hints generated from `phantom_route_hints` will be limited to a maximum
90 /// of 3 hints to ensure that the invoice can be scanned in a QR code. These hints are selected
91 /// in the order that the nodes in `PhantomRouteHints` are specified, selecting one hint per node
92 /// until the maximum is hit. Callers may provide as many `PhantomRouteHints::channels` as
93 /// desired, but note that some nodes will be trimmed if more than 3 nodes are provided.
95 /// `description_hash` is a SHA-256 hash of the description text
97 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
98 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
99 /// If `None` is provided for `payment_hash`, then one will be created.
101 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
102 /// in excess of the current time.
104 /// `duration_since_epoch` is the current time since epoch in seconds.
106 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
107 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
110 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
111 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
112 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
113 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
114 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
116 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
117 /// available and the current time is supplied by the caller.
118 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
119 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
120 description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
121 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
122 ) -> Result<Invoice, SignOrCreationError<()>>
124 ES::Target: EntropySource,
125 NS::Target: NodeSigner,
128 _create_phantom_invoice::<ES, NS, L>(
129 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
130 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
131 min_final_cltv_expiry_delta, duration_since_epoch,
135 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
136 amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
137 invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
138 node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
139 ) -> Result<Invoice, SignOrCreationError<()>>
141 ES::Target: EntropySource,
142 NS::Target: NodeSigner,
146 if phantom_route_hints.is_empty() {
147 return Err(SignOrCreationError::CreationError(
148 CreationError::MissingRouteHints,
152 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
153 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
156 let invoice = match description {
157 InvoiceDescription::Direct(description) => {
158 InvoiceBuilder::new(network).description(description.0.clone())
160 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
163 // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
164 let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
165 let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
166 let payment_secret = create_from_hash(
170 invoice_expiry_delta_secs,
173 min_final_cltv_expiry_delta,
175 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
176 (payment_hash, payment_secret)
181 invoice_expiry_delta_secs,
185 min_final_cltv_expiry_delta,
187 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
190 log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
191 phantom_route_hints.len(), log_bytes!(payment_hash.0));
193 let mut invoice = invoice
194 .duration_since_epoch(duration_since_epoch)
195 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
196 .payment_secret(payment_secret)
197 .min_final_cltv_expiry_delta(
198 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
199 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
200 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
201 if let Some(amt) = amt_msat {
202 invoice = invoice.amount_milli_satoshis(amt);
205 for route_hint in select_phantom_hints(amt_msat, phantom_route_hints, logger) {
206 invoice = invoice.private_route(route_hint);
209 let raw_invoice = match invoice.build_raw() {
211 Err(e) => return Err(SignOrCreationError::CreationError(e))
213 let hrp_str = raw_invoice.hrp.to_string();
214 let hrp_bytes = hrp_str.as_bytes();
215 let data_without_signature = raw_invoice.data.to_base32();
216 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
217 match signed_raw_invoice {
218 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
219 Err(e) => Err(SignOrCreationError::SignError(e))
223 /// Utility to select route hints for phantom invoices.
224 /// See [`PhantomKeysManager`] for more information on phantom node payments.
226 /// To ensure that the phantom invoice is still readable by QR code, we limit to 3 hints per invoice:
227 /// * Select up to three channels per node.
228 /// * Select one hint from each node, up to three hints or until we run out of hints.
230 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
231 fn select_phantom_hints<L: Deref>(amt_msat: Option<u64>, phantom_route_hints: Vec<PhantomRouteHints>,
232 logger: L) -> Vec<RouteHint>
236 let mut phantom_hints: Vec<Vec<RouteHint>> = Vec::new();
238 for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
239 log_trace!(logger, "Generating phantom route hints for node {}",
240 log_pubkey!(real_node_pubkey));
241 let mut route_hints = sort_and_filter_channels(channels, amt_msat, &logger);
243 // If we have any public channel, the route hints from `sort_and_filter_channels` will be
244 // empty. In that case we create a RouteHint on which we will push a single hop with the
245 // phantom route into the invoice, and let the sender find the path to the `real_node_pubkey`
246 // node by looking at our public channels.
247 if route_hints.is_empty() {
248 route_hints.push(RouteHint(vec![]))
250 for route_hint in &mut route_hints {
251 route_hint.0.push(RouteHintHop {
252 src_node_id: real_node_pubkey,
253 short_channel_id: phantom_scid,
256 proportional_millionths: 0,
258 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
259 htlc_minimum_msat: None,
260 htlc_maximum_msat: None,});
263 phantom_hints.push(route_hints);
266 // We have one vector per real node involved in creating the phantom invoice. To distribute
267 // the hints across our real nodes we add one hint from each in turn until no node has any hints
268 // left (if one node has more hints than any other, these will accumulate at the end of the
270 let mut invoice_hints: Vec<RouteHint> = Vec::new();
271 let mut hint_idx = 0;
274 let mut remaining_hints = false;
276 for hints in phantom_hints.iter() {
277 if invoice_hints.len() == 3 {
281 if hint_idx < hints.len() {
282 invoice_hints.push(hints[hint_idx].clone());
283 remaining_hints = true
287 if !remaining_hints {
295 #[cfg(feature = "std")]
296 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
297 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
298 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
299 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
300 /// that the payment secret is valid when the invoice is paid.
302 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
303 /// in excess of the current time.
305 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
306 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
307 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
308 /// confirmations during routing.
310 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
311 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
312 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
313 network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
314 min_final_cltv_expiry_delta: Option<u16>,
315 ) -> Result<Invoice, SignOrCreationError<()>>
317 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
318 T::Target: BroadcasterInterface,
319 ES::Target: EntropySource,
320 NS::Target: NodeSigner,
321 SP::Target: SignerProvider,
322 F::Target: FeeEstimator,
326 use std::time::SystemTime;
327 let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
328 .expect("for the foreseeable future this shouldn't happen");
329 create_invoice_from_channelmanager_and_duration_since_epoch(
330 channelmanager, node_signer, logger, network, amt_msat,
331 description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
335 #[cfg(feature = "std")]
336 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
337 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
338 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
339 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
340 /// that the payment secret is valid when the invoice is paid.
341 /// Use this variant if you want to pass the `description_hash` to the invoice.
343 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
344 /// in excess of the current time.
346 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
347 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
348 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
349 /// confirmations during routing.
351 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
352 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>(
353 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
354 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
355 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
356 ) -> Result<Invoice, SignOrCreationError<()>>
358 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
359 T::Target: BroadcasterInterface,
360 ES::Target: EntropySource,
361 NS::Target: NodeSigner,
362 SP::Target: SignerProvider,
363 F::Target: FeeEstimator,
367 use std::time::SystemTime;
369 let duration = SystemTime::now()
370 .duration_since(SystemTime::UNIX_EPOCH)
371 .expect("for the foreseeable future this shouldn't happen");
373 create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
374 channelmanager, node_signer, logger, network, amt_msat,
375 description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
379 /// See [`create_invoice_from_channelmanager_with_description_hash`]
380 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
381 /// available and the current time is supplied by the caller.
382 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>(
383 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
384 network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
385 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
386 ) -> Result<Invoice, SignOrCreationError<()>>
388 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
389 T::Target: BroadcasterInterface,
390 ES::Target: EntropySource,
391 NS::Target: NodeSigner,
392 SP::Target: SignerProvider,
393 F::Target: FeeEstimator,
397 _create_invoice_from_channelmanager_and_duration_since_epoch(
398 channelmanager, node_signer, logger, network, amt_msat,
399 InvoiceDescription::Hash(&description_hash),
400 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
404 /// See [`create_invoice_from_channelmanager`]
405 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
406 /// available and the current time is supplied by the caller.
407 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>(
408 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
409 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
410 invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
411 ) -> Result<Invoice, SignOrCreationError<()>>
413 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
414 T::Target: BroadcasterInterface,
415 ES::Target: EntropySource,
416 NS::Target: NodeSigner,
417 SP::Target: SignerProvider,
418 F::Target: FeeEstimator,
422 _create_invoice_from_channelmanager_and_duration_since_epoch(
423 channelmanager, node_signer, logger, network, amt_msat,
424 InvoiceDescription::Direct(
425 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
427 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
431 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>(
432 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
433 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
434 duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
435 ) -> Result<Invoice, SignOrCreationError<()>>
437 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
438 T::Target: BroadcasterInterface,
439 ES::Target: EntropySource,
440 NS::Target: NodeSigner,
441 SP::Target: SignerProvider,
442 F::Target: FeeEstimator,
446 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
447 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
450 // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
452 let (payment_hash, payment_secret) = channelmanager
453 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs, min_final_cltv_expiry_delta)
454 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
455 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
456 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch,
457 invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta)
460 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
461 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
462 /// This may be useful if you're building an on-chain swap or involving another protocol where
463 /// the payment hash is also involved outside the scope of lightning.
464 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>(
465 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
466 network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
467 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
468 ) -> Result<Invoice, SignOrCreationError<()>>
470 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
471 T::Target: BroadcasterInterface,
472 ES::Target: EntropySource,
473 NS::Target: NodeSigner,
474 SP::Target: SignerProvider,
475 F::Target: FeeEstimator,
479 let payment_secret = channelmanager
480 .create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs,
481 min_final_cltv_expiry_delta)
482 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
483 _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
484 channelmanager, node_signer, logger, network, amt_msat,
485 InvoiceDescription::Direct(
486 &Description::new(description).map_err(SignOrCreationError::CreationError)?,
488 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret,
489 min_final_cltv_expiry_delta,
493 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>(
494 channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
495 network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
496 invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
497 min_final_cltv_expiry_delta: Option<u16>,
498 ) -> Result<Invoice, SignOrCreationError<()>>
500 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
501 T::Target: BroadcasterInterface,
502 ES::Target: EntropySource,
503 NS::Target: NodeSigner,
504 SP::Target: SignerProvider,
505 F::Target: FeeEstimator,
509 let our_node_pubkey = channelmanager.get_our_node_id();
510 let channels = channelmanager.list_channels();
512 if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
513 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
516 log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
518 let invoice = match description {
519 InvoiceDescription::Direct(description) => {
520 InvoiceBuilder::new(network).description(description.0.clone())
522 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
525 let mut invoice = invoice
526 .duration_since_epoch(duration_since_epoch)
527 .payee_pub_key(our_node_pubkey)
528 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
529 .payment_secret(payment_secret)
531 .min_final_cltv_expiry_delta(
532 // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
533 min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
534 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
535 if let Some(amt) = amt_msat {
536 invoice = invoice.amount_milli_satoshis(amt);
539 let route_hints = sort_and_filter_channels(channels, amt_msat, &logger);
540 for hint in route_hints {
541 invoice = invoice.private_route(hint);
544 let raw_invoice = match invoice.build_raw() {
546 Err(e) => return Err(SignOrCreationError::CreationError(e))
548 let hrp_str = raw_invoice.hrp.to_string();
549 let hrp_bytes = hrp_str.as_bytes();
550 let data_without_signature = raw_invoice.data.to_base32();
551 let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
552 match signed_raw_invoice {
553 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
554 Err(e) => Err(SignOrCreationError::SignError(e))
558 /// Sorts and filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
561 /// The filtering is based on the following criteria:
562 /// * Only one channel per counterparty node
563 /// * If the counterparty has a channel that is above the `min_inbound_capacity_msat` + 10% scaling
564 /// factor (to allow some margin for change in inbound), select the channel with the lowest
565 /// inbound capacity that is above this threshold.
566 /// * If no `min_inbound_capacity_msat` is specified, or the counterparty has no channels above the
567 /// minimum + 10% scaling factor, select the channel with the highest inbound capacity per counterparty.
568 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
569 /// `is_usable` (i.e. the peer is connected).
570 /// * If any public channel exists, only public [`RouteHint`]s will be returned.
571 /// * If any public, announced, channel exists (i.e. a channel with 7+ confs, to ensure the
572 /// announcement has had a chance to propagate), no [`RouteHint`]s will be returned, as the
573 /// sender is expected to find the path by looking at the public channels instead.
574 /// * Limited to a total of 3 channels.
575 /// * Sorted by lowest inbound capacity if an online channel with the minimum amount requested exists,
576 /// otherwise sort by highest inbound capacity to give the payment the best chance of succeeding.
577 fn sort_and_filter_channels<L: Deref>(
578 channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
579 ) -> Vec<RouteHint> where L::Target: Logger {
580 let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
581 let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
582 let mut min_capacity_channel_exists = false;
583 let mut online_channel_exists = false;
584 let mut online_min_capacity_channel_exists = false;
585 let mut has_pub_unconf_chan = false;
587 log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
588 for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
589 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
590 log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
594 if channel.is_public {
595 if channel.confirmations.is_some() && channel.confirmations < Some(7) {
596 // If we have a public channel, but it doesn't have enough confirmations to (yet)
597 // be in the public network graph (and have gotten a chance to propagate), include
598 // route hints but only for public channels to protect private channel privacy.
599 has_pub_unconf_chan = true;
601 // If any public channel exists, return no hints and let the sender
602 // look at the public channels instead.
603 log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
604 log_bytes!(channel.channel_id));
609 if channel.inbound_capacity_msat >= min_inbound_capacity {
610 if !min_capacity_channel_exists {
611 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
612 min_capacity_channel_exists = true;
615 if channel.is_usable {
616 online_min_capacity_channel_exists = true;
620 if channel.is_usable && !online_channel_exists {
621 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
622 online_channel_exists = true;
625 match filtered_channels.entry(channel.counterparty.node_id) {
626 hash_map::Entry::Occupied(mut entry) => {
627 let current_max_capacity = entry.get().inbound_capacity_msat;
628 // If this channel is public and the previous channel is not, ensure we replace the
629 // previous channel to avoid announcing non-public channels.
630 let new_now_public = channel.is_public && !entry.get().is_public;
631 // Decide whether we prefer the currently selected channel with the node to the new one,
632 // based on their inbound capacity.
633 let prefer_current = prefer_current_channel(min_inbound_capacity_msat, current_max_capacity,
634 channel.inbound_capacity_msat);
635 // If the public-ness of the channel has not changed (in which case simply defer to
636 // `new_now_public), and this channel has more desirable inbound than the incumbent,
637 // prefer to include this channel.
638 let new_channel_preferable = channel.is_public == entry.get().is_public && !prefer_current;
640 if new_now_public || new_channel_preferable {
642 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
643 log_pubkey!(channel.counterparty.node_id),
644 log_bytes!(channel.channel_id), channel.short_channel_id,
645 channel.inbound_capacity_msat,
646 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
647 current_max_capacity);
648 entry.insert(channel);
651 "Preferring counterparty {} channel {} (SCID {:?}, {} msats) over {} (SCID {:?}, {} msats) for invoice route hints",
652 log_pubkey!(channel.counterparty.node_id),
653 log_bytes!(entry.get().channel_id), entry.get().short_channel_id,
654 current_max_capacity,
655 log_bytes!(channel.channel_id), channel.short_channel_id,
656 channel.inbound_capacity_msat);
659 hash_map::Entry::Vacant(entry) => {
660 entry.insert(channel);
665 let route_hint_from_channel = |channel: ChannelDetails| {
666 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
667 RouteHint(vec![RouteHintHop {
668 src_node_id: channel.counterparty.node_id,
669 short_channel_id: channel.get_inbound_payment_scid().unwrap(),
671 base_msat: forwarding_info.fee_base_msat,
672 proportional_millionths: forwarding_info.fee_proportional_millionths,
674 cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
675 htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
676 htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
678 // If all channels are private, prefer to return route hints which have a higher capacity than
679 // the payment value and where we're currently connected to the channel counterparty.
680 // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
681 // those which meet at least one criteria.
682 let mut eligible_channels = filtered_channels
684 .map(|(_, channel)| channel)
686 let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
687 let include_channel = if has_pub_unconf_chan {
688 // If we have a public channel, but it doesn't have enough confirmations to (yet)
689 // be in the public network graph (and have gotten a chance to propagate), include
690 // route hints but only for public channels to protect private channel privacy.
692 } else if online_min_capacity_channel_exists {
693 has_enough_capacity && channel.is_usable
694 } else if min_capacity_channel_exists && online_channel_exists {
695 // If there are some online channels and some min_capacity channels, but no
696 // online-and-min_capacity channels, just include the min capacity ones and ignore
699 } else if min_capacity_channel_exists {
701 } else if online_channel_exists {
706 log_trace!(logger, "Including channel {} in invoice route hints",
707 log_bytes!(channel.channel_id));
708 } else if !has_enough_capacity {
709 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
710 log_bytes!(channel.channel_id));
712 debug_assert!(!channel.is_usable || (has_pub_unconf_chan && !channel.is_public));
713 log_trace!(logger, "Ignoring channel {} with disconnected peer",
714 log_bytes!(channel.channel_id));
719 .collect::<Vec<ChannelDetails>>();
721 eligible_channels.sort_unstable_by(|a, b| {
722 if online_min_capacity_channel_exists {
723 a.inbound_capacity_msat.cmp(&b.inbound_capacity_msat)
725 b.inbound_capacity_msat.cmp(&a.inbound_capacity_msat)
727 eligible_channels.into_iter().take(3).map(route_hint_from_channel).collect::<Vec<RouteHint>>()
730 /// prefer_current_channel chooses a channel to use for route hints between a currently selected and candidate
731 /// channel based on the inbound capacity of each channel and the minimum inbound capacity requested for the hints,
732 /// returning true if the current channel should be preferred over the candidate channel.
733 /// * If no minimum amount is requested, the channel with the most inbound is chosen to maximize the chances that a
734 /// payment of any size will succeed.
735 /// * If we have channels with inbound above our minimum requested inbound (plus a 10% scaling factor, expressed as a
736 /// percentage) then we choose the lowest inbound channel with above this amount. If we have sufficient inbound
737 /// channels, we don't want to deplete our larger channels with small payments (the off-chain version of "grinding
739 /// * If no channel above our minimum amount exists, then we just prefer the channel with the most inbound to give
740 /// payments the best chance of succeeding in multiple parts.
741 fn prefer_current_channel(min_inbound_capacity_msat: Option<u64>, current_channel: u64,
742 candidate_channel: u64) -> bool {
744 // If no min amount is given for the hints, err of the side of caution and choose the largest channel inbound to
745 // maximize chances of any payment succeeding.
746 if min_inbound_capacity_msat.is_none() {
747 return current_channel > candidate_channel
750 let scaled_min_inbound = min_inbound_capacity_msat.unwrap() * 110;
751 let current_sufficient = current_channel * 100 >= scaled_min_inbound;
752 let candidate_sufficient = candidate_channel * 100 >= scaled_min_inbound;
754 if current_sufficient && candidate_sufficient {
755 return current_channel < candidate_channel
756 } else if current_sufficient {
758 } else if candidate_sufficient {
762 current_channel > candidate_channel
767 use core::time::Duration;
768 use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
769 use bitcoin_hashes::{Hash, sha256};
770 use bitcoin_hashes::sha256::Hash as Sha256;
771 use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
772 use lightning::events::{MessageSendEvent, MessageSendEventsProvider, Event};
773 use lightning::ln::{PaymentPreimage, PaymentHash};
774 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
775 use lightning::ln::functional_test_utils::*;
776 use lightning::ln::msgs::ChannelMessageHandler;
777 use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
778 use lightning::util::test_utils;
779 use lightning::util::config::UserConfig;
780 use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
781 use std::collections::HashSet;
784 fn test_prefer_current_channel() {
785 // No minimum, prefer larger candidate channel.
786 assert_eq!(crate::utils::prefer_current_channel(None, 100, 200), false);
788 // No minimum, prefer larger current channel.
789 assert_eq!(crate::utils::prefer_current_channel(None, 200, 100), true);
791 // Minimum set, prefer current channel over minimum + buffer.
792 assert_eq!(crate::utils::prefer_current_channel(Some(100), 115, 100), true);
794 // Minimum set, prefer candidate channel over minimum + buffer.
795 assert_eq!(crate::utils::prefer_current_channel(Some(100), 105, 125), false);
797 // Minimum set, both channels sufficient, prefer smaller current channel.
798 assert_eq!(crate::utils::prefer_current_channel(Some(100), 115, 125), true);
800 // Minimum set, both channels sufficient, prefer smaller candidate channel.
801 assert_eq!(crate::utils::prefer_current_channel(Some(100), 200, 160), false);
803 // Minimum set, neither sufficient, prefer larger current channel.
804 assert_eq!(crate::utils::prefer_current_channel(Some(200), 100, 50), true);
806 // Minimum set, neither sufficient, prefer larger candidate channel.
807 assert_eq!(crate::utils::prefer_current_channel(Some(200), 100, 150), false);
812 fn test_from_channelmanager() {
813 let chanmon_cfgs = create_chanmon_cfgs(2);
814 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
815 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
816 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
817 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
818 let non_default_invoice_expiry_secs = 4200;
819 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
820 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
821 Some(10_000), "test".to_string(), Duration::from_secs(1234567),
822 non_default_invoice_expiry_secs, None).unwrap();
823 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
824 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
825 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
826 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
827 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
829 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
831 let chan = &nodes[1].node.list_usable_channels()[0];
832 assert_eq!(invoice.route_hints().len(), 1);
833 assert_eq!(invoice.route_hints()[0].0.len(), 1);
834 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
836 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
837 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
839 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
840 invoice.min_final_cltv_expiry_delta() as u32)
841 .with_features(invoice.features().unwrap().clone())
842 .with_route_hints(invoice.route_hints());
843 let route_params = RouteParameters {
845 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
847 let first_hops = nodes[0].node.list_usable_channels();
848 let network_graph = &node_cfgs[0].network_graph;
849 let logger = test_utils::TestLogger::new();
850 let scorer = test_utils::TestScorer::new();
851 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
852 let route = find_route(
853 &nodes[0].node.get_our_node_id(), &route_params, network_graph,
854 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
857 let payment_event = {
858 let mut payment_hash = PaymentHash([0; 32]);
859 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
860 nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
861 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
862 assert_eq!(added_monitors.len(), 1);
863 added_monitors.clear();
865 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
866 assert_eq!(events.len(), 1);
867 SendEvent::from_event(events.remove(0))
870 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
871 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
872 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
873 assert_eq!(added_monitors.len(), 1);
874 added_monitors.clear();
875 let events = nodes[1].node.get_and_clear_pending_msg_events();
876 assert_eq!(events.len(), 2);
879 fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
880 let chanmon_cfgs = create_chanmon_cfgs(2);
881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884 let custom_min_final_cltv_expiry_delta = Some(50);
886 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
887 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
888 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
889 if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
891 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
892 custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
896 fn test_create_invoice_custom_min_final_cltv_delta() {
897 do_create_invoice_min_final_cltv_delta(true);
898 do_create_invoice_min_final_cltv_delta(false);
902 fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
903 let chanmon_cfgs = create_chanmon_cfgs(2);
904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
906 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
907 let custom_min_final_cltv_expiry_delta = Some(21);
909 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
910 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
911 Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
912 custom_min_final_cltv_expiry_delta,
914 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
918 fn test_create_invoice_with_description_hash() {
919 let chanmon_cfgs = create_chanmon_cfgs(2);
920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
923 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
924 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
925 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
926 Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
928 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
929 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
930 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
934 fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
935 let chanmon_cfgs = create_chanmon_cfgs(2);
936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
938 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
939 let payment_hash = PaymentHash([0; 32]);
940 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
941 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
942 Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
945 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
946 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
947 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
948 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
952 fn test_hints_has_only_public_confd_channels() {
953 let chanmon_cfgs = create_chanmon_cfgs(2);
954 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
955 let mut config = test_default_channel_config();
956 config.channel_handshake_config.minimum_depth = 1;
957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), Some(config)]);
958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
960 // Create a private channel with lots of capacity and a lower value public channel (without
961 // confirming the funding tx yet).
962 let unannounced_scid = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
963 let conf_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 10_000, 0);
965 // Before the channel is available, we should include the unannounced_scid.
966 let mut scid_aliases = HashSet::new();
967 scid_aliases.insert(unannounced_scid.0.short_channel_id_alias.unwrap());
968 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
970 // However after we mine the funding tx and exchange channel_ready messages for the public
971 // channel we'll immediately switch to including it as a route hint, even though it isn't
973 let pub_channel_scid = mine_transaction(&nodes[0], &conf_tx);
974 let node_a_pub_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
975 nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &node_a_pub_channel_ready);
977 assert_eq!(mine_transaction(&nodes[1], &conf_tx), pub_channel_scid);
978 let events = nodes[1].node.get_and_clear_pending_msg_events();
979 assert_eq!(events.len(), 2);
980 if let MessageSendEvent::SendChannelReady { msg, .. } = &events[0] {
981 nodes[0].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), msg);
983 if let MessageSendEvent::SendChannelUpdate { msg, .. } = &events[1] {
984 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), msg);
987 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()));
989 expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
990 expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
992 scid_aliases.clear();
993 scid_aliases.insert(node_a_pub_channel_ready.short_channel_id_alias.unwrap());
994 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
995 // This also applies even if the amount is more than the payment amount, to ensure users
996 // dont screw up their privacy.
997 match_invoice_routes(Some(50_000_000), &nodes[1], scid_aliases.clone());
999 // The same remains true until the channel has 7 confirmations, at which point we include
1001 connect_blocks(&nodes[1], 5);
1002 match_invoice_routes(Some(5000), &nodes[1], scid_aliases.clone());
1003 connect_blocks(&nodes[1], 1);
1004 get_event_msg!(nodes[1], MessageSendEvent::SendAnnouncementSignatures, nodes[0].node.get_our_node_id());
1005 match_invoice_routes(Some(5000), &nodes[1], HashSet::new());
1009 fn test_hints_includes_single_channels_to_nodes() {
1010 let chanmon_cfgs = create_chanmon_cfgs(3);
1011 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1012 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1013 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);
1016 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1018 let mut scid_aliases = HashSet::new();
1019 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1020 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1022 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
1026 fn test_hints_has_only_lowest_inbound_capacity_channel_above_minimum() {
1027 let chanmon_cfgs = create_chanmon_cfgs(2);
1028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1030 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1032 let _chan_1_0_inbound_below_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000, 0);
1033 let _chan_1_0_large_inbound_above_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 500_000, 0);
1034 let chan_1_0_low_inbound_above_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 200_000, 0);
1036 let mut scid_aliases = HashSet::new();
1037 scid_aliases.insert(chan_1_0_low_inbound_above_amt.0.short_channel_id_alias.unwrap());
1038 match_invoice_routes(Some(100_000_000), &nodes[0], scid_aliases);
1042 fn test_hints_has_only_online_channels() {
1043 let chanmon_cfgs = create_chanmon_cfgs(4);
1044 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1045 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1046 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1047 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
1048 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
1049 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
1051 // With all peers connected we should get all hints that have sufficient value
1052 let mut scid_aliases = HashSet::new();
1053 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
1054 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
1056 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1058 // With only one sufficient-value peer connected we should only get its hint
1059 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
1060 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
1061 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1063 // If we don't have any sufficient-value peers connected we should get all hints with
1064 // sufficient value, even though there is a connected insufficient-value peer.
1065 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
1066 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
1067 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
1071 fn test_insufficient_inbound_sort_by_highest_capacity() {
1072 let chanmon_cfgs = create_chanmon_cfgs(5);
1073 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1074 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1075 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1076 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1077 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 200_000, 0);
1078 let chan_3_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 300_000, 0);
1079 let chan_4_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 4, 0, 400_000, 0);
1081 // When no single channel has enough inbound capacity for the payment, we expect the three
1082 // highest inbound channels to be chosen.
1083 let mut scid_aliases = HashSet::new();
1084 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1085 scid_aliases.insert(chan_3_0.0.short_channel_id_alias.unwrap());
1086 scid_aliases.insert(chan_4_0.0.short_channel_id_alias.unwrap());
1088 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
1092 fn test_sufficient_inbound_sort_by_lowest_capacity() {
1093 let chanmon_cfgs = create_chanmon_cfgs(5);
1094 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1095 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1096 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1097 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1098 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 200_000, 0);
1099 let chan_3_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 300_000, 0);
1100 let _chan_4_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 4, 0, 400_000, 0);
1102 // When we have channels that have sufficient inbound for the payment, test that we sort
1103 // by lowest inbound capacity.
1104 let mut scid_aliases = HashSet::new();
1105 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1106 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1107 scid_aliases.insert(chan_3_0.0.short_channel_id_alias.unwrap());
1109 match_invoice_routes(Some(50_000_000), &nodes[0], scid_aliases.clone());
1113 fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
1114 let chanmon_cfgs = create_chanmon_cfgs(3);
1115 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1116 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1117 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1118 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1120 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
1121 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1122 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1123 let mut private_chan_cfg = UserConfig::default();
1124 private_chan_cfg.channel_handshake_config.announced_channel = false;
1125 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();
1126 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
1127 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
1128 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
1129 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
1131 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
1133 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
1134 confirm_transaction_at(&nodes[2], &tx, conf_height);
1135 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
1136 confirm_transaction_at(&nodes[0], &tx, conf_height);
1137 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
1138 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
1139 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()));
1140 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
1141 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
1142 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
1143 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
1144 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
1146 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
1147 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1148 // Therefore only `chan_1_0` should be included in the hints.
1149 let mut scid_aliases = HashSet::new();
1150 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1151 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
1155 fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
1156 let chanmon_cfgs = create_chanmon_cfgs(3);
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_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1162 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1163 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1164 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1166 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
1167 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
1168 // public channel between `nodes[2]` and `nodes[0]`
1169 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1173 fn test_only_public_channels_includes_no_channels_in_hints() {
1174 let chanmon_cfgs = create_chanmon_cfgs(3);
1175 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1176 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1177 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1178 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
1179 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
1180 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
1182 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1183 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1184 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1186 // As all of `nodes[0]` channels are public, no channels should be included in the hints
1187 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
1191 fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
1192 let chanmon_cfgs = create_chanmon_cfgs(3);
1193 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1194 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1195 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1196 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
1197 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
1199 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
1200 let mut scid_aliases_99_000_001_msat = HashSet::new();
1201 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1203 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
1205 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
1206 let mut scid_aliases_99_000_000_msat = HashSet::new();
1207 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1208 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1210 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
1212 // As the invoice amt is above all channels' inbound capacity, they will still be included
1213 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
1214 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1215 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1217 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1219 // An invoice with no specified amount should include all channels in the route hints.
1220 let mut scid_aliases_no_specified_amount = HashSet::new();
1221 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1222 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1224 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1227 fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1228 invoice_amt: Option<u64>,
1229 invoice_node: &Node<'a, 'b, 'c>,
1230 mut chan_ids_to_match: HashSet<u64>
1232 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
1233 invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
1234 Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
1235 3600, None).unwrap();
1236 let hints = invoice.private_routes();
1239 let hint_short_chan_id = (hint.0).0[0].short_channel_id;
1240 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1242 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1246 #[cfg(feature = "std")]
1247 fn test_multi_node_receive() {
1248 do_test_multi_node_receive(true);
1249 do_test_multi_node_receive(false);
1252 #[cfg(feature = "std")]
1253 fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1254 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1255 let seed_1 = [42u8; 32];
1256 let seed_2 = [43u8; 32];
1257 let cross_node_seed = [44u8; 32];
1258 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1259 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1260 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1261 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1262 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1263 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1264 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1265 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1266 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1267 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1268 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1270 let payment_amt = 10_000;
1271 let route_hints = vec![
1272 nodes[1].node.get_phantom_route_hints(),
1273 nodes[2].node.get_phantom_route_hints(),
1276 let user_payment_preimage = PaymentPreimage([1; 32]);
1277 let payment_hash = if user_generated_pmt_hash {
1278 Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1282 let non_default_invoice_expiry_secs = 4200;
1285 crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1286 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1287 route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1288 Currency::BitcoinTestnet, None, Duration::from_secs(1234567)
1290 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1291 let payment_preimage = if user_generated_pmt_hash {
1292 user_payment_preimage
1294 nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1297 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1298 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1299 assert_eq!(invoice.route_hints().len(), 2);
1300 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1301 assert!(!invoice.features().unwrap().supports_basic_mpp());
1303 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
1304 invoice.min_final_cltv_expiry_delta() as u32)
1305 .with_features(invoice.features().unwrap().clone())
1306 .with_route_hints(invoice.route_hints());
1307 let params = RouteParameters {
1309 final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1311 let first_hops = nodes[0].node.list_usable_channels();
1312 let network_graph = &node_cfgs[0].network_graph;
1313 let logger = test_utils::TestLogger::new();
1314 let scorer = test_utils::TestScorer::new();
1315 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1316 let route = find_route(
1317 &nodes[0].node.get_our_node_id(), ¶ms, network_graph,
1318 Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1320 let (payment_event, fwd_idx) = {
1321 let mut payment_hash = PaymentHash([0; 32]);
1322 payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1323 nodes[0].node.send_payment(&route, payment_hash, &Some(*invoice.payment_secret()), PaymentId(payment_hash.0)).unwrap();
1324 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1325 assert_eq!(added_monitors.len(), 1);
1326 added_monitors.clear();
1328 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1329 assert_eq!(events.len(), 1);
1330 let fwd_idx = match events[0] {
1331 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1332 if node_id == nodes[1].node.get_our_node_id() {
1336 _ => panic!("Unexpected event")
1338 (SendEvent::from_event(events.remove(0)), fwd_idx)
1340 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1341 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1343 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1344 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1345 // payments "look real" by taking more time.
1346 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1347 nodes[fwd_idx].node.process_pending_htlc_forwards();
1348 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1349 nodes[fwd_idx].node.process_pending_htlc_forwards();
1351 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1352 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1353 do_claim_payment_along_route(&nodes[0], &[&vec!(&nodes[fwd_idx])[..]], false, payment_preimage);
1354 let events = nodes[0].node.get_and_clear_pending_events();
1355 assert_eq!(events.len(), 2);
1357 Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1358 assert_eq!(payment_preimage, *ev_preimage);
1359 assert_eq!(payment_hash, *ev_hash);
1360 assert_eq!(fee_paid_msat, &Some(0));
1362 _ => panic!("Unexpected event")
1365 Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1366 assert_eq!(hash, Some(payment_hash));
1368 _ => panic!("Unexpected event")
1373 #[cfg(feature = "std")]
1374 fn test_multi_node_hints_has_htlc_min_max_values() {
1375 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1376 let seed_1 = [42u8; 32];
1377 let seed_2 = [43u8; 32];
1378 let cross_node_seed = [44u8; 32];
1379 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1380 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1381 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1382 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1383 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1385 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1386 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1388 let payment_amt = 20_000;
1389 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1390 let route_hints = vec![
1391 nodes[1].node.get_phantom_route_hints(),
1392 nodes[2].node.get_phantom_route_hints(),
1395 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1396 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1397 "test".to_string(), 3600, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1398 nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1400 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1401 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1402 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1404 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1405 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1406 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1410 #[cfg(feature = "std")]
1411 fn create_phantom_invoice_with_description_hash() {
1412 let chanmon_cfgs = create_chanmon_cfgs(3);
1413 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1414 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1415 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1417 let payment_amt = 20_000;
1418 let route_hints = vec![
1419 nodes[1].node.get_phantom_route_hints(),
1420 nodes[2].node.get_phantom_route_hints(),
1423 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1424 let non_default_invoice_expiry_secs = 4200;
1425 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1426 &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1428 Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1429 route_hints, nodes[1].keys_manager, nodes[1].keys_manager, nodes[1].logger,
1430 Currency::BitcoinTestnet, None, Duration::from_secs(1234567),
1433 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1434 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1435 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1436 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1440 #[cfg(feature = "std")]
1441 fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1442 let chanmon_cfgs = create_chanmon_cfgs(3);
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 payment_amt = 20_000;
1448 let route_hints = vec![
1449 nodes[1].node.get_phantom_route_hints(),
1450 nodes[2].node.get_phantom_route_hints(),
1452 let user_payment_preimage = PaymentPreimage([1; 32]);
1453 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1454 let non_default_invoice_expiry_secs = 4200;
1455 let min_final_cltv_expiry_delta = Some(100);
1456 let duration_since_epoch = Duration::from_secs(1234567);
1457 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1458 &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1459 "".to_string(), non_default_invoice_expiry_secs, route_hints, nodes[1].keys_manager, nodes[1].keys_manager,
1460 nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap();
1461 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1462 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1463 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1467 #[cfg(feature = "std")]
1468 fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1469 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1470 let seed_1 = [42u8; 32];
1471 let seed_2 = [43u8; 32];
1472 let cross_node_seed = [44u8; 32];
1473 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1474 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1475 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1476 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1477 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1479 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1480 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1482 let mut scid_aliases = HashSet::new();
1483 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1484 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1486 match_multi_node_invoice_routes(
1489 vec![&nodes[1], &nodes[2],],
1496 #[cfg(feature = "std")]
1497 fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1498 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1499 let seed_1 = [42u8; 32];
1500 let seed_2 = [43u8; 32];
1501 let cross_node_seed = [44u8; 32];
1502 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1503 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1504 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1505 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1506 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1508 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1509 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1510 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1512 let mut scid_aliases = HashSet::new();
1513 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1514 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1515 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1517 match_multi_node_invoice_routes(
1520 vec![&nodes[2], &nodes[3],],
1527 #[cfg(feature = "std")]
1528 fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1529 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1530 let seed_1 = [42u8; 32];
1531 let seed_2 = [43u8; 32];
1532 let cross_node_seed = [44u8; 32];
1533 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1534 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1535 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1536 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1537 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1539 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1540 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1542 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1543 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1544 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1545 let mut private_chan_cfg = UserConfig::default();
1546 private_chan_cfg.channel_handshake_config.announced_channel = false;
1547 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();
1548 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1549 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1550 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1551 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1553 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1555 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1556 confirm_transaction_at(&nodes[1], &tx, conf_height);
1557 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1558 confirm_transaction_at(&nodes[3], &tx, conf_height);
1559 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1560 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1561 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()));
1562 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1563 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1564 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1565 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1566 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1568 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1569 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1570 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1571 let mut scid_aliases = HashSet::new();
1572 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1573 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1575 match_multi_node_invoice_routes(
1578 vec![&nodes[2], &nodes[3],],
1585 #[cfg(feature = "std")]
1586 fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1587 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1588 let seed_1 = [42u8; 32];
1589 let seed_2 = [43u8; 32];
1590 let cross_node_seed = [44u8; 32];
1591 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1592 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1593 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1594 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1595 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1597 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1599 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1600 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1601 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1603 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1604 // `chan_0_2` as `nodes[2]` only has public channels.
1605 let mut scid_aliases = HashSet::new();
1606 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1608 match_multi_node_invoice_routes(
1611 vec![&nodes[1], &nodes[2],],
1618 #[cfg(feature = "std")]
1619 fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1620 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1621 let seed_1 = [42u8; 32];
1622 let seed_2 = [43u8; 32];
1623 let cross_node_seed = [44u8; 32];
1624 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1625 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1626 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1627 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1628 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1630 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1631 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1632 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1633 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1635 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1637 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1638 // channels for `nodes[2]` as it contains a mix of public and private channels.
1639 let mut scid_aliases = HashSet::new();
1640 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1642 match_multi_node_invoice_routes(
1645 vec![&nodes[2], &nodes[3],],
1652 #[cfg(feature = "std")]
1653 fn test_multi_node_hints_has_only_lowest_inbound_channel_above_minimum() {
1654 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1655 let seed_1 = [42u8; 32];
1656 let seed_2 = [43u8; 32];
1657 let cross_node_seed = [44u8; 32];
1658 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1659 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1660 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1661 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1662 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1664 let _chan_0_1_below_amt = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1665 let _chan_0_1_above_amt_high_inbound = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 500_000, 0);
1666 let chan_0_1_above_amt_low_inbound = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 180_000, 0);
1667 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1669 let mut scid_aliases = HashSet::new();
1670 scid_aliases.insert(chan_0_1_above_amt_low_inbound.0.short_channel_id_alias.unwrap());
1671 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1673 match_multi_node_invoice_routes(
1676 vec![&nodes[1], &nodes[2],],
1683 #[cfg(feature = "std")]
1684 fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1685 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1686 let seed_1 = [42u8; 32];
1687 let seed_2 = [43u8; 32];
1688 let cross_node_seed = [44u8; 32];
1689 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1690 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1691 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1692 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1693 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1695 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1696 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1697 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1699 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1700 let mut scid_aliases_99_000_001_msat = HashSet::new();
1701 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1702 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1704 match_multi_node_invoice_routes(
1707 vec![&nodes[2], &nodes[3],],
1708 scid_aliases_99_000_001_msat,
1712 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1713 let mut scid_aliases_99_000_000_msat = HashSet::new();
1714 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1715 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1716 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1718 match_multi_node_invoice_routes(
1721 vec![&nodes[2], &nodes[3],],
1722 scid_aliases_99_000_000_msat,
1726 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1727 // `nodes[2]` them should be included.
1728 let mut scid_aliases_300_000_000_msat = HashSet::new();
1729 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1730 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1731 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1733 match_multi_node_invoice_routes(
1736 vec![&nodes[2], &nodes[3],],
1737 scid_aliases_300_000_000_msat,
1741 // Since the no specified amount, all channels should included.
1742 let mut scid_aliases_no_specified_amount = HashSet::new();
1743 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1744 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1745 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1747 match_multi_node_invoice_routes(
1750 vec![&nodes[2], &nodes[3],],
1751 scid_aliases_no_specified_amount,
1757 fn test_multi_node_hints_limited_to_3() {
1758 let mut chanmon_cfgs = create_chanmon_cfgs(6);
1759 let seed_1 = [42 as u8; 32];
1760 let seed_2 = [43 as u8; 32];
1761 let seed_3 = [44 as u8; 32];
1762 let seed_4 = [45 as u8; 32];
1763 let cross_node_seed = [44 as u8; 32];
1764 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1765 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1766 chanmon_cfgs[4].keys_manager.backing = PhantomKeysManager::new(&seed_3, 43, 44, &cross_node_seed);
1767 chanmon_cfgs[5].keys_manager.backing = PhantomKeysManager::new(&seed_4, 43, 44, &cross_node_seed);
1768 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1769 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1770 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1772 // Setup each phantom node with two channels from distinct peers.
1773 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 10_000, 0);
1774 let chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 20_000, 0);
1775 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 20_000, 0);
1776 let _chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 10_000, 0);
1777 let chan_0_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 4, 20_000, 0);
1778 let _chan_1_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 4, 10_000, 0);
1779 let _chan_0_5 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 5, 20_000, 0);
1780 let _chan_1_5 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 5, 10_000, 0);
1782 // Set invoice amount > all channels inbound so that every one is eligible for inclusion
1783 // and hints will be sorted by largest inbound capacity.
1784 let invoice_amt = Some(100_000_000);
1786 // With 4 phantom nodes, assert that we include 1 hint per node, up to 3 nodes.
1787 let mut scid_aliases = HashSet::new();
1788 scid_aliases.insert(chan_1_2.0.short_channel_id_alias.unwrap());
1789 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1790 scid_aliases.insert(chan_0_4.0.short_channel_id_alias.unwrap());
1792 match_multi_node_invoice_routes(
1795 vec![&nodes[2], &nodes[3], &nodes[4], &nodes[5]],
1800 // With 2 phantom nodes, assert that we include no more than 3 hints.
1801 let mut scid_aliases = HashSet::new();
1802 scid_aliases.insert(chan_1_2.0.short_channel_id_alias.unwrap());
1803 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1804 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1806 match_multi_node_invoice_routes(
1809 vec![&nodes[2], &nodes[3]],
1816 fn test_multi_node_hints_at_least_3() {
1817 let mut chanmon_cfgs = create_chanmon_cfgs(5);
1818 let seed_1 = [42 as u8; 32];
1819 let seed_2 = [43 as u8; 32];
1820 let cross_node_seed = [44 as u8; 32];
1821 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1822 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1823 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1824 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1825 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1827 let _chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 10_000, 0);
1828 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 20_000, 0);
1829 let chan_2_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 3, 30_000, 0);
1830 let chan_0_4 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 4, 10_000, 0);
1832 // Since the invoice amount is above all channels inbound, all four are eligible. Test that
1833 // we still include 3 hints from 2 distinct nodes sorted by inbound.
1834 let mut scid_aliases = HashSet::new();
1835 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1836 scid_aliases.insert(chan_2_3.0.short_channel_id_alias.unwrap());
1837 scid_aliases.insert(chan_0_4.0.short_channel_id_alias.unwrap());
1839 match_multi_node_invoice_routes(
1842 vec![&nodes[3], &nodes[4],],
1848 fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1849 invoice_amt: Option<u64>,
1850 invoice_node: &Node<'a, 'b, 'c>,
1851 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1852 mut chan_ids_to_match: HashSet<u64>,
1853 nodes_contains_public_channels: bool
1855 let phantom_route_hints = network_multi_nodes.iter()
1856 .map(|node| node.node.get_phantom_route_hints())
1857 .collect::<Vec<PhantomRouteHints>>();
1858 let phantom_scids = phantom_route_hints.iter()
1859 .map(|route_hint| route_hint.phantom_scid)
1860 .collect::<HashSet<u64>>();
1862 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1863 &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1864 3600, phantom_route_hints, invoice_node.keys_manager, invoice_node.keys_manager,
1865 invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1867 let invoice_hints = invoice.private_routes();
1869 for hint in invoice_hints {
1870 let hints = &(hint.0).0;
1873 assert!(nodes_contains_public_channels);
1874 let phantom_scid = hints[0].short_channel_id;
1875 assert!(phantom_scids.contains(&phantom_scid));
1878 let hint_short_chan_id = hints[0].short_channel_id;
1879 assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1880 let phantom_scid = hints[1].short_channel_id;
1881 assert!(phantom_scids.contains(&phantom_scid));
1883 _ => panic!("Incorrect hint length generated")
1886 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1890 fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1891 let chanmon_cfgs = create_chanmon_cfgs(2);
1892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1894 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1895 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1896 nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1897 Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1900 Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},