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::cmp::fixed_time_eq;
13use bitcoin::hashes::hmac::{Hmac, HmacEngine};
14use bitcoin::hashes::sha256::Hash as Sha256;
15use bitcoin::hashes::{Hash, HashEngine};
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::offers::nonce::Nonce;
22use crate::sign::EntropySource;
23use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
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_expanded_key`].
41///
42/// [`NodeSigner::get_expanded_key`]: crate::sign::NodeSigner::get_expanded_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 => {
116				Ok(Method::LdkPaymentHashCustomFinalCltv)
117			},
118			bits if bits == Method::UserPaymentHashCustomFinalCltv as u8 => {
119				Ok(Method::UserPaymentHashCustomFinalCltv)
120			},
121			bits if bits == Method::SpontaneousPayment as u8 => Ok(Method::SpontaneousPayment),
122			unknown => Err(unknown),
123		}
124	}
125}
126
127fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 {
128	let expiry_bytes = &bytes[AMT_MSAT_LEN..];
129	u16::from_be_bytes([expiry_bytes[0], expiry_bytes[1]])
130}
131
132/// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment`], but no
133/// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without
134/// a `ChannelManager`.
135///
136/// `keys` is generated by calling [`NodeSigner::get_expanded_key`]. It is recommended to
137/// cache this value and not regenerate it for each new inbound payment.
138///
139/// `current_time` is a Unix timestamp representing the current time.
140///
141/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
142/// on versions of LDK prior to 0.0.114.
143///
144/// [phantom node payments]: crate::sign::PhantomKeysManager
145/// [`NodeSigner::get_expanded_key`]: crate::sign::NodeSigner::get_expanded_key
146pub fn create<ES: Deref>(
147	keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
148	entropy_source: &ES, current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
149) -> Result<(PaymentHash, PaymentSecret), ()>
150where
151	ES::Target: EntropySource,
152{
153	let metadata_bytes = construct_metadata_bytes(
154		min_value_msat,
155		if min_final_cltv_expiry_delta.is_some() {
156			Method::LdkPaymentHashCustomFinalCltv
157		} else {
158			Method::LdkPaymentHash
159		},
160		invoice_expiry_delta_secs,
161		current_time,
162		min_final_cltv_expiry_delta,
163	)?;
164
165	let mut iv_bytes = [0 as u8; IV_LEN];
166	let rand_bytes = entropy_source.get_secure_random_bytes();
167	iv_bytes.copy_from_slice(&rand_bytes[..IV_LEN]);
168
169	let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
170	hmac.input(&iv_bytes);
171	hmac.input(&metadata_bytes);
172	let payment_preimage_bytes = Hmac::from_engine(hmac).to_byte_array();
173
174	let ldk_pmt_hash = PaymentHash(Sha256::hash(&payment_preimage_bytes).to_byte_array());
175	let payment_secret = construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key);
176	Ok((ldk_pmt_hash, payment_secret))
177}
178
179/// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`],
180/// but no `ChannelManager` is required. Useful for generating invoices for [phantom node payments]
181/// without a `ChannelManager`.
182///
183/// See [`create`] for information on the `keys` and `current_time` parameters.
184///
185/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
186/// on versions of LDK prior to 0.0.114.
187///
188/// [phantom node payments]: crate::sign::PhantomKeysManager
189pub fn create_from_hash(
190	keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash,
191	invoice_expiry_delta_secs: u32, current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
192) -> Result<PaymentSecret, ()> {
193	let metadata_bytes = construct_metadata_bytes(
194		min_value_msat,
195		if min_final_cltv_expiry_delta.is_some() {
196			Method::UserPaymentHashCustomFinalCltv
197		} else {
198			Method::UserPaymentHash
199		},
200		invoice_expiry_delta_secs,
201		current_time,
202		min_final_cltv_expiry_delta,
203	)?;
204
205	let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
206	hmac.input(&metadata_bytes);
207	hmac.input(&payment_hash.0);
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
216pub(crate) fn create_for_spontaneous_payment(
217	keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
218	current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
219) -> Result<PaymentSecret, ()> {
220	let metadata_bytes = construct_metadata_bytes(
221		min_value_msat,
222		Method::SpontaneousPayment,
223		invoice_expiry_delta_secs,
224		current_time,
225		min_final_cltv_expiry_delta,
226	)?;
227
228	let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
229	hmac.input(&metadata_bytes);
230	let hmac_bytes = Hmac::from_engine(hmac).to_byte_array();
231
232	let mut iv_bytes = [0 as u8; IV_LEN];
233	iv_bytes.copy_from_slice(&hmac_bytes[..IV_LEN]);
234
235	Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
236}
237
238pub(crate) fn calculate_absolute_expiry(
239	highest_seen_timestamp: u64, invoice_expiry_delta_secs: u32,
240) -> u64 {
241	// We assume that highest_seen_timestamp is pretty close to the current time - it's updated when
242	// we receive a new block with the maximum time we've seen in a header. It should never be more
243	// than two hours in the future.  Thus, we add two hours here as a buffer to ensure we
244	// absolutely never fail a payment too early.
245	// Note that we assume that received blocks have reasonably up-to-date timestamps.
246	highest_seen_timestamp + invoice_expiry_delta_secs as u64 + 7200
247}
248
249fn construct_metadata_bytes(
250	min_value_msat: Option<u64>, payment_type: Method, invoice_expiry_delta_secs: u32,
251	highest_seen_timestamp: u64, min_final_cltv_expiry_delta: Option<u16>,
252) -> Result<[u8; METADATA_LEN], ()> {
253	if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
254		return Err(());
255	}
256
257	let mut min_amt_msat_bytes: [u8; AMT_MSAT_LEN] = match min_value_msat {
258		Some(amt) => amt.to_be_bytes(),
259		None => [0; AMT_MSAT_LEN],
260	};
261	min_amt_msat_bytes[0] |= (payment_type as u8) << METHOD_TYPE_OFFSET;
262
263	let expiry_timestamp =
264		calculate_absolute_expiry(highest_seen_timestamp, invoice_expiry_delta_secs);
265	let mut expiry_bytes = expiry_timestamp.to_be_bytes();
266
267	// `min_value_msat` should fit in (64 bits - 3 payment type bits =) 61 bits as an unsigned integer.
268	// This should leave us with a maximum value greater than the 21M BTC supply cap anyway.
269	if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) {
270		return Err(());
271	}
272
273	// `expiry_timestamp` should fit in (64 bits - 2 delta bytes =) 48 bits as an unsigned integer.
274	// Bitcoin's block header timestamps are actually `u32`s, so we're technically already limited to
275	// the much smaller maximum timestamp of `u32::MAX` for now, but we check the u64 `expiry_timestamp`
276	// for future-proofing.
277	if min_final_cltv_expiry_delta.is_some() && expiry_timestamp > ((1u64 << 48) - 1) {
278		return Err(());
279	}
280
281	if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
282		let bytes = min_final_cltv_expiry_delta.to_be_bytes();
283		expiry_bytes[0] |= bytes[0];
284		expiry_bytes[1] |= bytes[1];
285	}
286
287	let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
288
289	metadata_bytes[..AMT_MSAT_LEN].copy_from_slice(&min_amt_msat_bytes);
290	metadata_bytes[AMT_MSAT_LEN..].copy_from_slice(&expiry_bytes);
291
292	Ok(metadata_bytes)
293}
294
295fn construct_payment_secret(
296	iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN],
297	metadata_key: &[u8; METADATA_KEY_LEN],
298) -> PaymentSecret {
299	let mut payment_secret_bytes: [u8; 32] = [0; 32];
300	let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
301	iv_slice.copy_from_slice(iv_bytes);
302
303	ChaCha20::encrypt_single_block(
304		metadata_key,
305		iv_bytes,
306		encrypted_metadata_slice,
307		metadata_bytes,
308	);
309	PaymentSecret(payment_secret_bytes)
310}
311
312/// Check that an inbound payment's `payment_data` field is sane.
313///
314/// LDK does not store any data for pending inbound payments. Instead, we construct our payment
315/// secret (and, if supplied by LDK, our payment preimage) to include encrypted metadata about the
316/// payment.
317///
318/// For payments without a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
319///   payment method (3 bits) || payment amount (8 bytes - 3 bits) || expiry (8 bytes)
320///
321/// For payments including a custom `min_final_cltv_expiry_delta`, the metadata is constructed as:
322///   payment method (3 bits) || payment amount (8 bytes - 3 bits) || min_final_cltv_expiry_delta (2 bytes) || expiry (6 bytes)
323///
324/// In both cases the result is then encrypted using a key derived from [`NodeSigner::get_expanded_key`].
325///
326/// Then on payment receipt, we verify in this method that the payment preimage and payment secret
327/// match what was constructed.
328///
329/// [`create_inbound_payment`] and [`create_inbound_payment_for_hash`] are called by the user to
330/// construct the payment secret and/or payment hash that this method is verifying. If the former
331/// method is called, then the payment method bits mentioned above are represented internally as
332/// [`Method::LdkPaymentHash`]. If the latter, [`Method::UserPaymentHash`].
333///
334/// For the former method, the payment preimage is constructed as an HMAC of payment metadata and
335/// random bytes. Because the payment secret is also encoded with these random bytes and metadata
336/// (with the metadata encrypted with a block cipher), we're able to authenticate the preimage on
337/// payment receipt.
338///
339/// For the latter, the payment secret instead contains an HMAC of the user-provided payment hash
340/// and payment metadata (encrypted with a block cipher), allowing us to authenticate the payment
341/// hash and metadata on payment receipt.
342///
343/// See [`ExpandedKey`] docs for more info on the individual keys used.
344///
345/// [`NodeSigner::get_expanded_key`]: crate::sign::NodeSigner::get_expanded_key
346/// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
347/// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
348pub(super) fn verify<L: Deref>(
349	payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData, highest_seen_timestamp: u64,
350	keys: &ExpandedKey, logger: &L,
351) -> Result<(Option<PaymentPreimage>, Option<u16>), ()>
352where
353	L::Target: Logger,
354{
355	let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys);
356
357	let payment_type_res =
358		Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
359	let mut amt_msat_bytes = [0; AMT_MSAT_LEN];
360	let mut expiry_bytes = [0; METADATA_LEN - AMT_MSAT_LEN];
361	amt_msat_bytes.copy_from_slice(&metadata_bytes[..AMT_MSAT_LEN]);
362	expiry_bytes.copy_from_slice(&metadata_bytes[AMT_MSAT_LEN..]);
363	// Zero out the bits reserved to indicate the payment type.
364	amt_msat_bytes[0] &= 0b00011111;
365	let mut min_final_cltv_expiry_delta = None;
366
367	// Make sure to check the HMAC before doing the other checks below, to mitigate timing attacks.
368	let mut payment_preimage = None;
369
370	match payment_type_res {
371		Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => {
372			let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
373			hmac.input(&metadata_bytes[..]);
374			hmac.input(&payment_hash.0);
375			if !fixed_time_eq(
376				&iv_bytes,
377				&Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0,
378			) {
379				log_trace!(
380					logger,
381					"Failing HTLC with user-generated payment_hash {}: unexpected payment_secret",
382					&payment_hash
383				);
384				return Err(());
385			}
386		},
387		Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
388			match derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys) {
389				Ok(preimage) => payment_preimage = Some(preimage),
390				Err(bad_preimage_bytes) => {
391					log_trace!(
392						logger,
393						"Failing HTLC with payment_hash {} due to mismatching preimage {}",
394						&payment_hash,
395						log_bytes!(bad_preimage_bytes)
396					);
397					return Err(());
398				},
399			}
400		},
401		Ok(Method::SpontaneousPayment) => {
402			let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
403			hmac.input(&metadata_bytes[..]);
404			if !fixed_time_eq(
405				&iv_bytes,
406				&Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0,
407			) {
408				log_trace!(logger, "Failing async payment HTLC with sender-generated payment_hash {}: unexpected payment_secret", &payment_hash);
409				return Err(());
410			}
411		},
412		Err(unknown_bits) => {
413			log_trace!(
414				logger,
415				"Failing HTLC with payment hash {} due to unknown payment type {}",
416				&payment_hash,
417				unknown_bits
418			);
419			return Err(());
420		},
421	}
422
423	match payment_type_res {
424		Ok(Method::UserPaymentHashCustomFinalCltv) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
425			min_final_cltv_expiry_delta =
426				Some(min_final_cltv_expiry_delta_from_metadata(metadata_bytes));
427			// Zero out first two bytes of expiry reserved for `min_final_cltv_expiry_delta`.
428			expiry_bytes[0] &= 0;
429			expiry_bytes[1] &= 0;
430		},
431		_ => {},
432	}
433
434	let min_amt_msat: u64 = u64::from_be_bytes(amt_msat_bytes.into());
435	let expiry = u64::from_be_bytes(expiry_bytes.try_into().unwrap());
436
437	if payment_data.total_msat < min_amt_msat {
438		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);
439		return Err(());
440	}
441
442	if expiry < highest_seen_timestamp {
443		log_trace!(logger, "Failing HTLC with payment_hash {}: expired payment", &payment_hash);
444		return Err(());
445	}
446
447	Ok((payment_preimage, min_final_cltv_expiry_delta))
448}
449
450pub(super) fn get_payment_preimage(
451	payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey,
452) -> Result<PaymentPreimage, APIError> {
453	let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_secret, keys);
454
455	match Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET) {
456		Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
457			derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys).map_err(
458				|bad_preimage_bytes| APIError::APIMisuseError {
459					err: format!(
460						"Payment hash {} did not match decoded preimage {}",
461						&payment_hash,
462						log_bytes!(bad_preimage_bytes)
463					),
464				},
465			)
466		},
467		Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => {
468			Err(APIError::APIMisuseError {
469				err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash"
470					.to_string(),
471			})
472		},
473		Ok(Method::SpontaneousPayment) => Err(APIError::APIMisuseError {
474			err: "Can't extract payment preimage for spontaneous payments".to_string(),
475		}),
476		Err(other) => {
477			Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) })
478		},
479	}
480}
481
482fn decrypt_metadata(
483	payment_secret: PaymentSecret, keys: &ExpandedKey,
484) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
485	let mut iv_bytes = [0; IV_LEN];
486	let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
487	iv_bytes.copy_from_slice(iv_slice);
488
489	let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
490	ChaCha20::encrypt_single_block(
491		&keys.metadata_key,
492		&iv_bytes,
493		&mut metadata_bytes,
494		encrypted_metadata_bytes,
495	);
496
497	(iv_bytes, metadata_bytes)
498}
499
500// Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
501// this case.
502fn derive_ldk_payment_preimage(
503	payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN],
504	keys: &ExpandedKey,
505) -> Result<PaymentPreimage, [u8; 32]> {
506	let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
507	hmac.input(iv_bytes);
508	hmac.input(metadata_bytes);
509	let decoded_payment_preimage = Hmac::from_engine(hmac).to_byte_array();
510	if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).to_byte_array()) {
511		return Err(decoded_payment_preimage);
512	}
513	return Ok(PaymentPreimage(decoded_payment_preimage));
514}