Skip to content

Commit 6842c1f

Browse files
committed
Add a BOLT11 invoice utility to ChannelManager
Now that the lightning crate depends on the lightning_invoice crate, the utility functions previously living in the latter can be implemented on ChannelManager. Additionally, the parameters are now moved to a struct in order to remove the increasingly combinatorial blow-up of methods. The new Bolt11InvoiceParameters is used to determine what values to set in the invoice. Using None for any given parameter results in a reasonable the default or a behavior determined by the ChannelManager as detailed in the documentation.
1 parent 9b65531 commit 6842c1f

File tree

2 files changed

+237
-171
lines changed

2 files changed

+237
-171
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ use {
102102
crate::offers::refund::RefundMaybeWithDerivedMetadataBuilder,
103103
};
104104

105+
use lightning_invoice::{Bolt11Invoice, Bolt11InvoiceDescription, CreationError, Currency, InvoiceBuilder as Bolt11InvoiceBuilder, SignOrCreationError, DEFAULT_EXPIRY_TIME};
106+
105107
use alloc::collections::{btree_map, BTreeMap};
106108

107109
use crate::io;
@@ -9093,6 +9095,144 @@ where
90939095
self.finish_close_channel(failure);
90949096
}
90959097
}
9098+
9099+
/// Utility for creating a BOLT11 invoice that can be verified by [`ChannelManager`] without
9100+
/// storing any additional state. It achieves this by including a [`PaymentSecret`] in the
9101+
/// invoice for which it uses to verify that the invoice has not expired and the payment amount
9102+
/// is sufficient, reproducing the [`PaymentPreimage`] if applicable.
9103+
pub fn create_bolt11_invoice(
9104+
&self, params: Bolt11InvoiceParameters,
9105+
) -> Result<Bolt11Invoice, SignOrCreationError<()>> {
9106+
let Bolt11InvoiceParameters {
9107+
currency, amount_msats, description, duration_since_epoch, invoice_expiry_delta_secs,
9108+
min_final_cltv_expiry_delta, payment_hash,
9109+
} = params;
9110+
9111+
let currency = match currency {
9112+
Some(currency) => currency,
9113+
None => Network::from_chain_hash(self.chain_hash).map(Into::into).unwrap_or(Currency::Bitcoin),
9114+
};
9115+
9116+
#[cfg(feature = "std")]
9117+
let duration_since_epoch = duration_since_epoch
9118+
.unwrap_or_else(|| {
9119+
use std::time::SystemTime;
9120+
SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)
9121+
.expect("for the foreseeable future this shouldn't happen")
9122+
});
9123+
#[cfg(not(feature = "std"))]
9124+
let duration_since_epoch = duration_since_epoch.unwrap_or_else(||
9125+
Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
9126+
);
9127+
9128+
if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
9129+
if min_final_cltv_expiry_delta.saturating_add(3) < MIN_FINAL_CLTV_EXPIRY_DELTA {
9130+
return Err(SignOrCreationError::CreationError(CreationError::MinFinalCltvExpiryDeltaTooShort));
9131+
}
9132+
}
9133+
9134+
let (payment_hash, payment_secret) = match payment_hash {
9135+
Some(payment_hash) => {
9136+
let payment_secret = self
9137+
.create_inbound_payment_for_hash(
9138+
payment_hash, amount_msats,
9139+
invoice_expiry_delta_secs.unwrap_or(DEFAULT_EXPIRY_TIME as u32),
9140+
min_final_cltv_expiry_delta,
9141+
)
9142+
.map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?;
9143+
(payment_hash, payment_secret)
9144+
},
9145+
None => {
9146+
self
9147+
.create_inbound_payment(
9148+
amount_msats, invoice_expiry_delta_secs.unwrap_or(DEFAULT_EXPIRY_TIME as u32),
9149+
min_final_cltv_expiry_delta,
9150+
)
9151+
.map_err(|()| SignOrCreationError::CreationError(CreationError::InvalidAmount))?
9152+
},
9153+
};
9154+
9155+
log_trace!(self.logger, "Creating invoice with payment hash {}", &payment_hash);
9156+
9157+
let invoice = Bolt11InvoiceBuilder::new(currency);
9158+
let invoice = match description {
9159+
Bolt11InvoiceDescription::Direct(description) => invoice.description(description.into_inner().0),
9160+
Bolt11InvoiceDescription::Hash(hash) => invoice.description_hash(hash.0),
9161+
};
9162+
9163+
let mut invoice = invoice
9164+
.duration_since_epoch(duration_since_epoch)
9165+
.payee_pub_key(self.get_our_node_id())
9166+
.payment_hash(Hash::from_slice(&payment_hash.0).unwrap())
9167+
.payment_secret(payment_secret)
9168+
.basic_mpp()
9169+
.min_final_cltv_expiry_delta(
9170+
// Add a buffer of 3 to the delta if present, otherwise use LDK's minimum.
9171+
min_final_cltv_expiry_delta.map(|x| x.saturating_add(3)).unwrap_or(MIN_FINAL_CLTV_EXPIRY_DELTA).into()
9172+
);
9173+
9174+
if let Some(invoice_expiry_delta_secs) = invoice_expiry_delta_secs{
9175+
invoice = invoice.expiry_time(Duration::from_secs(invoice_expiry_delta_secs.into()));
9176+
}
9177+
9178+
if let Some(amount_msats) = amount_msats {
9179+
invoice = invoice.amount_milli_satoshis(amount_msats);
9180+
}
9181+
9182+
let channels = self.list_channels();
9183+
let route_hints = super::invoice_utils::sort_and_filter_channels(channels, amount_msats, &self.logger);
9184+
for hint in route_hints {
9185+
invoice = invoice.private_route(hint);
9186+
}
9187+
9188+
let raw_invoice = invoice.build_raw().map_err(|e| SignOrCreationError::CreationError(e))?;
9189+
let signature = self.node_signer.sign_invoice(&raw_invoice, Recipient::Node);
9190+
9191+
raw_invoice
9192+
.sign(|_| signature)
9193+
.map(|invoice| Bolt11Invoice::from_signed(invoice).unwrap())
9194+
.map_err(|e| SignOrCreationError::SignError(e))
9195+
}
9196+
}
9197+
9198+
/// Parameters used with [`create_bolt11_invoice`].
9199+
///
9200+
/// [`create_bolt11_invoice`]: ChannelManager::create_bolt11_invoice
9201+
pub struct Bolt11InvoiceParameters {
9202+
/// A BIP-0173 currency. If not set, uses the [`Currency`] for the [`Network`] used when
9203+
/// initializing [`ChannelManager`]. See [`ChainParameters::network`].
9204+
pub currency: Option<Currency>,
9205+
9206+
/// The amount for the invoice, if any.
9207+
pub amount_msats: Option<u64>,
9208+
9209+
/// The description for what the invoice is for, or hash of such description.
9210+
pub description: Bolt11InvoiceDescription,
9211+
9212+
/// The duration since the Unix epoch signifying when the invoice was created. If not set,
9213+
/// the current time is used or the highest timestamp seen for non-`std` builds.
9214+
pub duration_since_epoch: Option<Duration>,
9215+
9216+
/// The invoice expiration relative to [`duration_since_epoch`]. If not set, the invoice will
9217+
/// expire in [`DEFAULT_EXPIRY_TIME`] by default.
9218+
///
9219+
/// [`duration_since_epoch`]: Self::duration_since_epoch
9220+
pub invoice_expiry_delta_secs: Option<u32>,
9221+
9222+
/// The minimum `cltv_expiry` for the last HTLC in the route. If not set, will use
9223+
/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
9224+
///
9225+
/// If set, must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`], and a three-block buffer will be
9226+
/// added as well to allow for up to a few new block confirmations during routing.
9227+
pub min_final_cltv_expiry_delta: Option<u16>,
9228+
9229+
/// The payment hash used in the invoice. If not set, a payment hash will be generated using a
9230+
/// preimage that can be reproduced by [`ChannelManager`] without storing any state.
9231+
///
9232+
/// Uses the payment hash if set. This may be useful if you're building an on-chain swap or
9233+
/// involving another protocol where the payment hash is also involved outside the scope of
9234+
/// lightning.
9235+
pub payment_hash: Option<PaymentHash>,
90969236
}
90979237

90989238
macro_rules! create_offer_builder { ($self: ident, $builder: ty) => {

0 commit comments

Comments
 (0)