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