lightning/ln/
inbound_payment.rs

1// This file is Copyright its original authors, visible in version control
2// history.
3//
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
8// licenses.
9
10//! Utilities to generate inbound payment information in service of invoice creation.
11
12use bitcoin::hashes::{Hash, HashEngine};
13use bitcoin::hashes::cmp::fixed_time_eq;
14use bitcoin::hashes::hmac::{Hmac, HmacEngine};
15use bitcoin::hashes::sha256::Hash as Sha256;
16
17use crate::crypto::chacha20::ChaCha20;
18use crate::crypto::utils::hkdf_extract_expand_6x;
19use crate::ln::msgs;
20use crate::ln::msgs::MAX_VALUE_MSAT;
21use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
22use crate::offers::nonce::Nonce;
23use crate::sign::EntropySource;
24use crate::util::errors::APIError;
25use crate::util::logger::Logger;
26
27#[allow(unused_imports)]
28use crate::prelude::*;
29
30use core::ops::Deref;
31
32pub(crate) const IV_LEN: usize = 16;
33const METADATA_LEN: usize = 16;
34const METADATA_KEY_LEN: usize = 32;
35const AMT_MSAT_LEN: usize = 8;
36// Used to shift the payment type bits to take up the top 3 bits of the metadata bytes, or to
37// retrieve said payment type bits.
38const METHOD_TYPE_OFFSET: usize = 5;
39
40/// A set of keys that were HKDF-expanded. Returned by [`NodeSigner::get_inbound_payment_key`].
41///
42/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
43#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
44pub struct ExpandedKey {
45	/// The key used to encrypt the bytes containing the payment metadata (i.e. the amount and
46	/// expiry, included for payment verification on decryption).
47	metadata_key: [u8; 32],
48	/// The key used to authenticate an LDK-provided payment hash and metadata as previously
49	/// registered with LDK.
50	ldk_pmt_hash_key: [u8; 32],
51	/// The key used to authenticate a user-provided payment hash and metadata as previously
52	/// registered with LDK.
53	user_pmt_hash_key: [u8; 32],
54	/// The base key used to derive signing keys and authenticate messages for BOLT 12 Offers.
55	offers_base_key: [u8; 32],
56	/// The key used to encrypt message metadata for BOLT 12 Offers.
57	offers_encryption_key: [u8; 32],
58	/// The key used to authenticate spontaneous payments' metadata as previously registered with LDK
59	/// for inclusion in a blinded path.
60	spontaneous_pmt_key: [u8; 32],
61}
62
63impl ExpandedKey {
64	/// Create a  new [`ExpandedKey`] for generating an inbound payment hash and secret.
65	///
66	/// It is recommended to cache this value and not regenerate it for each new inbound payment.
67	pub fn new(key_material: [u8; 32]) -> ExpandedKey {
68		let (
69			metadata_key,
70			ldk_pmt_hash_key,
71			user_pmt_hash_key,
72			offers_base_key,
73			offers_encryption_key,
74			spontaneous_pmt_key,
75		) = hkdf_extract_expand_6x(b"LDK Inbound Payment Key Expansion", &key_material);
76		Self {
77			metadata_key,
78			ldk_pmt_hash_key,
79			user_pmt_hash_key,
80			offers_base_key,
81			offers_encryption_key,
82			spontaneous_pmt_key,
83		}
84	}
85
86	/// Returns an [`HmacEngine`] used to construct [`Offer::metadata`].
87	///
88	/// [`Offer::metadata`]: crate::offers::offer::Offer::metadata
89	pub(crate) fn hmac_for_offer(&self) -> HmacEngine<Sha256> {
90		HmacEngine::<Sha256>::new(&self.offers_base_key)
91	}
92
93	/// Encrypts or decrypts the given `bytes`. Used for data included in an offer message's
94	/// metadata (e.g., payment id).
95	pub(crate) fn crypt_for_offer(&self, mut bytes: [u8; 32], nonce: Nonce) -> [u8; 32] {
96		ChaCha20::encrypt_single_block_in_place(&self.offers_encryption_key, &nonce.0, &mut bytes);
97		bytes
98	}
99}
100
101/// We currently set aside 3 bits for the `Method` in the `PaymentSecret`.
102enum Method {
103	LdkPaymentHash = 0,
104	UserPaymentHash = 1,
105	LdkPaymentHashCustomFinalCltv = 2,
106	UserPaymentHashCustomFinalCltv = 3,
107	SpontaneousPayment = 4,
108}
109
110impl Method {
111	fn from_bits(bits: u8) -> Result<Method, u8> {
112		match bits {
113			bits if bits == Method::LdkPaymentHash as u8 => Ok(Method::LdkPaymentHash),
114			bits if bits == Method::UserPaymentHash as u8 => Ok(Method::UserPaymentHash),
115			bits if bits == Method::LdkPaymentHashCustomFinalCltv as u8 => Ok(Method::LdkPaymentHashCustomFinalCltv),
116			bits if bits == Method::UserPaymentHashCustomFinalCltv as u8 => Ok(Method::UserPaymentHashCustomFinalCltv),
117			bits if bits == Method::SpontaneousPayment as u8 => Ok(Method::SpontaneousPayment),
118			unknown => Err(unknown),
119		}
120	}
121}
122
123fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 {
124	let expiry_bytes = &bytes[AMT_MSAT_LEN..];
125	u16::from_be_bytes([expiry_bytes[0], expiry_bytes[1]])
126}
127
128/// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment`], but no
129/// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without
130/// a `ChannelManager`.
131///
132/// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key`]. It is recommended to
133/// cache this value and not regenerate it for each new inbound payment.
134///
135/// `current_time` is a Unix timestamp representing the current time.
136///
137/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
138/// on versions of LDK prior to 0.0.114.
139///
140/// [phantom node payments]: crate::sign::PhantomKeysManager
141/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
142pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>,
143	invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64,
144	min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()>
145	where ES::Target: EntropySource
146{
147	let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
148			Method::LdkPaymentHashCustomFinalCltv
149		} else {
150			Method::LdkPaymentHash
151		}, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
152
153	let mut iv_bytes = [0 as u8; IV_LEN];
154	let rand_bytes = entropy_source.get_secure_random_bytes();
155	iv_bytes.copy_from_slice(&rand_bytes[..IV_LEN]);
156
157	let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
158	hmac.input(&iv_bytes);
159	hmac.input(&metadata_bytes);
160	let payment_preimage_bytes = Hmac::from_engine(hmac).to_byte_array();
161
162	let ldk_pmt_hash = PaymentHash(Sha256::hash(&payment_preimage_bytes).to_byte_array());
163	let payment_secret = construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key);
164	Ok((ldk_pmt_hash, payment_secret))
165}
166
167/// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`],
168/// but no `ChannelManager` is required. Useful for generating invoices for [phantom node payments]
169/// without a `ChannelManager`.
170///
171/// See [`create`] for information on the `keys` and `current_time` parameters.
172///
173/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
174/// on versions of LDK prior to 0.0.114.
175///
176/// [phantom node payments]: crate::sign::PhantomKeysManager
177pub fn create_from_hash(keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash,
178	invoice_expiry_delta_secs: u32, current_time: u64, min_final_cltv_expiry_delta: Option<u16>) -> Result<PaymentSecret, ()> {
179	let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
180			Method::UserPaymentHashCustomFinalCltv
181		} else {
182			Method::UserPaymentHash
183		}, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
184
185	let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
186	hmac.input(&metadata_bytes);
187	hmac.input(&payment_hash.0);
188	let hmac_bytes = Hmac::from_engine(hmac).to_byte_array();
189
190	let mut iv_bytes = [0 as u8; IV_LEN];
191	iv_bytes.copy_from_slice(&hmac_bytes[..IV_LEN]);
192
193	Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
194}
195
196#[cfg(async_payments)]
197pub(super) fn create_for_spontaneous_payment(
198	keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
199	current_time: u64, min_final_cltv_expiry_delta: Option<u16>
200) -> Result<PaymentSecret, ()> {
201	let metadata_bytes = construct_metadata_bytes(
202		min_value_msat, Method::SpontaneousPayment, invoice_expiry_delta_secs, current_time,
203		min_final_cltv_expiry_delta
204	)?;
205
206	let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
207	hmac.input(&metadata_bytes);
208	let hmac_bytes = Hmac::from_engine(hmac).to_byte_array();
209
210	let mut iv_bytes = [0 as u8; IV_LEN];
211	iv_bytes.copy_from_slice(&hmac_bytes[..IV_LEN]);
212
213	Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
214}
215
216fn construct_metadata_bytes(min_value_msat: Option<u64>, payment_type: Method,
217	invoice_expiry_delta_secs: u32, highest_seen_timestamp: u64, min_final_cltv_expiry_delta: Option<u16>) -> Result<[u8; METADATA_LEN], ()> {
218	if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
219		return Err(());
220	}
221
222	let mut min_amt_msat_bytes: [u8; AMT_MSAT_LEN] = match min_value_msat {
223		Some(amt) => amt.to_be_bytes(),
224		None => [0; AMT_MSAT_LEN],
225	};
226	min_amt_msat_bytes[0] |= (payment_type as u8) << METHOD_TYPE_OFFSET;
227
228	// We assume that highest_seen_timestamp is pretty close to the current time - it's updated when
229	// we receive a new block with the maximum time we've seen in a header. It should never be more
230	// than two hours in the future.  Thus, we add two hours here as a buffer to ensure we
231	// absolutely never fail a payment too early.
232	// Note that we assume that received blocks have reasonably up-to-date timestamps.
233	let expiry_timestamp = highest_seen_timestamp + invoice_expiry_delta_secs as u64 + 7200;
234	let mut expiry_bytes = expiry_timestamp.to_be_bytes();
235
236	// `min_value_msat` should fit in (64 bits - 3 payment type bits =) 61 bits as an unsigned integer.
237	// This should leave us with a maximum value greater than the 21M BTC supply cap anyway.
238	if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) { return Err(()); }
239
240	// `expiry_timestamp` should fit in (64 bits - 2 delta bytes =) 48 bits as an unsigned integer.
241	// Bitcoin's block header timestamps are actually `u32`s, so we're technically already limited to
242	// the much smaller maximum timestamp of `u32::MAX` for now, but we check the u64 `expiry_timestamp`
243	// for future-proofing.
244	if min_final_cltv_expiry_delta.is_some() && expiry_timestamp > ((1u64 << 48) - 1) { return Err(()); }
245
246	if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
247		let bytes = min_final_cltv_expiry_delta.to_be_bytes();
248		expiry_bytes[0] |= bytes[0];
249		expiry_bytes[1] |= bytes[1];
250	}
251
252	let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
253
254	metadata_bytes[..AMT_MSAT_LEN].copy_from_slice(&min_amt_msat_bytes);
255	metadata_bytes[AMT_MSAT_LEN..].copy_from_slice(&expiry_bytes);
256
257	Ok(metadata_bytes)
258}
259
260fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], metadata_key: &[u8; METADATA_KEY_LEN]) -> PaymentSecret {
261	let mut payment_secret_bytes: [u8; 32] = [0; 32];
262	let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
263	iv_slice.copy_from_slice(iv_bytes);
264
265	ChaCha20::encrypt_single_block(
266		metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
267	);
268	PaymentSecret(payment_secret_bytes)
269}
270
271/// Check that an inbound payment's `payment_data` field is sane.
272///
273/// LDK does not store any data for pending inbound payments. Instead, we construct our payment
274/// secret (and, if supplied by LDK, our payment preimage) to include encrypted metadata about the
275/// payment.
276///
277/// For payments without a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
278///   payment method (3 bits) || payment amount (8 bytes - 3 bits) || expiry (8 bytes)
279///
280/// For payments including a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
281///   payment method (3 bits) || payment amount (8 bytes - 3 bits) || min_final_cltv_expiry_delta (2 bytes) || expiry (6 bytes)
282///
283/// In both cases the result is then encrypted using a key derived from [`NodeSigner::get_inbound_payment_key`].
284///
285/// Then on payment receipt, we verify in this method that the payment preimage and payment secret
286/// match what was constructed.
287///
288/// [`create_inbound_payment`] and [`create_inbound_payment_for_hash`] are called by the user to
289/// construct the payment secret and/or payment hash that this method is verifying. If the former
290/// method is called, then the payment method bits mentioned above are represented internally as
291/// [`Method::LdkPaymentHash`]. If the latter, [`Method::UserPaymentHash`].
292///
293/// For the former method, the payment preimage is constructed as an HMAC of payment metadata and
294/// random bytes. Because the payment secret is also encoded with these random bytes and metadata
295/// (with the metadata encrypted with a block cipher), we're able to authenticate the preimage on
296/// payment receipt.
297///
298/// For the latter, the payment secret instead contains an HMAC of the user-provided payment hash
299/// and payment metadata (encrypted with a block cipher), allowing us to authenticate the payment
300/// hash and metadata on payment receipt.
301///
302/// See [`ExpandedKey`] docs for more info on the individual keys used.
303///
304/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
305/// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
306/// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
307pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData,
308	highest_seen_timestamp: u64, keys: &ExpandedKey, logger: &L) -> Result<
309	(Option<PaymentPreimage>, Option<u16>), ()>
310	where L::Target: Logger
311{
312	let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys);
313
314	let payment_type_res = Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
315	let mut amt_msat_bytes = [0; AMT_MSAT_LEN];
316	let mut expiry_bytes = [0; METADATA_LEN - AMT_MSAT_LEN];
317	amt_msat_bytes.copy_from_slice(&metadata_bytes[..AMT_MSAT_LEN]);
318	expiry_bytes.copy_from_slice(&metadata_bytes[AMT_MSAT_LEN..]);
319	// Zero out the bits reserved to indicate the payment type.
320	amt_msat_bytes[0] &= 0b00011111;
321	let mut min_final_cltv_expiry_delta = None;
322
323	// Make sure to check the HMAC before doing the other checks below, to mitigate timing attacks.
324	let mut payment_preimage = None;
325
326	match payment_type_res {
327		Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => {
328			let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
329			hmac.input(&metadata_bytes[..]);
330			hmac.input(&payment_hash.0);
331			if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0) {
332				log_trace!(logger, "Failing HTLC with user-generated payment_hash {}: unexpected payment_secret", &payment_hash);
333				return Err(())
334			}
335		},
336		Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
337			match derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys) {
338				Ok(preimage) => payment_preimage = Some(preimage),
339				Err(bad_preimage_bytes) => {
340					log_trace!(logger, "Failing HTLC with payment_hash {} due to mismatching preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes));
341					return Err(())
342				}
343			}
344		},
345		Ok(Method::SpontaneousPayment) => {
346			let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
347			hmac.input(&metadata_bytes[..]);
348			if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0) {
349				log_trace!(logger, "Failing async payment HTLC with sender-generated payment_hash {}: unexpected payment_secret", &payment_hash);
350				return Err(())
351			}
352		},
353		Err(unknown_bits) => {
354			log_trace!(logger, "Failing HTLC with payment hash {} due to unknown payment type {}", &payment_hash, unknown_bits);
355			return Err(());
356		}
357	}
358
359	match payment_type_res {
360		Ok(Method::UserPaymentHashCustomFinalCltv) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
361			min_final_cltv_expiry_delta = Some(min_final_cltv_expiry_delta_from_metadata(metadata_bytes));
362			// Zero out first two bytes of expiry reserved for `min_final_cltv_expiry_delta`.
363			expiry_bytes[0] &= 0;
364			expiry_bytes[1] &= 0;
365		}
366		_ => {}
367	}
368
369	let min_amt_msat: u64 = u64::from_be_bytes(amt_msat_bytes.into());
370	let expiry = u64::from_be_bytes(expiry_bytes.try_into().unwrap());
371
372	if payment_data.total_msat < min_amt_msat {
373		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);
374		return Err(())
375	}
376
377	if expiry < highest_seen_timestamp {
378		log_trace!(logger, "Failing HTLC with payment_hash {}: expired payment", &payment_hash);
379		return Err(())
380	}
381
382	Ok((payment_preimage, min_final_cltv_expiry_delta))
383}
384
385pub(super) fn get_payment_preimage(payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey) -> Result<PaymentPreimage, APIError> {
386	let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_secret, keys);
387
388	match Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET) {
389		Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
390			derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys)
391				.map_err(|bad_preimage_bytes| APIError::APIMisuseError {
392					err: format!("Payment hash {} did not match decoded preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes))
393				})
394		},
395		Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => Err(APIError::APIMisuseError {
396			err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash".to_string()
397		}),
398		Ok(Method::SpontaneousPayment) => Err(APIError::APIMisuseError {
399			err: "Can't extract payment preimage for spontaneous payments".to_string()
400		}),
401		Err(other) => Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) }),
402	}
403}
404
405fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
406	let mut iv_bytes = [0; IV_LEN];
407	let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
408	iv_bytes.copy_from_slice(iv_slice);
409
410	let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
411	ChaCha20::encrypt_single_block(
412		&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
413	);
414
415	(iv_bytes, metadata_bytes)
416}
417
418// Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
419// this case.
420fn derive_ldk_payment_preimage(payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], keys: &ExpandedKey) -> Result<PaymentPreimage, [u8; 32]> {
421	let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
422	hmac.input(iv_bytes);
423	hmac.input(metadata_bytes);
424	let decoded_payment_preimage = Hmac::from_engine(hmac).to_byte_array();
425	if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).to_byte_array()) {
426		return Err(decoded_payment_preimage);
427	}
428	return Ok(PaymentPreimage(decoded_payment_preimage))
429}