3d19d3a9f691734759cac1ed5e0eb48caed4f540
[rust-lightning] / lightning-invoice / src / utils.rs
1 //! Convenient utilities to create an invoice.
2
3 use crate::{CreationError, Currency, Invoice, InvoiceBuilder, SignOrCreationError};
4 use crate::payment::Payer;
5
6 use crate::{prelude::*, Description, InvoiceDescription, Sha256};
7 use bech32::ToBase32;
8 use bitcoin_hashes::Hash;
9 use lightning::chain;
10 use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
11 use lightning::chain::keysinterface::{Recipient, NodeSigner, SignerProvider, EntropySource};
12 use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
13 use lightning::ln::channelmanager::{ChannelDetails, ChannelManager, PaymentId, PaymentSendFailure, MIN_FINAL_CLTV_EXPIRY_DELTA};
14 use lightning::ln::channelmanager::{PhantomRouteHints, MIN_CLTV_EXPIRY_DELTA};
15 use lightning::ln::inbound_payment::{create, create_from_hash, ExpandedKey};
16 use lightning::routing::gossip::RoutingFees;
17 use lightning::routing::router::{InFlightHtlcs, Route, RouteHint, RouteHintHop, Router};
18 use lightning::util::logger::Logger;
19 use secp256k1::PublicKey;
20 use core::ops::Deref;
21 use core::time::Duration;
22
23 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
24 /// See [`PhantomKeysManager`] for more information on phantom node payments.
25 ///
26 /// `phantom_route_hints` parameter:
27 /// * Contains channel info for all nodes participating in the phantom invoice
28 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
29 ///   participating node
30 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
31 ///   updated when a channel becomes disabled or closes
32 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
33 ///   may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
34 ///   down
35 ///
36 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
37 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
38 /// If `None` is provided for `payment_hash`, then one will be created.
39 ///
40 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
41 /// in excess of the current time.
42 /// 
43 /// `duration_since_epoch` is the current time since epoch in seconds.
44 ///
45 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
46 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3.
47 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
48 /// confirmations during routing.
49 ///
50 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
51 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
52 /// requirement).
53 ///
54 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
55 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
56 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
57 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
58 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
59 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
60 /// 
61 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
62 /// available and the current time is supplied by the caller.
63 pub fn create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
64         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: String,
65         invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
66         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
67 ) -> Result<Invoice, SignOrCreationError<()>>
68 where
69         ES::Target: EntropySource,
70         NS::Target: NodeSigner,
71         L::Target: Logger,
72 {
73         let description = Description::new(description).map_err(SignOrCreationError::CreationError)?;
74         let description = InvoiceDescription::Direct(&description,);
75         _create_phantom_invoice::<ES, NS, L>(
76                 amt_msat, payment_hash, description, invoice_expiry_delta_secs, phantom_route_hints,
77                 entropy_source, node_signer, logger, network, min_final_cltv_expiry_delta, duration_since_epoch,
78         )
79 }
80
81 /// Utility to create an invoice that can be paid to one of multiple nodes, or a "phantom invoice."
82 /// See [`PhantomKeysManager`] for more information on phantom node payments.
83 ///
84 /// `phantom_route_hints` parameter:
85 /// * Contains channel info for all nodes participating in the phantom invoice
86 /// * Entries are retrieved from a call to [`ChannelManager::get_phantom_route_hints`] on each
87 ///   participating node
88 /// * It is fine to cache `phantom_route_hints` and reuse it across invoices, as long as the data is
89 ///   updated when a channel becomes disabled or closes
90 /// * Note that if too many channels are included in [`PhantomRouteHints::channels`], the invoice
91 ///   may be too long for QR code scanning. To fix this, `PhantomRouteHints::channels` may be pared
92 ///   down
93 ///
94 /// `description_hash` is a SHA-256 hash of the description text
95 ///
96 /// `payment_hash` can be specified if you have a specific need for a custom payment hash (see the difference
97 /// between [`ChannelManager::create_inbound_payment`] and [`ChannelManager::create_inbound_payment_for_hash`]).
98 /// If `None` is provided for `payment_hash`, then one will be created.
99 ///
100 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
101 /// in excess of the current time.
102 /// 
103 /// `duration_since_epoch` is the current time since epoch in seconds.
104 ///
105 /// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom
106 /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this
107 /// requirement).
108 ///
109 /// [`PhantomKeysManager`]: lightning::chain::keysinterface::PhantomKeysManager
110 /// [`ChannelManager::get_phantom_route_hints`]: lightning::ln::channelmanager::ChannelManager::get_phantom_route_hints
111 /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment
112 /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
113 /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels
114 /// 
115 /// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
116 /// available and the current time is supplied by the caller.
117 pub fn create_phantom_invoice_with_description_hash<ES: Deref, NS: Deref, L: Deref>(
118         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, invoice_expiry_delta_secs: u32,
119         description_hash: Sha256, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
120         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
121 ) -> Result<Invoice, SignOrCreationError<()>>
122 where
123         ES::Target: EntropySource,
124         NS::Target: NodeSigner,
125         L::Target: Logger,
126 {
127         _create_phantom_invoice::<ES, NS, L>(
128                 amt_msat, payment_hash, InvoiceDescription::Hash(&description_hash),
129                 invoice_expiry_delta_secs, phantom_route_hints, entropy_source, node_signer, logger, network,
130                 min_final_cltv_expiry_delta, duration_since_epoch,
131         )
132 }
133
134 fn _create_phantom_invoice<ES: Deref, NS: Deref, L: Deref>(
135         amt_msat: Option<u64>, payment_hash: Option<PaymentHash>, description: InvoiceDescription,
136         invoice_expiry_delta_secs: u32, phantom_route_hints: Vec<PhantomRouteHints>, entropy_source: ES,
137         node_signer: NS, logger: L, network: Currency, min_final_cltv_expiry_delta: Option<u16>, duration_since_epoch: Duration,
138 ) -> Result<Invoice, SignOrCreationError<()>>
139 where
140         ES::Target: EntropySource,
141         NS::Target: NodeSigner,
142         L::Target: Logger,
143 {
144
145         if phantom_route_hints.len() == 0 {
146                 return Err(SignOrCreationError::CreationError(
147                         CreationError::MissingRouteHints,
148                 ));
149         }
150
151         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
152                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
153         }
154
155         let invoice = match description {
156                 InvoiceDescription::Direct(description) => {
157                         InvoiceBuilder::new(network).description(description.0.clone())
158                 }
159                 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
160         };
161
162         // If we ever see performance here being too slow then we should probably take this ExpandedKey as a parameter instead.
163         let keys = ExpandedKey::new(&node_signer.get_inbound_payment_key_material());
164         let (payment_hash, payment_secret) = if let Some(payment_hash) = payment_hash {
165                 let payment_secret = create_from_hash(
166                         &keys,
167                         amt_msat,
168                         payment_hash,
169                         invoice_expiry_delta_secs,
170                         duration_since_epoch
171                                 .as_secs(),
172                         min_final_cltv_expiry_delta,
173                 )
174                 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
175                 (payment_hash, payment_secret)
176         } else {
177                 create(
178                         &keys,
179                         amt_msat,
180                         invoice_expiry_delta_secs,
181                         &entropy_source,
182                         duration_since_epoch
183                                 .as_secs(),
184                         min_final_cltv_expiry_delta,
185                 )
186                 .map_err(|_| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
187         };
188
189         log_trace!(logger, "Creating phantom invoice from {} participating nodes with payment hash {}",
190                 phantom_route_hints.len(), log_bytes!(payment_hash.0));
191
192         let mut invoice = invoice
193                 .duration_since_epoch(duration_since_epoch)
194                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
195                 .payment_secret(payment_secret)
196                 .min_final_cltv_expiry_delta(
197                         // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
198                         min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
199                 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
200         if let Some(amt) = amt_msat {
201                 invoice = invoice.amount_milli_satoshis(amt);
202         }
203
204         for PhantomRouteHints { channels, phantom_scid, real_node_pubkey } in phantom_route_hints {
205                 log_trace!(logger, "Generating phantom route hints for node {}",
206                         log_pubkey!(real_node_pubkey));
207                 let mut route_hints = filter_channels(channels, amt_msat, &logger);
208
209                 // If we have any public channel, the route hints from `filter_channels` will be empty.
210                 // In that case we create a RouteHint on which we will push a single hop with the phantom
211                 // route into the invoice, and let the sender find the path to the `real_node_pubkey`
212                 // node by looking at our public channels.
213                 if route_hints.is_empty() {
214                         route_hints.push(RouteHint(vec![]))
215                 }
216                 for mut route_hint in route_hints {
217                         route_hint.0.push(RouteHintHop {
218                                 src_node_id: real_node_pubkey,
219                                 short_channel_id: phantom_scid,
220                                 fees: RoutingFees {
221                                         base_msat: 0,
222                                         proportional_millionths: 0,
223                                 },
224                                 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
225                                 htlc_minimum_msat: None,
226                                 htlc_maximum_msat: None,});
227                         invoice = invoice.private_route(route_hint.clone());
228                 }
229         }
230
231         let raw_invoice = match invoice.build_raw() {
232                 Ok(inv) => inv,
233                 Err(e) => return Err(SignOrCreationError::CreationError(e))
234         };
235         let hrp_str = raw_invoice.hrp.to_string();
236         let hrp_bytes = hrp_str.as_bytes();
237         let data_without_signature = raw_invoice.data.to_base32();
238         let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::PhantomNode));
239         match signed_raw_invoice {
240                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
241                 Err(e) => Err(SignOrCreationError::SignError(e))
242         }
243 }
244
245 #[cfg(feature = "std")]
246 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
247 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
248 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
249 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
250 /// that the payment secret is valid when the invoice is paid.
251 ///
252 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
253 /// in excess of the current time.
254 ///
255 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
256 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
257 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
258 /// confirmations during routing.
259 ///
260 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
261 pub fn create_invoice_from_channelmanager<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>(
262         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
263         network: Currency, amt_msat: Option<u64>, description: String, invoice_expiry_delta_secs: u32,
264         min_final_cltv_expiry_delta: Option<u16>,
265 ) -> Result<Invoice, SignOrCreationError<()>>
266 where
267         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
268         T::Target: BroadcasterInterface,
269         ES::Target: EntropySource,
270         NS::Target: NodeSigner,
271         SP::Target: SignerProvider,
272         F::Target: FeeEstimator,
273         R::Target: Router,
274         L::Target: Logger,
275 {
276         use std::time::SystemTime;
277         let duration = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
278                 .expect("for the foreseeable future this shouldn't happen");
279         create_invoice_from_channelmanager_and_duration_since_epoch(
280                 channelmanager, node_signer, logger, network, amt_msat,
281                 description, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
282         )
283 }
284
285 #[cfg(feature = "std")]
286 /// Utility to construct an invoice. Generally, unless you want to do something like a custom
287 /// cltv_expiry, this is what you should be using to create an invoice. The reason being, this
288 /// method stores the invoice's payment secret and preimage in `ChannelManager`, so (a) the user
289 /// doesn't have to store preimage/payment secret information and (b) `ChannelManager` can verify
290 /// that the payment secret is valid when the invoice is paid.
291 /// Use this variant if you want to pass the `description_hash` to the invoice.
292 ///
293 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
294 /// in excess of the current time.
295 ///
296 /// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to
297 /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
298 /// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block
299 /// confirmations during routing.
300 ///
301 /// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA
302 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>(
303         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
304         network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
305         invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
306 ) -> Result<Invoice, SignOrCreationError<()>>
307 where
308         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
309         T::Target: BroadcasterInterface,
310         ES::Target: EntropySource,
311         NS::Target: NodeSigner,
312         SP::Target: SignerProvider,
313         F::Target: FeeEstimator,
314         R::Target: Router,
315         L::Target: Logger,
316 {
317         use std::time::SystemTime;
318
319         let duration = SystemTime::now()
320                 .duration_since(SystemTime::UNIX_EPOCH)
321                 .expect("for the foreseeable future this shouldn't happen");
322
323         create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
324                 channelmanager, node_signer, logger, network, amt_msat,
325                 description_hash, duration, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
326         )
327 }
328
329 /// See [`create_invoice_from_channelmanager_with_description_hash`]
330 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
331 /// available and the current time is supplied by the caller.
332 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>(
333         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
334         network: Currency, amt_msat: Option<u64>, description_hash: Sha256,
335         duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
336 ) -> Result<Invoice, SignOrCreationError<()>>
337                 where
338                         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
339                         T::Target: BroadcasterInterface,
340                         ES::Target: EntropySource,
341                         NS::Target: NodeSigner,
342                         SP::Target: SignerProvider,
343                         F::Target: FeeEstimator,
344                         R::Target: Router,
345                         L::Target: Logger,
346 {
347         _create_invoice_from_channelmanager_and_duration_since_epoch(
348                 channelmanager, node_signer, logger, network, amt_msat,
349                 InvoiceDescription::Hash(&description_hash),
350                 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
351         )
352 }
353
354 /// See [`create_invoice_from_channelmanager`]
355 /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not
356 /// available and the current time is supplied by the caller.
357 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>(
358         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
359         network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
360         invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
361 ) -> Result<Invoice, SignOrCreationError<()>>
362                 where
363                         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
364                         T::Target: BroadcasterInterface,
365                         ES::Target: EntropySource,
366                         NS::Target: NodeSigner,
367                         SP::Target: SignerProvider,
368                         F::Target: FeeEstimator,
369                         R::Target: Router,
370                         L::Target: Logger,
371 {
372         _create_invoice_from_channelmanager_and_duration_since_epoch(
373                 channelmanager, node_signer, logger, network, amt_msat,
374                 InvoiceDescription::Direct(
375                         &Description::new(description).map_err(SignOrCreationError::CreationError)?,
376                 ),
377                 duration_since_epoch, invoice_expiry_delta_secs, min_final_cltv_expiry_delta,
378         )
379 }
380
381 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>(
382         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
383         network: Currency, amt_msat: Option<u64>, description: InvoiceDescription,
384         duration_since_epoch: Duration, invoice_expiry_delta_secs: u32, min_final_cltv_expiry_delta: Option<u16>,
385 ) -> Result<Invoice, SignOrCreationError<()>>
386                 where
387                         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
388                         T::Target: BroadcasterInterface,
389                         ES::Target: EntropySource,
390                         NS::Target: NodeSigner,
391                         SP::Target: SignerProvider,
392                         F::Target: FeeEstimator,
393                         R::Target: Router,
394                         L::Target: Logger,
395 {
396         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
397                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
398         }
399
400         // `create_inbound_payment` only returns an error if the amount is greater than the total bitcoin
401         // supply.
402         let (payment_hash, payment_secret) = channelmanager
403                 .create_inbound_payment(amt_msat, invoice_expiry_delta_secs, min_final_cltv_expiry_delta)
404                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
405         _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
406                 channelmanager, node_signer, logger, network, amt_msat, description, duration_since_epoch,
407                 invoice_expiry_delta_secs, payment_hash, payment_secret, min_final_cltv_expiry_delta)
408 }
409
410 /// See [`create_invoice_from_channelmanager_and_duration_since_epoch`]
411 /// This version allows for providing a custom [`PaymentHash`] for the invoice.
412 /// This may be useful if you're building an on-chain swap or involving another protocol where
413 /// the payment hash is also involved outside the scope of lightning.
414 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>(
415         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
416         network: Currency, amt_msat: Option<u64>, description: String, duration_since_epoch: Duration,
417         invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, min_final_cltv_expiry_delta: Option<u16>,
418 ) -> Result<Invoice, SignOrCreationError<()>>
419         where
420                 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
421                 T::Target: BroadcasterInterface,
422                 ES::Target: EntropySource,
423                 NS::Target: NodeSigner,
424                 SP::Target: SignerProvider,
425                 F::Target: FeeEstimator,
426                 R::Target: Router,
427                 L::Target: Logger,
428 {
429         let payment_secret = channelmanager
430                 .create_inbound_payment_for_hash(payment_hash, amt_msat, invoice_expiry_delta_secs,
431                         min_final_cltv_expiry_delta)
432                 .map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
433         _create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
434                 channelmanager, node_signer, logger, network, amt_msat,
435                 InvoiceDescription::Direct(
436                         &Description::new(description).map_err(SignOrCreationError::CreationError)?,
437                 ),
438                 duration_since_epoch, invoice_expiry_delta_secs, payment_hash, payment_secret,
439                 min_final_cltv_expiry_delta,
440         )
441 }
442
443 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>(
444         channelmanager: &ChannelManager<M, T, ES, NS, SP, F, R, L>, node_signer: NS, logger: L,
445         network: Currency, amt_msat: Option<u64>, description: InvoiceDescription, duration_since_epoch: Duration,
446         invoice_expiry_delta_secs: u32, payment_hash: PaymentHash, payment_secret: PaymentSecret,
447         min_final_cltv_expiry_delta: Option<u16>,
448 ) -> Result<Invoice, SignOrCreationError<()>>
449         where
450                 M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
451                 T::Target: BroadcasterInterface,
452                 ES::Target: EntropySource,
453                 NS::Target: NodeSigner,
454                 SP::Target: SignerProvider,
455                 F::Target: FeeEstimator,
456                 R::Target: Router,
457                 L::Target: Logger,
458 {
459         let our_node_pubkey = channelmanager.get_our_node_id();
460         let channels = channelmanager.list_channels();
461
462         if min_final_cltv_expiry_delta.is_some() && min_final_cltv_expiry_delta.unwrap().saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
463                 return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
464         }
465
466         log_trace!(logger, "Creating invoice with payment hash {}", log_bytes!(payment_hash.0));
467
468         let invoice = match description {
469                 InvoiceDescription::Direct(description) => {
470                         InvoiceBuilder::new(network).description(description.0.clone())
471                 }
472                 InvoiceDescription::Hash(hash) => InvoiceBuilder::new(network).description_hash(hash.0),
473         };
474
475         let mut invoice = invoice
476                 .duration_since_epoch(duration_since_epoch)
477                 .payee_pub_key(our_node_pubkey)
478                 .payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
479                 .payment_secret(payment_secret)
480                 .basic_mpp()
481                 .min_final_cltv_expiry_delta(
482                         // Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
483                         min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into())
484                 .expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
485         if let Some(amt) = amt_msat {
486                 invoice = invoice.amount_milli_satoshis(amt);
487         }
488
489         let route_hints = filter_channels(channels, amt_msat, &logger);
490         for hint in route_hints {
491                 invoice = invoice.private_route(hint);
492         }
493
494         let raw_invoice = match invoice.build_raw() {
495                 Ok(inv) => inv,
496                 Err(e) => return Err(SignOrCreationError::CreationError(e))
497         };
498         let hrp_str = raw_invoice.hrp.to_string();
499         let hrp_bytes = hrp_str.as_bytes();
500         let data_without_signature = raw_invoice.data.to_base32();
501         let signed_raw_invoice = raw_invoice.sign(|_| node_signer.sign_invoice(hrp_bytes, &data_without_signature, Recipient::Node));
502         match signed_raw_invoice {
503                 Ok(inv) => Ok(Invoice::from_signed(inv).unwrap()),
504                 Err(e) => Err(SignOrCreationError::SignError(e))
505         }
506 }
507
508 /// Filters the `channels` for an invoice, and returns the corresponding `RouteHint`s to include
509 /// in the invoice.
510 ///
511 /// The filtering is based on the following criteria:
512 /// * Only one channel per counterparty node
513 /// * Always select the channel with the highest inbound capacity per counterparty node
514 /// * Prefer channels with capacity at least `min_inbound_capacity_msat` and where the channel
515 ///   `is_usable` (i.e. the peer is connected).
516 /// * If any public channel exists, the returned `RouteHint`s will be empty, and the sender will
517 ///   need to find the path by looking at the public channels instead
518 fn filter_channels<L: Deref>(
519         channels: Vec<ChannelDetails>, min_inbound_capacity_msat: Option<u64>, logger: &L
520 ) -> Vec<RouteHint> where L::Target: Logger {
521         let mut filtered_channels: HashMap<PublicKey, ChannelDetails> = HashMap::new();
522         let min_inbound_capacity = min_inbound_capacity_msat.unwrap_or(0);
523         let mut min_capacity_channel_exists = false;
524         let mut online_channel_exists = false;
525         let mut online_min_capacity_channel_exists = false;
526
527         log_trace!(logger, "Considering {} channels for invoice route hints", channels.len());
528         for channel in channels.into_iter().filter(|chan| chan.is_channel_ready) {
529                 if channel.get_inbound_payment_scid().is_none() || channel.counterparty.forwarding_info.is_none() {
530                         log_trace!(logger, "Ignoring channel {} for invoice route hints", log_bytes!(channel.channel_id));
531                         continue;
532                 }
533
534                 if channel.is_public {
535                         // If any public channel exists, return no hints and let the sender
536                         // look at the public channels instead.
537                         log_trace!(logger, "Not including channels in invoice route hints on account of public channel {}",
538                                 log_bytes!(channel.channel_id));
539                         return vec![]
540                 }
541
542                 if channel.inbound_capacity_msat >= min_inbound_capacity {
543                         if !min_capacity_channel_exists {
544                                 log_trace!(logger, "Channel with enough inbound capacity exists for invoice route hints");
545                                 min_capacity_channel_exists = true;
546                         }
547
548                         if channel.is_usable {
549                                 online_min_capacity_channel_exists = true;
550                         }
551                 }
552
553                 if channel.is_usable {
554                         if !online_channel_exists {
555                                 log_trace!(logger, "Channel with connected peer exists for invoice route hints");
556                                 online_channel_exists = true;
557                         }
558                 }
559
560                 match filtered_channels.entry(channel.counterparty.node_id) {
561                         hash_map::Entry::Occupied(mut entry) => {
562                                 let current_max_capacity = entry.get().inbound_capacity_msat;
563                                 if channel.inbound_capacity_msat < current_max_capacity {
564                                         log_trace!(logger,
565                                                 "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
566                                                 log_pubkey!(channel.counterparty.node_id),
567                                                 log_bytes!(entry.get().channel_id), current_max_capacity,
568                                                 log_bytes!(channel.channel_id), channel.inbound_capacity_msat);
569                                         continue;
570                                 }
571                                 log_trace!(logger,
572                                         "Preferring counterparty {} channel {} ({} msats) over {} ({} msats) for invoice route hints",
573                                         log_pubkey!(channel.counterparty.node_id),
574                                         log_bytes!(channel.channel_id), channel.inbound_capacity_msat,
575                                         log_bytes!(entry.get().channel_id), current_max_capacity);
576                                 entry.insert(channel);
577                         }
578                         hash_map::Entry::Vacant(entry) => {
579                                 entry.insert(channel);
580                         }
581                 }
582         }
583
584         let route_hint_from_channel = |channel: ChannelDetails| {
585                 let forwarding_info = channel.counterparty.forwarding_info.as_ref().unwrap();
586                 RouteHint(vec![RouteHintHop {
587                         src_node_id: channel.counterparty.node_id,
588                         short_channel_id: channel.get_inbound_payment_scid().unwrap(),
589                         fees: RoutingFees {
590                                 base_msat: forwarding_info.fee_base_msat,
591                                 proportional_millionths: forwarding_info.fee_proportional_millionths,
592                         },
593                         cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
594                         htlc_minimum_msat: channel.inbound_htlc_minimum_msat,
595                         htlc_maximum_msat: channel.inbound_htlc_maximum_msat,}])
596         };
597         // If all channels are private, prefer to return route hints which have a higher capacity than
598         // the payment value and where we're currently connected to the channel counterparty.
599         // Even if we cannot satisfy both goals, always ensure we include *some* hints, preferring
600         // those which meet at least one criteria.
601         filtered_channels
602                 .into_iter()
603                 .map(|(_, channel)| channel)
604                 .filter(|channel| {
605                         let has_enough_capacity = channel.inbound_capacity_msat >= min_inbound_capacity;
606                         let include_channel = if online_min_capacity_channel_exists {
607                                 has_enough_capacity && channel.is_usable
608                         } else if min_capacity_channel_exists && online_channel_exists {
609                                 // If there are some online channels and some min_capacity channels, but no
610                                 // online-and-min_capacity channels, just include the min capacity ones and ignore
611                                 // online-ness.
612                                 has_enough_capacity
613                         } else if min_capacity_channel_exists {
614                                 has_enough_capacity
615                         } else if online_channel_exists {
616                                 channel.is_usable
617                         } else { true };
618
619                         if include_channel {
620                                 log_trace!(logger, "Including channel {} in invoice route hints",
621                                         log_bytes!(channel.channel_id));
622                         } else if !has_enough_capacity {
623                                 log_trace!(logger, "Ignoring channel {} without enough capacity for invoice route hints",
624                                         log_bytes!(channel.channel_id));
625                         } else {
626                                 debug_assert!(!channel.is_usable);
627                                 log_trace!(logger, "Ignoring channel {} with disconnected peer",
628                                         log_bytes!(channel.channel_id));
629                         }
630
631                         include_channel
632                 })
633                 .map(route_hint_from_channel)
634                 .collect::<Vec<RouteHint>>()
635 }
636
637 impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref> Payer for ChannelManager<M, T, ES, NS, SP, F, R, L>
638 where
639         M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
640         T::Target: BroadcasterInterface,
641         ES::Target: EntropySource,
642         NS::Target: NodeSigner,
643         SP::Target: SignerProvider,
644         F::Target: FeeEstimator,
645         R::Target: Router,
646         L::Target: Logger,
647 {
648         fn node_id(&self) -> PublicKey {
649                 self.get_our_node_id()
650         }
651
652         fn first_hops(&self) -> Vec<ChannelDetails> {
653                 self.list_usable_channels()
654         }
655
656         fn send_payment(
657                 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
658                 payment_id: PaymentId
659         ) -> Result<(), PaymentSendFailure> {
660                 self.send_payment(route, payment_hash, payment_secret, payment_id)
661         }
662
663         fn send_spontaneous_payment(
664                 &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId,
665         ) -> Result<(), PaymentSendFailure> {
666                 self.send_spontaneous_payment(route, Some(payment_preimage), payment_id).map(|_| ())
667         }
668
669         fn retry_payment(
670                 &self, route: &Route, payment_id: PaymentId
671         ) -> Result<(), PaymentSendFailure> {
672                 self.retry_payment(route, payment_id)
673         }
674
675         fn abandon_payment(&self, payment_id: PaymentId) {
676                 self.abandon_payment(payment_id)
677         }
678
679         fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() }
680 }
681
682 #[cfg(test)]
683 mod test {
684         use core::time::Duration;
685         use crate::{Currency, Description, InvoiceDescription, SignOrCreationError, CreationError};
686         use bitcoin_hashes::{Hash, sha256};
687         use bitcoin_hashes::sha256::Hash as Sha256;
688         use lightning::chain::keysinterface::{EntropySource, PhantomKeysManager};
689         use lightning::ln::{PaymentPreimage, PaymentHash};
690         use lightning::ln::channelmanager::{PhantomRouteHints, MIN_FINAL_CLTV_EXPIRY_DELTA, PaymentId};
691         use lightning::ln::functional_test_utils::*;
692         use lightning::ln::msgs::ChannelMessageHandler;
693         use lightning::routing::router::{PaymentParameters, RouteParameters, find_route};
694         use lightning::util::events::{MessageSendEvent, MessageSendEventsProvider, Event};
695         use lightning::util::test_utils;
696         use lightning::util::config::UserConfig;
697         use crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch;
698         use std::collections::HashSet;
699
700         #[test]
701         fn test_from_channelmanager() {
702                 let chanmon_cfgs = create_chanmon_cfgs(2);
703                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
704                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
705                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
706                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
707                 let non_default_invoice_expiry_secs = 4200;
708                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
709                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
710                         Some(10_000), "test".to_string(), Duration::from_secs(1234567),
711                         non_default_invoice_expiry_secs, None).unwrap();
712                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
713                 // If no `min_final_cltv_expiry_delta` is specified, then it should be `MIN_FINAL_CLTV_EXPIRY_DELTA`.
714                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
715                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
716                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
717
718                 // Invoice SCIDs should always use inbound SCID aliases over the real channel ID, if one is
719                 // available.
720                 let chan = &nodes[1].node.list_usable_channels()[0];
721                 assert_eq!(invoice.route_hints().len(), 1);
722                 assert_eq!(invoice.route_hints()[0].0.len(), 1);
723                 assert_eq!(invoice.route_hints()[0].0[0].short_channel_id, chan.inbound_scid_alias.unwrap());
724
725                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan.inbound_htlc_minimum_msat);
726                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan.inbound_htlc_maximum_msat);
727
728                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
729                                 invoice.min_final_cltv_expiry_delta() as u32)
730                         .with_features(invoice.features().unwrap().clone())
731                         .with_route_hints(invoice.route_hints());
732                 let route_params = RouteParameters {
733                         payment_params,
734                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
735                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
736                 };
737                 let first_hops = nodes[0].node.list_usable_channels();
738                 let network_graph = &node_cfgs[0].network_graph;
739                 let logger = test_utils::TestLogger::new();
740                 let scorer = test_utils::TestScorer::with_penalty(0);
741                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
742                 let route = find_route(
743                         &nodes[0].node.get_our_node_id(), &route_params, &network_graph,
744                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
745                 ).unwrap();
746
747                 let payment_event = {
748                         let mut payment_hash = PaymentHash([0; 32]);
749                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
750                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
751                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
752                         assert_eq!(added_monitors.len(), 1);
753                         added_monitors.clear();
754
755                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
756                         assert_eq!(events.len(), 1);
757                         SendEvent::from_event(events.remove(0))
758
759                 };
760                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
761                 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
762                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
763                 assert_eq!(added_monitors.len(), 1);
764                 added_monitors.clear();
765                 let events = nodes[1].node.get_and_clear_pending_msg_events();
766                 assert_eq!(events.len(), 2);
767         }
768
769         fn do_create_invoice_min_final_cltv_delta(with_custom_delta: bool) {
770                 let chanmon_cfgs = create_chanmon_cfgs(2);
771                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
772                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
773                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
774                 let custom_min_final_cltv_expiry_delta = Some(50);
775
776                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
777                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
778                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
779                         if with_custom_delta { custom_min_final_cltv_expiry_delta } else { None },
780                 ).unwrap();
781                 assert_eq!(invoice.min_final_cltv_expiry_delta(), if with_custom_delta {
782                         custom_min_final_cltv_expiry_delta.unwrap() + 3 /* Buffer */} else { MIN_FINAL_CLTV_EXPIRY_DELTA } as u64);
783         }
784
785         #[test]
786         fn test_create_invoice_custom_min_final_cltv_delta() {
787                 do_create_invoice_min_final_cltv_delta(true);
788                 do_create_invoice_min_final_cltv_delta(false);
789         }
790
791         #[test]
792         fn create_invoice_min_final_cltv_delta_equals_htlc_fail_buffer() {
793                 let chanmon_cfgs = create_chanmon_cfgs(2);
794                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
795                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
796                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
797                 let custom_min_final_cltv_expiry_delta = Some(21);
798
799                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
800                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
801                         Some(10_000), "".into(), Duration::from_secs(1234567), 3600,
802                         custom_min_final_cltv_expiry_delta,
803                 ).unwrap();
804                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
805         }
806
807         #[test]
808         fn test_create_invoice_with_description_hash() {
809                 let chanmon_cfgs = create_chanmon_cfgs(2);
810                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
811                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
812                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
813                 let description_hash = crate::Sha256(Hash::hash("Testing description_hash".as_bytes()));
814                 let invoice = crate::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(
815                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
816                         Some(10_000), description_hash, Duration::from_secs(1234567), 3600, None,
817                 ).unwrap();
818                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
819                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
820                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Testing description_hash".as_bytes()))));
821         }
822
823         #[test]
824         fn test_create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash() {
825                 let chanmon_cfgs = create_chanmon_cfgs(2);
826                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
827                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
828                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
829                 let payment_hash = PaymentHash([0; 32]);
830                 let invoice = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(
831                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
832                         Some(10_000), "test".to_string(), Duration::from_secs(1234567), 3600,
833                         payment_hash, None,
834                 ).unwrap();
835                 assert_eq!(invoice.amount_pico_btc(), Some(100_000));
836                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
837                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
838                 assert_eq!(invoice.payment_hash(), &sha256::Hash::from_slice(&payment_hash.0[..]).unwrap());
839         }
840
841         #[test]
842         fn test_hints_includes_single_channels_to_nodes() {
843                 let chanmon_cfgs = create_chanmon_cfgs(3);
844                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
845                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
846                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
847
848                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
849                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
850
851                 let mut scid_aliases = HashSet::new();
852                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
853                 scid_aliases.insert(chan_2_0.0.short_channel_id_alias.unwrap());
854
855                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
856         }
857
858         #[test]
859         fn test_hints_has_only_highest_inbound_capacity_channel() {
860                 let chanmon_cfgs = create_chanmon_cfgs(2);
861                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
862                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
863                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
864                 let _chan_1_0_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
865                 let chan_1_0_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
866                 let _chan_1_0_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 1_000_000, 0);
867                 let mut scid_aliases = HashSet::new();
868                 scid_aliases.insert(chan_1_0_high_inbound_capacity.0.short_channel_id_alias.unwrap());
869                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
870         }
871
872         #[test]
873         fn test_hints_has_only_online_channels() {
874                 let chanmon_cfgs = create_chanmon_cfgs(4);
875                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
876                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
877                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
878                 let chan_a = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 10_000_000, 0);
879                 let chan_b = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 10_000_000, 0);
880                 let _chan_c = create_unannounced_chan_between_nodes_with_value(&nodes, 3, 0, 1_000_000, 0);
881
882                 // With all peers connected we should get all hints that have sufficient value
883                 let mut scid_aliases = HashSet::new();
884                 scid_aliases.insert(chan_a.0.short_channel_id_alias.unwrap());
885                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
886
887                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
888
889                 // With only one sufficient-value peer connected we should only get its hint
890                 scid_aliases.remove(&chan_b.0.short_channel_id_alias.unwrap());
891                 nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
892                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases.clone());
893
894                 // If we don't have any sufficient-value peers connected we should get all hints with
895                 // sufficient value, even though there is a connected insufficient-value peer.
896                 scid_aliases.insert(chan_b.0.short_channel_id_alias.unwrap());
897                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
898                 match_invoice_routes(Some(1_000_000_000), &nodes[0], scid_aliases);
899         }
900
901         #[test]
902         fn test_forwarding_info_not_assigned_channel_excluded_from_hints() {
903                 let chanmon_cfgs = create_chanmon_cfgs(3);
904                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
905                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
906                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
907                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
908
909                 // Create an unannonced channel between `nodes[2]` and `nodes[0]`, for which the
910                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
911                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
912                 let mut private_chan_cfg = UserConfig::default();
913                 private_chan_cfg.channel_handshake_config.announced_channel = false;
914                 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();
915                 let open_channel = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
916                 nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_channel);
917                 let accept_channel = get_event_msg!(nodes[0], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
918                 nodes[2].node.handle_accept_channel(&nodes[0].node.get_our_node_id(), &accept_channel);
919
920                 let tx = sign_funding_transaction(&nodes[2], &nodes[0], 1_000_000, temporary_channel_id);
921
922                 let conf_height = core::cmp::max(nodes[2].best_block_info().1 + 1, nodes[0].best_block_info().1 + 1);
923                 confirm_transaction_at(&nodes[2], &tx, conf_height);
924                 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
925                 confirm_transaction_at(&nodes[0], &tx, conf_height);
926                 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH - 1);
927                 let as_channel_ready = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReady, nodes[0].node.get_our_node_id());
928                 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()));
929                 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
930                 nodes[0].node.handle_channel_ready(&nodes[2].node.get_our_node_id(), &as_channel_ready);
931                 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
932                 expect_channel_ready_event(&nodes[0], &nodes[2].node.get_our_node_id());
933                 expect_channel_ready_event(&nodes[2], &nodes[0].node.get_our_node_id());
934
935                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the second
936                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
937                 // Therefore only `chan_1_0` should be included in the hints.
938                 let mut scid_aliases = HashSet::new();
939                 scid_aliases.insert(chan_1_0.0.short_channel_id_alias.unwrap());
940                 match_invoice_routes(Some(5000), &nodes[0], scid_aliases);
941         }
942
943         #[test]
944         fn test_no_hints_if_a_mix_between_public_and_private_channel_exists() {
945                 let chanmon_cfgs = create_chanmon_cfgs(3);
946                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
947                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
948                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
949                 let _chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
950
951                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
952                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
953                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
954
955                 // Ensure that the invoice doesn't include any route hints for any of `nodes[0]` channels,
956                 // even though all channels between `nodes[1]` and `nodes[0]` are private, as there is a
957                 // public channel between `nodes[2]` and `nodes[0]`
958                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
959         }
960
961         #[test]
962         fn test_only_public_channels_includes_no_channels_in_hints() {
963                 let chanmon_cfgs = create_chanmon_cfgs(3);
964                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
965                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
966                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
967                 let chan_1_0 = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 100000, 10001);
968                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_1_0.0);
969                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_1_0.1);
970
971                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
972                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
973                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
974
975                 // As all of `nodes[0]` channels are public, no channels should be included in the hints
976                 match_invoice_routes(Some(5000), &nodes[0], HashSet::new());
977         }
978
979         #[test]
980         fn test_channels_with_lower_inbound_capacity_than_invoice_amt_hints_filtering() {
981                 let chanmon_cfgs = create_chanmon_cfgs(3);
982                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
983                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
984                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
985                 let chan_1_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 0, 100_000, 0);
986                 let chan_2_0 = create_unannounced_chan_between_nodes_with_value(&nodes, 2, 0, 1_000_000, 0);
987
988                 // As the invoice amt is 1 msat above chan_1_0's inbound capacity, it shouldn't be included
989                 let mut scid_aliases_99_000_001_msat = HashSet::new();
990                 scid_aliases_99_000_001_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
991
992                 match_invoice_routes(Some(99_000_001), &nodes[0], scid_aliases_99_000_001_msat);
993
994                 // As the invoice amt is exactly at chan_1_0's inbound capacity, it should be included
995                 let mut scid_aliases_99_000_000_msat = HashSet::new();
996                 scid_aliases_99_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
997                 scid_aliases_99_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
998
999                 match_invoice_routes(Some(99_000_000), &nodes[0], scid_aliases_99_000_000_msat);
1000
1001                 // As the invoice amt is above all channels' inbound capacity, they will still be included
1002                 let mut scid_aliases_2_000_000_000_msat = HashSet::new();
1003                 scid_aliases_2_000_000_000_msat.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1004                 scid_aliases_2_000_000_000_msat.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1005
1006                 match_invoice_routes(Some(2_000_000_000), &nodes[0], scid_aliases_2_000_000_000_msat);
1007
1008                 // An invoice with no specified amount should include all channels in the route hints.
1009                 let mut scid_aliases_no_specified_amount = HashSet::new();
1010                 scid_aliases_no_specified_amount.insert(chan_1_0.0.short_channel_id_alias.unwrap());
1011                 scid_aliases_no_specified_amount.insert(chan_2_0.0.short_channel_id_alias.unwrap());
1012
1013                 match_invoice_routes(None, &nodes[0], scid_aliases_no_specified_amount);
1014         }
1015
1016         fn match_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1017                 invoice_amt: Option<u64>,
1018                 invoice_node: &Node<'a, 'b, 'c>,
1019                 mut chan_ids_to_match: HashSet<u64>
1020         ) {
1021                 let invoice = create_invoice_from_channelmanager_and_duration_since_epoch(
1022                         &invoice_node.node, invoice_node.keys_manager, invoice_node.logger,
1023                         Currency::BitcoinTestnet, invoice_amt, "test".to_string(), Duration::from_secs(1234567),
1024                         3600, None).unwrap();
1025                 let hints = invoice.private_routes();
1026
1027                 for hint in hints {
1028                         let hint_short_chan_id = (hint.0).0[0].short_channel_id;
1029                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1030                 }
1031                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1032         }
1033
1034         #[test]
1035         #[cfg(feature = "std")]
1036         fn test_multi_node_receive() {
1037                 do_test_multi_node_receive(true);
1038                 do_test_multi_node_receive(false);
1039         }
1040
1041         #[cfg(feature = "std")]
1042         fn do_test_multi_node_receive(user_generated_pmt_hash: bool) {
1043                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1044                 let seed_1 = [42 as u8; 32];
1045                 let seed_2 = [43 as u8; 32];
1046                 let cross_node_seed = [44 as u8; 32];
1047                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1048                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1049                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1050                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1051                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1052                 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1053                 nodes[0].node.handle_channel_update(&nodes[1].node.get_our_node_id(), &chan_0_1.1);
1054                 nodes[1].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_1.0);
1055                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1056                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1057                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1058
1059                 let payment_amt = 10_000;
1060                 let route_hints = vec![
1061                         nodes[1].node.get_phantom_route_hints(),
1062                         nodes[2].node.get_phantom_route_hints(),
1063                 ];
1064
1065                 let user_payment_preimage = PaymentPreimage([1; 32]);
1066                 let payment_hash = if user_generated_pmt_hash {
1067                         Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()))
1068                 } else {
1069                         None
1070                 };
1071                 let non_default_invoice_expiry_secs = 4200;
1072
1073                 let invoice =
1074                         crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger>(
1075                                 Some(payment_amt), payment_hash, "test".to_string(), non_default_invoice_expiry_secs,
1076                                 route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1077                                 Currency::BitcoinTestnet, None, Duration::from_secs(1234567)
1078                         ).unwrap();
1079                 let (payment_hash, payment_secret) = (PaymentHash(invoice.payment_hash().into_inner()), *invoice.payment_secret());
1080                 let payment_preimage = if user_generated_pmt_hash {
1081                         user_payment_preimage
1082                 } else {
1083                         nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap()
1084                 };
1085
1086                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1087                 assert_eq!(invoice.description(), InvoiceDescription::Direct(&Description("test".to_string())));
1088                 assert_eq!(invoice.route_hints().len(), 2);
1089                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1090                 assert!(!invoice.features().unwrap().supports_basic_mpp());
1091
1092                 let payment_params = PaymentParameters::from_node_id(invoice.recover_payee_pub_key(),
1093                                 invoice.min_final_cltv_expiry_delta() as u32)
1094                         .with_features(invoice.features().unwrap().clone())
1095                         .with_route_hints(invoice.route_hints());
1096                 let params = RouteParameters {
1097                         payment_params,
1098                         final_value_msat: invoice.amount_milli_satoshis().unwrap(),
1099                         final_cltv_expiry_delta: invoice.min_final_cltv_expiry_delta() as u32,
1100                 };
1101                 let first_hops = nodes[0].node.list_usable_channels();
1102                 let network_graph = &node_cfgs[0].network_graph;
1103                 let logger = test_utils::TestLogger::new();
1104                 let scorer = test_utils::TestScorer::with_penalty(0);
1105                 let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
1106                 let route = find_route(
1107                         &nodes[0].node.get_our_node_id(), &params, &network_graph,
1108                         Some(&first_hops.iter().collect::<Vec<_>>()), &logger, &scorer, &random_seed_bytes
1109                 ).unwrap();
1110                 let (payment_event, fwd_idx) = {
1111                         let mut payment_hash = PaymentHash([0; 32]);
1112                         payment_hash.0.copy_from_slice(&invoice.payment_hash().as_ref()[0..32]);
1113                         nodes[0].node.send_payment(&route, payment_hash, &Some(invoice.payment_secret().clone()), PaymentId(payment_hash.0)).unwrap();
1114                         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
1115                         assert_eq!(added_monitors.len(), 1);
1116                         added_monitors.clear();
1117
1118                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1119                         assert_eq!(events.len(), 1);
1120                         let fwd_idx = match events[0] {
1121                                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
1122                                         if node_id == nodes[1].node.get_our_node_id() {
1123                                                 1
1124                                         } else { 2 }
1125                                 },
1126                                 _ => panic!("Unexpected event")
1127                         };
1128                         (SendEvent::from_event(events.remove(0)), fwd_idx)
1129                 };
1130                 nodes[fwd_idx].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1131                 commitment_signed_dance!(nodes[fwd_idx], nodes[0], &payment_event.commitment_msg, false, true);
1132
1133                 // Note that we have to "forward pending HTLCs" twice before we see the PaymentClaimable as
1134                 // this "emulates" the payment taking two hops, providing some privacy to make phantom node
1135                 // payments "look real" by taking more time.
1136                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1137                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1138                 expect_pending_htlcs_forwardable_ignore!(nodes[fwd_idx]);
1139                 nodes[fwd_idx].node.process_pending_htlc_forwards();
1140
1141                 let payment_preimage_opt = if user_generated_pmt_hash { None } else { Some(payment_preimage) };
1142                 expect_payment_claimable!(&nodes[fwd_idx], payment_hash, payment_secret, payment_amt, payment_preimage_opt, route.paths[0].last().unwrap().pubkey);
1143                 do_claim_payment_along_route(&nodes[0], &vec!(&vec!(&nodes[fwd_idx])[..]), false, payment_preimage);
1144                 let events = nodes[0].node.get_and_clear_pending_events();
1145                 assert_eq!(events.len(), 2);
1146                 match events[0] {
1147                         Event::PaymentSent { payment_preimage: ref ev_preimage, payment_hash: ref ev_hash, ref fee_paid_msat, .. } => {
1148                                 assert_eq!(payment_preimage, *ev_preimage);
1149                                 assert_eq!(payment_hash, *ev_hash);
1150                                 assert_eq!(fee_paid_msat, &Some(0));
1151                         },
1152                         _ => panic!("Unexpected event")
1153                 }
1154                 match events[1] {
1155                         Event::PaymentPathSuccessful { payment_hash: hash, .. } => {
1156                                 assert_eq!(hash, Some(payment_hash));
1157                         },
1158                         _ => panic!("Unexpected event")
1159                 }
1160         }
1161
1162         #[test]
1163         #[cfg(feature = "std")]
1164         fn test_multi_node_hints_has_htlc_min_max_values() {
1165                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1166                 let seed_1 = [42 as u8; 32];
1167                 let seed_2 = [43 as u8; 32];
1168                 let cross_node_seed = [44 as u8; 32];
1169                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1170                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1171                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1172                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1173                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1174
1175                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1176                 create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1177
1178                 let payment_amt = 20_000;
1179                 let (payment_hash, _payment_secret) = nodes[1].node.create_inbound_payment(Some(payment_amt), 3600, None).unwrap();
1180                 let route_hints = vec![
1181                         nodes[1].node.get_phantom_route_hints(),
1182                         nodes[2].node.get_phantom_route_hints(),
1183                 ];
1184
1185                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1186                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), Some(payment_hash),
1187                                 "test".to_string(), 3600, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1188                                 &nodes[1].logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1189
1190                 let chan_0_1 = &nodes[1].node.list_usable_channels()[0];
1191                 assert_eq!(invoice.route_hints()[0].0[0].htlc_minimum_msat, chan_0_1.inbound_htlc_minimum_msat);
1192                 assert_eq!(invoice.route_hints()[0].0[0].htlc_maximum_msat, chan_0_1.inbound_htlc_maximum_msat);
1193
1194                 let chan_0_2 = &nodes[2].node.list_usable_channels()[0];
1195                 assert_eq!(invoice.route_hints()[1].0[0].htlc_minimum_msat, chan_0_2.inbound_htlc_minimum_msat);
1196                 assert_eq!(invoice.route_hints()[1].0[0].htlc_maximum_msat, chan_0_2.inbound_htlc_maximum_msat);
1197         }
1198
1199         #[test]
1200         #[cfg(feature = "std")]
1201         fn create_phantom_invoice_with_description_hash() {
1202                 let chanmon_cfgs = create_chanmon_cfgs(3);
1203                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1204                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1205                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1206
1207                 let payment_amt = 20_000;
1208                 let route_hints = vec![
1209                         nodes[1].node.get_phantom_route_hints(),
1210                         nodes[2].node.get_phantom_route_hints(),
1211                 ];
1212
1213                 let description_hash = crate::Sha256(Hash::hash("Description hash phantom invoice".as_bytes()));
1214                 let non_default_invoice_expiry_secs = 4200;
1215                 let invoice = crate::utils::create_phantom_invoice_with_description_hash::<
1216                         &test_utils::TestKeysInterface, &test_utils::TestKeysInterface, &test_utils::TestLogger,
1217                 >(
1218                         Some(payment_amt), None, non_default_invoice_expiry_secs, description_hash,
1219                         route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager, &nodes[1].logger,
1220                         Currency::BitcoinTestnet, None, Duration::from_secs(1234567),
1221                 )
1222                 .unwrap();
1223                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1224                 assert_eq!(invoice.min_final_cltv_expiry_delta(), MIN_FINAL_CLTV_EXPIRY_DELTA as u64);
1225                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1226                 assert_eq!(invoice.description(), InvoiceDescription::Hash(&crate::Sha256(Sha256::hash("Description hash phantom invoice".as_bytes()))));
1227         }
1228
1229         #[test]
1230         #[cfg(feature = "std")]
1231         fn create_phantom_invoice_with_custom_payment_hash_and_custom_min_final_cltv_delta() {
1232                 let chanmon_cfgs = create_chanmon_cfgs(3);
1233                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1234                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1235                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1236
1237                 let payment_amt = 20_000;
1238                 let route_hints = vec![
1239                         nodes[1].node.get_phantom_route_hints(),
1240                         nodes[2].node.get_phantom_route_hints(),
1241                 ];
1242                 let user_payment_preimage = PaymentPreimage([1; 32]);
1243                 let payment_hash = Some(PaymentHash(Sha256::hash(&user_payment_preimage.0[..]).into_inner()));
1244                 let non_default_invoice_expiry_secs = 4200;
1245                 let min_final_cltv_expiry_delta = Some(100);
1246                 let duration_since_epoch = Duration::from_secs(1234567);
1247                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1248                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(Some(payment_amt), payment_hash,
1249                                 "".to_string(), non_default_invoice_expiry_secs, route_hints, &nodes[1].keys_manager, &nodes[1].keys_manager,
1250                                 &nodes[1].logger, Currency::BitcoinTestnet, min_final_cltv_expiry_delta, duration_since_epoch).unwrap();
1251                 assert_eq!(invoice.amount_pico_btc(), Some(200_000));
1252                 assert_eq!(invoice.min_final_cltv_expiry_delta(), (min_final_cltv_expiry_delta.unwrap() + 3) as u64);
1253                 assert_eq!(invoice.expiry_time(), Duration::from_secs(non_default_invoice_expiry_secs.into()));
1254         }
1255
1256         #[test]
1257         #[cfg(feature = "std")]
1258         fn test_multi_node_hints_includes_single_channels_to_participating_nodes() {
1259                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1260                 let seed_1 = [42 as u8; 32];
1261                 let seed_2 = [43 as u8; 32];
1262                 let cross_node_seed = [44 as u8; 32];
1263                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1264                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1265                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1266                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1267                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1268
1269                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1270                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1271
1272                 let mut scid_aliases = HashSet::new();
1273                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1274                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1275
1276                 match_multi_node_invoice_routes(
1277                         Some(10_000),
1278                         &nodes[1],
1279                         vec![&nodes[1], &nodes[2],],
1280                         scid_aliases,
1281                         false
1282                 );
1283         }
1284
1285         #[test]
1286         #[cfg(feature = "std")]
1287         fn test_multi_node_hints_includes_one_channel_of_each_counterparty_nodes_per_participating_node() {
1288                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1289                 let seed_1 = [42 as u8; 32];
1290                 let seed_2 = [43 as u8; 32];
1291                 let cross_node_seed = [44 as u8; 32];
1292                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1293                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1294                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1295                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1296                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1297
1298                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1299                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1300                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 3_000_000, 10005);
1301
1302                 let mut scid_aliases = HashSet::new();
1303                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1304                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1305                 scid_aliases.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1306
1307                 match_multi_node_invoice_routes(
1308                         Some(10_000),
1309                         &nodes[2],
1310                         vec![&nodes[2], &nodes[3],],
1311                         scid_aliases,
1312                         false
1313                 );
1314         }
1315
1316         #[test]
1317         #[cfg(feature = "std")]
1318         fn test_multi_node_forwarding_info_not_assigned_channel_excluded_from_hints() {
1319                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1320                 let seed_1 = [42 as u8; 32];
1321                 let seed_2 = [43 as u8; 32];
1322                 let cross_node_seed = [44 as u8; 32];
1323                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1324                 chanmon_cfgs[3].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1325                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1326                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1327                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1328
1329                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1330                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 1000000, 10001);
1331
1332                 // Create an unannonced channel between `nodes[1]` and `nodes[3]`, for which the
1333                 // `msgs::ChannelUpdate` is never handled for the node(s). As the `msgs::ChannelUpdate`
1334                 // is never handled, the `channel.counterparty.forwarding_info` is never assigned.
1335                 let mut private_chan_cfg = UserConfig::default();
1336                 private_chan_cfg.channel_handshake_config.announced_channel = false;
1337                 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();
1338                 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[3].node.get_our_node_id());
1339                 nodes[3].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_channel);
1340                 let accept_channel = get_event_msg!(nodes[3], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
1341                 nodes[1].node.handle_accept_channel(&nodes[3].node.get_our_node_id(), &accept_channel);
1342
1343                 let tx = sign_funding_transaction(&nodes[1], &nodes[3], 1_000_000, temporary_channel_id);
1344
1345                 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[3].best_block_info().1 + 1);
1346                 confirm_transaction_at(&nodes[1], &tx, conf_height);
1347                 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
1348                 confirm_transaction_at(&nodes[3], &tx, conf_height);
1349                 connect_blocks(&nodes[3], CHAN_CONFIRM_DEPTH - 1);
1350                 let as_channel_ready = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReady, nodes[3].node.get_our_node_id());
1351                 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()));
1352                 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[3].node.get_our_node_id());
1353                 nodes[3].node.handle_channel_ready(&nodes[1].node.get_our_node_id(), &as_channel_ready);
1354                 get_event_msg!(nodes[3], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
1355                 expect_channel_ready_event(&nodes[1], &nodes[3].node.get_our_node_id());
1356                 expect_channel_ready_event(&nodes[3], &nodes[1].node.get_our_node_id());
1357
1358                 // As `msgs::ChannelUpdate` was never handled for the participating node(s) of the third
1359                 // channel, the channel will never be assigned any `counterparty.forwarding_info`.
1360                 // Therefore only `chan_0_3` should be included in the hints for `nodes[3]`.
1361                 let mut scid_aliases = HashSet::new();
1362                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1363                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1364
1365                 match_multi_node_invoice_routes(
1366                         Some(10_000),
1367                         &nodes[2],
1368                         vec![&nodes[2], &nodes[3],],
1369                         scid_aliases,
1370                         false
1371                 );
1372         }
1373
1374         #[test]
1375         #[cfg(feature = "std")]
1376         fn test_multi_node_with_only_public_channels_hints_includes_only_phantom_route() {
1377                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1378                 let seed_1 = [42 as u8; 32];
1379                 let seed_2 = [43 as u8; 32];
1380                 let cross_node_seed = [44 as u8; 32];
1381                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1382                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1383                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1384                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1385                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1386
1387                 let chan_0_1 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
1388
1389                 let chan_2_0 = create_announced_chan_between_nodes_with_value(&nodes, 2, 0, 100000, 10001);
1390                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_2_0.1);
1391                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_2_0.0);
1392
1393                 // Hints should include `chan_0_1` from as `nodes[1]` only have private channels, but not
1394                 // `chan_0_2` as `nodes[2]` only has public channels.
1395                 let mut scid_aliases = HashSet::new();
1396                 scid_aliases.insert(chan_0_1.0.short_channel_id_alias.unwrap());
1397
1398                 match_multi_node_invoice_routes(
1399                         Some(10_000),
1400                         &nodes[1],
1401                         vec![&nodes[1], &nodes[2],],
1402                         scid_aliases,
1403                         true
1404                 );
1405         }
1406
1407         #[test]
1408         #[cfg(feature = "std")]
1409         fn test_multi_node_with_mixed_public_and_private_channel_hints_includes_only_phantom_route() {
1410                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1411                 let seed_1 = [42 as u8; 32];
1412                 let seed_2 = [43 as u8; 32];
1413                 let cross_node_seed = [44 as u8; 32];
1414                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1415                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1416                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1417                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1418                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1419
1420                 let chan_0_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1421                 nodes[0].node.handle_channel_update(&nodes[2].node.get_our_node_id(), &chan_0_2.1);
1422                 nodes[2].node.handle_channel_update(&nodes[0].node.get_our_node_id(), &chan_0_2.0);
1423                 let _chan_1_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
1424
1425                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100000, 10001);
1426
1427                 // Hints should include `chan_0_3` from as `nodes[3]` only have private channels, and no
1428                 // channels for `nodes[2]` as it contains a mix of public and private channels.
1429                 let mut scid_aliases = HashSet::new();
1430                 scid_aliases.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1431
1432                 match_multi_node_invoice_routes(
1433                         Some(10_000),
1434                         &nodes[2],
1435                         vec![&nodes[2], &nodes[3],],
1436                         scid_aliases,
1437                         true
1438                 );
1439         }
1440
1441         #[test]
1442         #[cfg(feature = "std")]
1443         fn test_multi_node_hints_has_only_highest_inbound_capacity_channel() {
1444                 let mut chanmon_cfgs = create_chanmon_cfgs(3);
1445                 let seed_1 = [42 as u8; 32];
1446                 let seed_2 = [43 as u8; 32];
1447                 let cross_node_seed = [44 as u8; 32];
1448                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1449                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1450                 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1451                 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1452                 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1453
1454                 let _chan_0_1_low_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
1455                 let chan_0_1_high_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 10_000_000, 0);
1456                 let _chan_0_1_medium_inbound_capacity = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
1457                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
1458
1459                 let mut scid_aliases = HashSet::new();
1460                 scid_aliases.insert(chan_0_1_high_inbound_capacity.0.short_channel_id_alias.unwrap());
1461                 scid_aliases.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1462
1463                 match_multi_node_invoice_routes(
1464                         Some(10_000),
1465                         &nodes[1],
1466                         vec![&nodes[1], &nodes[2],],
1467                         scid_aliases,
1468                         false
1469                 );
1470         }
1471
1472         #[test]
1473         #[cfg(feature = "std")]
1474         fn test_multi_node_channels_inbound_capacity_lower_than_invoice_amt_filtering() {
1475                 let mut chanmon_cfgs = create_chanmon_cfgs(4);
1476                 let seed_1 = [42 as u8; 32];
1477                 let seed_2 = [43 as u8; 32];
1478                 let cross_node_seed = [44 as u8; 32];
1479                 chanmon_cfgs[1].keys_manager.backing = PhantomKeysManager::new(&seed_1, 43, 44, &cross_node_seed);
1480                 chanmon_cfgs[2].keys_manager.backing = PhantomKeysManager::new(&seed_2, 43, 44, &cross_node_seed);
1481                 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1482                 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1483                 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1484
1485                 let chan_0_2 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 2, 1_000_000, 0);
1486                 let chan_0_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 0, 3, 100_000, 0);
1487                 let chan_1_3 = create_unannounced_chan_between_nodes_with_value(&nodes, 1, 3, 200_000, 0);
1488
1489                 // Since the invoice 1 msat above chan_0_3's inbound capacity, it should be filtered out.
1490                 let mut scid_aliases_99_000_001_msat = HashSet::new();
1491                 scid_aliases_99_000_001_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1492                 scid_aliases_99_000_001_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1493
1494                 match_multi_node_invoice_routes(
1495                         Some(99_000_001),
1496                         &nodes[2],
1497                         vec![&nodes[2], &nodes[3],],
1498                         scid_aliases_99_000_001_msat,
1499                         false
1500                 );
1501
1502                 // Since the invoice is exactly at chan_0_3's inbound capacity, it should be included.
1503                 let mut scid_aliases_99_000_000_msat = HashSet::new();
1504                 scid_aliases_99_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1505                 scid_aliases_99_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1506                 scid_aliases_99_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1507
1508                 match_multi_node_invoice_routes(
1509                         Some(99_000_000),
1510                         &nodes[2],
1511                         vec![&nodes[2], &nodes[3],],
1512                         scid_aliases_99_000_000_msat,
1513                         false
1514                 );
1515
1516                 // Since the invoice is above all of `nodes[2]` channels' inbound capacity, all of
1517                 // `nodes[2]` them should be included.
1518                 let mut scid_aliases_300_000_000_msat = HashSet::new();
1519                 scid_aliases_300_000_000_msat.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1520                 scid_aliases_300_000_000_msat.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1521                 scid_aliases_300_000_000_msat.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1522
1523                 match_multi_node_invoice_routes(
1524                         Some(300_000_000),
1525                         &nodes[2],
1526                         vec![&nodes[2], &nodes[3],],
1527                         scid_aliases_300_000_000_msat,
1528                         false
1529                 );
1530
1531                 // Since the no specified amount, all channels should included.
1532                 let mut scid_aliases_no_specified_amount = HashSet::new();
1533                 scid_aliases_no_specified_amount.insert(chan_0_2.0.short_channel_id_alias.unwrap());
1534                 scid_aliases_no_specified_amount.insert(chan_0_3.0.short_channel_id_alias.unwrap());
1535                 scid_aliases_no_specified_amount.insert(chan_1_3.0.short_channel_id_alias.unwrap());
1536
1537                 match_multi_node_invoice_routes(
1538                         None,
1539                         &nodes[2],
1540                         vec![&nodes[2], &nodes[3],],
1541                         scid_aliases_no_specified_amount,
1542                         false
1543                 );
1544         }
1545
1546         #[cfg(feature = "std")]
1547         fn match_multi_node_invoice_routes<'a, 'b: 'a, 'c: 'b>(
1548                 invoice_amt: Option<u64>,
1549                 invoice_node: &Node<'a, 'b, 'c>,
1550                 network_multi_nodes: Vec<&Node<'a, 'b, 'c>>,
1551                 mut chan_ids_to_match: HashSet<u64>,
1552                 nodes_contains_public_channels: bool
1553         ){
1554                 let phantom_route_hints = network_multi_nodes.iter()
1555                         .map(|node| node.node.get_phantom_route_hints())
1556                         .collect::<Vec<PhantomRouteHints>>();
1557                 let phantom_scids = phantom_route_hints.iter()
1558                         .map(|route_hint| route_hint.phantom_scid)
1559                         .collect::<HashSet<u64>>();
1560
1561                 let invoice = crate::utils::create_phantom_invoice::<&test_utils::TestKeysInterface,
1562                         &test_utils::TestKeysInterface, &test_utils::TestLogger>(invoice_amt, None, "test".to_string(),
1563                                 3600, phantom_route_hints, &invoice_node.keys_manager, &invoice_node.keys_manager,
1564                                 &invoice_node.logger, Currency::BitcoinTestnet, None, Duration::from_secs(1234567)).unwrap();
1565
1566                 let invoice_hints = invoice.private_routes();
1567
1568                 for hint in invoice_hints {
1569                         let hints = &(hint.0).0;
1570                         match hints.len() {
1571                                 1 => {
1572                                         assert!(nodes_contains_public_channels);
1573                                         let phantom_scid = hints[0].short_channel_id;
1574                                         assert!(phantom_scids.contains(&phantom_scid));
1575                                 },
1576                                 2 => {
1577                                         let hint_short_chan_id = hints[0].short_channel_id;
1578                                         assert!(chan_ids_to_match.remove(&hint_short_chan_id));
1579                                         let phantom_scid = hints[1].short_channel_id;
1580                                         assert!(phantom_scids.contains(&phantom_scid));
1581                                 },
1582                                 _ => panic!("Incorrect hint length generated")
1583                         }
1584                 }
1585                 assert!(chan_ids_to_match.is_empty(), "Unmatched short channel ids: {:?}", chan_ids_to_match);
1586         }
1587
1588         #[test]
1589         fn test_create_invoice_fails_with_invalid_custom_min_final_cltv_expiry_delta() {
1590                 let chanmon_cfgs = create_chanmon_cfgs(2);
1591                 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1592                 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1593                 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1594                 let result = crate::utils::create_invoice_from_channelmanager_and_duration_since_epoch(
1595                         &nodes[1].node, nodes[1].keys_manager, nodes[1].logger, Currency::BitcoinTestnet,
1596                         Some(10_000), "Some description".into(), Duration::from_secs(1234567), 3600, Some(MIN_FINAL_CLTV_EXPIRY_DELTA - 4),
1597                 );
1598                 match result {
1599                         Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort)) => {},
1600                         _ => panic!(),
1601                 }
1602         }
1603 }