1use 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;
36const METHOD_TYPE_OFFSET: usize = 5;
39
40#[derive(Hash, Copy, Clone, PartialEq, Eq, Debug)]
44pub struct ExpandedKey {
45 metadata_key: [u8; 32],
48 ldk_pmt_hash_key: [u8; 32],
51 user_pmt_hash_key: [u8; 32],
54 offers_base_key: [u8; 32],
56 offers_encryption_key: [u8; 32],
58 spontaneous_pmt_key: [u8; 32],
61}
62
63impl ExpandedKey {
64 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 pub(crate) fn hmac_for_offer(&self) -> HmacEngine<Sha256> {
90 HmacEngine::<Sha256>::new(&self.offers_base_key)
91 }
92
93 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
101enum 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
128pub 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
167pub 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 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 if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) { return Err(()); }
239
240 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
271pub(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 amt_msat_bytes[0] &= 0b00011111;
321 let mut min_final_cltv_expiry_delta = None;
322
323 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 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
418fn 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}