1use 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;
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 => {
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
132pub 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
179pub 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 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 if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) {
270 return Err(());
271 }
272
273 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
312pub(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 amt_msat_bytes[0] &= 0b00011111;
365 let mut min_final_cltv_expiry_delta = None;
366
367 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 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
500fn 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}