+ fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
+ let mut iv_bytes = [0; IV_LEN];
+ let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
+ iv_bytes.copy_from_slice(iv_slice);
+
+ let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
+ let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
+ for i in 0..METADATA_LEN {
+ metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
+ }
+
+ (iv_bytes, metadata_bytes)
+ }
+
+ // Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
+ // this case.
+ fn derive_ldk_payment_preimage(payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], keys: &ExpandedKey) -> Result<PaymentPreimage, [u8; 32]> {
+ let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
+ hmac.input(iv_bytes);
+ hmac.input(metadata_bytes);
+ let decoded_payment_preimage = Hmac::from_engine(hmac).into_inner();
+ if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).into_inner()) {
+ return Err(decoded_payment_preimage);
+ }
+ return Ok(PaymentPreimage(decoded_payment_preimage))
+ }
+