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