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