1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Utilities to generate inbound payment information in service of invoice creation.
12 use bitcoin::hashes::{Hash, HashEngine};
13 use bitcoin::hashes::cmp::fixed_time_eq;
14 use bitcoin::hashes::hmac::{Hmac, HmacEngine};
15 use bitcoin::hashes::sha256::Hash as Sha256;
16 use crate::sign::{KeyMaterial, EntropySource};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::msgs::MAX_VALUE_MSAT;
20 use crate::crypto::chacha20::ChaCha20;
21 use crate::crypto::utils::hkdf_extract_expand_5x;
22 use crate::util::errors::APIError;
23 use crate::util::logger::Logger;
25 #[allow(unused_imports)]
26 use crate::prelude::*;
30 pub(crate) const IV_LEN: usize = 16;
31 const METADATA_LEN: usize = 16;
32 const METADATA_KEY_LEN: usize = 32;
33 const AMT_MSAT_LEN: usize = 8;
34 // Used to shift the payment type bits to take up the top 3 bits of the metadata bytes, or to
35 // retrieve said payment type bits.
36 const METHOD_TYPE_OFFSET: usize = 5;
38 /// A set of keys that were HKDF-expanded from an initial call to
39 /// [`NodeSigner::get_inbound_payment_key_material`].
41 /// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
42 pub struct ExpandedKey {
43 /// The key used to encrypt the bytes containing the payment metadata (i.e. the amount and
44 /// expiry, included for payment verification on decryption).
45 metadata_key: [u8; 32],
46 /// The key used to authenticate an LDK-provided payment hash and metadata as previously
47 /// registered with LDK.
48 ldk_pmt_hash_key: [u8; 32],
49 /// The key used to authenticate a user-provided payment hash and metadata as previously
50 /// registered with LDK.
51 user_pmt_hash_key: [u8; 32],
52 /// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
53 offers_base_key: [u8; 32],
54 /// The key used to encrypt message metadata for BOLT 12 Offers.
55 offers_encryption_key: [u8; 32],
59 /// Create a new [`ExpandedKey`] for generating an inbound payment hash and secret.
61 /// It is recommended to cache this value and not regenerate it for each new inbound payment.
62 pub fn new(key_material: &KeyMaterial) -> ExpandedKey {
68 offers_encryption_key,
69 ) = hkdf_extract_expand_5x(b"LDK Inbound Payment Key Expansion", &key_material.0);
75 offers_encryption_key,
79 /// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
81 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
82 pub(crate) fn hmac_for_offer(
83 &self, nonce: Nonce, iv_bytes: &[u8; IV_LEN]
84 ) -> HmacEngine<Sha256> {
85 let mut hmac = HmacEngine::<Sha256>::new(&self.offers_base_key);
91 /// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
92 /// metadata (e.g., payment id).
93 pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
94 ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
99 /// A 128-bit number used only once.
101 /// Needed when constructing [`Offer::metadata`] and deriving [`Offer::signing_pubkey`] from
102 /// [`ExpandedKey`]. Must not be reused for any other derivation without first hashing.
104 /// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
105 /// [`Offer::signing_pubkey`]: crate::offers::offer::Offer::signing_pubkey
106 #[derive(Clone, Copy, Debug, PartialEq)]
107 pub(crate) struct Nonce(pub(crate) [u8; Self::LENGTH]);
110 /// Number of bytes in the nonce.
111 pub const LENGTH: usize = 16;
113 /// Creates a `Nonce` from the given [`EntropySource`].
114 pub fn from_entropy_source<ES: Deref>(entropy_source: ES) -> Self
116 ES::Target: EntropySource,
118 let mut bytes = [0u8; Self::LENGTH];
119 let rand_bytes = entropy_source.get_secure_random_bytes();
120 bytes.copy_from_slice(&rand_bytes[..Self::LENGTH]);
125 /// Returns a slice of the underlying bytes of size [`Nonce::LENGTH`].
126 pub fn as_slice(&self) -> &[u8] {
131 impl TryFrom<&[u8]> for Nonce {
134 fn try_from(bytes: &[u8]) -> Result<Self, ()> {
135 if bytes.len() != Self::LENGTH {
139 let mut copied_bytes = [0u8; Self::LENGTH];
140 copied_bytes.copy_from_slice(bytes);
142 Ok(Self(copied_bytes))
149 LdkPaymentHashCustomFinalCltv = 2,
150 UserPaymentHashCustomFinalCltv = 3,
154 fn from_bits(bits: u8) -> Result<Method, u8> {
156 bits if bits == Method::LdkPaymentHash as u8 => Ok(Method::LdkPaymentHash),
157 bits if bits == Method::UserPaymentHash as u8 => Ok(Method::UserPaymentHash),
158 bits if bits == Method::LdkPaymentHashCustomFinalCltv as u8 => Ok(Method::LdkPaymentHashCustomFinalCltv),
159 bits if bits == Method::UserPaymentHashCustomFinalCltv as u8 => Ok(Method::UserPaymentHashCustomFinalCltv),
160 unknown => Err(unknown),
165 fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 {
166 let expiry_bytes = &bytes[AMT_MSAT_LEN..];
167 u16::from_be_bytes([expiry_bytes[0], expiry_bytes[1]])
170 /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment`], but no
171 /// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without
172 /// a `ChannelManager`.
174 /// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key_material`] and then
175 /// calling [`ExpandedKey::new`] with its result. It is recommended to cache this value and not
176 /// regenerate it for each new inbound payment.
178 /// `current_time` is a Unix timestamp representing the current time.
180 /// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
181 /// on versions of LDK prior to 0.0.114.
183 /// [phantom node payments]: crate::sign::PhantomKeysManager
184 /// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
185 pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>,
186 invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64,
187 min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()>
188 where ES::Target: EntropySource
190 let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
191 Method::LdkPaymentHashCustomFinalCltv
193 Method::LdkPaymentHash
194 }, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
196 let mut iv_bytes = [0 as u8; IV_LEN];
197 let rand_bytes = entropy_source.get_secure_random_bytes();
198 iv_bytes.copy_from_slice(&rand_bytes[..IV_LEN]);
200 let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
201 hmac.input(&iv_bytes);
202 hmac.input(&metadata_bytes);
203 let payment_preimage_bytes = Hmac::from_engine(hmac).to_byte_array();
205 let ldk_pmt_hash = PaymentHash(Sha256::hash(&payment_preimage_bytes).to_byte_array());
206 let payment_secret = construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key);
207 Ok((ldk_pmt_hash, payment_secret))
210 /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`],
211 /// but no `ChannelManager` is required. Useful for generating invoices for [phantom node payments]
212 /// without a `ChannelManager`.
214 /// See [`create`] for information on the `keys` and `current_time` parameters.
216 /// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
217 /// on versions of LDK prior to 0.0.114.
219 /// [phantom node payments]: crate::sign::PhantomKeysManager
220 pub fn create_from_hash(keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash,
221 invoice_expiry_delta_secs: u32, current_time: u64, min_final_cltv_expiry_delta: Option<u16>) -> Result<PaymentSecret, ()> {
222 let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
223 Method::UserPaymentHashCustomFinalCltv
225 Method::UserPaymentHash
226 }, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
228 let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
229 hmac.input(&metadata_bytes);
230 hmac.input(&payment_hash.0);
231 let hmac_bytes = Hmac::from_engine(hmac).to_byte_array();
233 let mut iv_bytes = [0 as u8; IV_LEN];
234 iv_bytes.copy_from_slice(&hmac_bytes[..IV_LEN]);
236 Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
239 fn construct_metadata_bytes(min_value_msat: Option<u64>, payment_type: Method,
240 invoice_expiry_delta_secs: u32, highest_seen_timestamp: u64, min_final_cltv_expiry_delta: Option<u16>) -> Result<[u8; METADATA_LEN], ()> {
241 if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
245 let mut min_amt_msat_bytes: [u8; AMT_MSAT_LEN] = match min_value_msat {
246 Some(amt) => amt.to_be_bytes(),
247 None => [0; AMT_MSAT_LEN],
249 min_amt_msat_bytes[0] |= (payment_type as u8) << METHOD_TYPE_OFFSET;
251 // We assume that highest_seen_timestamp is pretty close to the current time - it's updated when
252 // we receive a new block with the maximum time we've seen in a header. It should never be more
253 // than two hours in the future. Thus, we add two hours here as a buffer to ensure we
254 // absolutely never fail a payment too early.
255 // Note that we assume that received blocks have reasonably up-to-date timestamps.
256 let expiry_timestamp = highest_seen_timestamp + invoice_expiry_delta_secs as u64 + 7200;
257 let mut expiry_bytes = expiry_timestamp.to_be_bytes();
259 // `min_value_msat` should fit in (64 bits - 3 payment type bits =) 61 bits as an unsigned integer.
260 // This should leave us with a maximum value greater than the 21M BTC supply cap anyway.
261 if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) { return Err(()); }
263 // `expiry_timestamp` should fit in (64 bits - 2 delta bytes =) 48 bits as an unsigned integer.
264 // Bitcoin's block header timestamps are actually `u32`s, so we're technically already limited to
265 // the much smaller maximum timestamp of `u32::MAX` for now, but we check the u64 `expiry_timestamp`
266 // for future-proofing.
267 if min_final_cltv_expiry_delta.is_some() && expiry_timestamp > ((1u64 << 48) - 1) { return Err(()); }
269 if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
270 let bytes = min_final_cltv_expiry_delta.to_be_bytes();
271 expiry_bytes[0] |= bytes[0];
272 expiry_bytes[1] |= bytes[1];
275 let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
277 metadata_bytes[..AMT_MSAT_LEN].copy_from_slice(&min_amt_msat_bytes);
278 metadata_bytes[AMT_MSAT_LEN..].copy_from_slice(&expiry_bytes);
283 fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], metadata_key: &[u8; METADATA_KEY_LEN]) -> PaymentSecret {
284 let mut payment_secret_bytes: [u8; 32] = [0; 32];
285 let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
286 iv_slice.copy_from_slice(iv_bytes);
288 ChaCha20::encrypt_single_block(
289 metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
291 PaymentSecret(payment_secret_bytes)
294 /// Check that an inbound payment's `payment_data` field is sane.
296 /// LDK does not store any data for pending inbound payments. Instead, we construct our payment
297 /// secret (and, if supplied by LDK, our payment preimage) to include encrypted metadata about the
300 /// For payments without a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
301 /// payment method (3 bits) || payment amount (8 bytes - 3 bits) || expiry (8 bytes)
303 /// For payments including a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
304 /// payment method (3 bits) || payment amount (8 bytes - 3 bits) || min_final_cltv_expiry_delta (2 bytes) || expiry (6 bytes)
306 /// In both cases the result is then encrypted using a key derived from [`NodeSigner::get_inbound_payment_key_material`].
308 /// Then on payment receipt, we verify in this method that the payment preimage and payment secret
309 /// match what was constructed.
311 /// [`create_inbound_payment`] and [`create_inbound_payment_for_hash`] are called by the user to
312 /// construct the payment secret and/or payment hash that this method is verifying. If the former
313 /// method is called, then the payment method bits mentioned above are represented internally as
314 /// [`Method::LdkPaymentHash`]. If the latter, [`Method::UserPaymentHash`].
316 /// For the former method, the payment preimage is constructed as an HMAC of payment metadata and
317 /// random bytes. Because the payment secret is also encoded with these random bytes and metadata
318 /// (with the metadata encrypted with a block cipher), we're able to authenticate the preimage on
321 /// For the latter, the payment secret instead contains an HMAC of the user-provided payment hash
322 /// and payment metadata (encrypted with a block cipher), allowing us to authenticate the payment
323 /// hash and metadata on payment receipt.
325 /// See [`ExpandedKey`] docs for more info on the individual keys used.
327 /// [`NodeSigner::get_inbound_payment_key_material`]: crate::sign::NodeSigner::get_inbound_payment_key_material
328 /// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
329 /// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
330 pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData,
331 highest_seen_timestamp: u64, keys: &ExpandedKey, logger: &L) -> Result<
332 (Option<PaymentPreimage>, Option<u16>), ()>
333 where L::Target: Logger
335 let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys);
337 let payment_type_res = Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
338 let mut amt_msat_bytes = [0; AMT_MSAT_LEN];
339 let mut expiry_bytes = [0; METADATA_LEN - AMT_MSAT_LEN];
340 amt_msat_bytes.copy_from_slice(&metadata_bytes[..AMT_MSAT_LEN]);
341 expiry_bytes.copy_from_slice(&metadata_bytes[AMT_MSAT_LEN..]);
342 // Zero out the bits reserved to indicate the payment type.
343 amt_msat_bytes[0] &= 0b00011111;
344 let mut min_final_cltv_expiry_delta = None;
346 // Make sure to check the HMAC before doing the other checks below, to mitigate timing attacks.
347 let mut payment_preimage = None;
349 match payment_type_res {
350 Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => {
351 let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
352 hmac.input(&metadata_bytes[..]);
353 hmac.input(&payment_hash.0);
354 if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0) {
355 log_trace!(logger, "Failing HTLC with user-generated payment_hash {}: unexpected payment_secret", &payment_hash);
359 Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
360 match derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys) {
361 Ok(preimage) => payment_preimage = Some(preimage),
362 Err(bad_preimage_bytes) => {
363 log_trace!(logger, "Failing HTLC with payment_hash {} due to mismatching preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes));
368 Err(unknown_bits) => {
369 log_trace!(logger, "Failing HTLC with payment hash {} due to unknown payment type {}", &payment_hash, unknown_bits);
374 match payment_type_res {
375 Ok(Method::UserPaymentHashCustomFinalCltv) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
376 min_final_cltv_expiry_delta = Some(min_final_cltv_expiry_delta_from_metadata(metadata_bytes));
377 // Zero out first two bytes of expiry reserved for `min_final_cltv_expiry_delta`.
378 expiry_bytes[0] &= 0;
379 expiry_bytes[1] &= 0;
384 let min_amt_msat: u64 = u64::from_be_bytes(amt_msat_bytes.into());
385 let expiry = u64::from_be_bytes(expiry_bytes.try_into().unwrap());
387 if payment_data.total_msat < min_amt_msat {
388 log_trace!(logger, "Failing HTLC with payment_hash {} due to total_msat {} being less than the minimum amount of {} msat", &payment_hash, payment_data.total_msat, min_amt_msat);
392 if expiry < highest_seen_timestamp {
393 log_trace!(logger, "Failing HTLC with payment_hash {}: expired payment", &payment_hash);
397 Ok((payment_preimage, min_final_cltv_expiry_delta))
400 pub(super) fn get_payment_preimage(payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey) -> Result<PaymentPreimage, APIError> {
401 let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_secret, keys);
403 match Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET) {
404 Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
405 derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys)
406 .map_err(|bad_preimage_bytes| APIError::APIMisuseError {
407 err: format!("Payment hash {} did not match decoded preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes))
410 Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => Err(APIError::APIMisuseError {
411 err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash".to_string()
413 Err(other) => Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) }),
417 fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
418 let mut iv_bytes = [0; IV_LEN];
419 let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
420 iv_bytes.copy_from_slice(iv_slice);
422 let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
423 ChaCha20::encrypt_single_block(
424 &keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
427 (iv_bytes, metadata_bytes)
430 // Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
432 fn derive_ldk_payment_preimage(payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], keys: &ExpandedKey) -> Result<PaymentPreimage, [u8; 32]> {
433 let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
434 hmac.input(iv_bytes);
435 hmac.input(metadata_bytes);
436 let decoded_payment_preimage = Hmac::from_engine(hmac).to_byte_array();
437 if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).to_byte_array()) {
438 return Err(decoded_payment_preimage);
440 return Ok(PaymentPreimage(decoded_payment_preimage))