Merge pull request #1930 from arik-so/2022-12-remove-keysinterface
[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 }
72
73 impl Method {
74         fn from_bits(bits: u8) -> Result<Method, u8> {
75                 match bits {
76                         bits if bits == Method::LdkPaymentHash as u8 => Ok(Method::LdkPaymentHash),
77                         bits if bits == Method::UserPaymentHash as u8 => Ok(Method::UserPaymentHash),
78                         unknown => Err(unknown),
79                 }
80         }
81 }
82
83 /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment`], but no
84 /// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without
85 /// a `ChannelManager`.
86 ///
87 /// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key_material`] and then
88 /// calling [`ExpandedKey::new`] with its result. It is recommended to cache this value and not
89 /// regenerate it for each new inbound payment.
90 ///
91 /// `current_time` is a Unix timestamp representing the current time.
92 ///
93 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
94 /// [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material
95 pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64) -> Result<(PaymentHash, PaymentSecret), ()>
96         where ES::Target: EntropySource
97 {
98         let metadata_bytes = construct_metadata_bytes(min_value_msat, Method::LdkPaymentHash, invoice_expiry_delta_secs, current_time)?;
99
100         let mut iv_bytes = [0 as u8; IV_LEN];
101         let rand_bytes = entropy_source.get_secure_random_bytes();
102         iv_bytes.copy_from_slice(&rand_bytes[..IV_LEN]);
103
104         let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
105         hmac.input(&iv_bytes);
106         hmac.input(&metadata_bytes);
107         let payment_preimage_bytes = Hmac::from_engine(hmac).into_inner();
108
109         let ldk_pmt_hash = PaymentHash(Sha256::hash(&payment_preimage_bytes).into_inner());
110         let payment_secret = construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key);
111         Ok((ldk_pmt_hash, payment_secret))
112 }
113
114 /// Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`],
115 /// but no `ChannelManager` is required. Useful for generating invoices for [phantom node payments]
116 /// without a `ChannelManager`.
117 ///
118 /// See [`create`] for information on the `keys` and `current_time` parameters.
119 ///
120 /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager
121 pub fn create_from_hash(keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash, invoice_expiry_delta_secs: u32, current_time: u64) -> Result<PaymentSecret, ()> {
122         let metadata_bytes = construct_metadata_bytes(min_value_msat, Method::UserPaymentHash, invoice_expiry_delta_secs, current_time)?;
123
124         let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
125         hmac.input(&metadata_bytes);
126         hmac.input(&payment_hash.0);
127         let hmac_bytes = Hmac::from_engine(hmac).into_inner();
128
129         let mut iv_bytes = [0 as u8; IV_LEN];
130         iv_bytes.copy_from_slice(&hmac_bytes[..IV_LEN]);
131
132         Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
133 }
134
135 fn construct_metadata_bytes(min_value_msat: Option<u64>, payment_type: Method, invoice_expiry_delta_secs: u32, highest_seen_timestamp: u64) -> Result<[u8; METADATA_LEN], ()> {
136         if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
137                 return Err(());
138         }
139
140         let mut min_amt_msat_bytes: [u8; AMT_MSAT_LEN] = match min_value_msat {
141                 Some(amt) => amt.to_be_bytes(),
142                 None => [0; AMT_MSAT_LEN],
143         };
144         min_amt_msat_bytes[0] |= (payment_type as u8) << METHOD_TYPE_OFFSET;
145
146         // We assume that highest_seen_timestamp is pretty close to the current time - it's updated when
147         // we receive a new block with the maximum time we've seen in a header. It should never be more
148         // than two hours in the future.  Thus, we add two hours here as a buffer to ensure we
149         // absolutely never fail a payment too early.
150         // Note that we assume that received blocks have reasonably up-to-date timestamps.
151         let expiry_bytes = (highest_seen_timestamp + invoice_expiry_delta_secs as u64 + 7200).to_be_bytes();
152
153         let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
154         metadata_bytes[..AMT_MSAT_LEN].copy_from_slice(&min_amt_msat_bytes);
155         metadata_bytes[AMT_MSAT_LEN..].copy_from_slice(&expiry_bytes);
156
157         Ok(metadata_bytes)
158 }
159
160 fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], metadata_key: &[u8; METADATA_KEY_LEN]) -> PaymentSecret {
161         let mut payment_secret_bytes: [u8; 32] = [0; 32];
162         let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
163         iv_slice.copy_from_slice(iv_bytes);
164
165         let chacha_block = ChaCha20::get_single_block(metadata_key, iv_bytes);
166         for i in 0..METADATA_LEN {
167                 encrypted_metadata_slice[i] = chacha_block[i] ^ metadata_bytes[i];
168         }
169         PaymentSecret(payment_secret_bytes)
170 }
171
172 /// Check that an inbound payment's `payment_data` field is sane.
173 ///
174 /// LDK does not store any data for pending inbound payments. Instead, we construct our payment
175 /// secret (and, if supplied by LDK, our payment preimage) to include encrypted metadata about the
176 /// payment.
177 ///
178 /// The metadata is constructed as:
179 ///   payment method (3 bits) || payment amount (8 bytes - 3 bits) || expiry (8 bytes)
180 /// and encrypted using a key derived from [`NodeSigner::get_inbound_payment_key_material`].
181 ///
182 /// Then on payment receipt, we verify in this method that the payment preimage and payment secret
183 /// match what was constructed.
184 ///
185 /// [`create_inbound_payment`] and [`create_inbound_payment_for_hash`] are called by the user to
186 /// construct the payment secret and/or payment hash that this method is verifying. If the former
187 /// method is called, then the payment method bits mentioned above are represented internally as
188 /// [`Method::LdkPaymentHash`]. If the latter, [`Method::UserPaymentHash`].
189 ///
190 /// For the former method, the payment preimage is constructed as an HMAC of payment metadata and
191 /// random bytes. Because the payment secret is also encoded with these random bytes and metadata
192 /// (with the metadata encrypted with a block cipher), we're able to authenticate the preimage on
193 /// payment receipt.
194 ///
195 /// For the latter, the payment secret instead contains an HMAC of the user-provided payment hash
196 /// and payment metadata (encrypted with a block cipher), allowing us to authenticate the payment
197 /// hash and metadata on payment receipt.
198 ///
199 /// See [`ExpandedKey`] docs for more info on the individual keys used.
200 ///
201 /// [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material
202 /// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
203 /// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
204 pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData, highest_seen_timestamp: u64, keys: &ExpandedKey, logger: &L) -> Result<Option<PaymentPreimage>, ()>
205         where L::Target: Logger
206 {
207         let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys);
208
209         let payment_type_res = Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
210         let mut amt_msat_bytes = [0; AMT_MSAT_LEN];
211         amt_msat_bytes.copy_from_slice(&metadata_bytes[..AMT_MSAT_LEN]);
212         // Zero out the bits reserved to indicate the payment type.
213         amt_msat_bytes[0] &= 0b00011111;
214         let min_amt_msat: u64 = u64::from_be_bytes(amt_msat_bytes.into());
215         let expiry = u64::from_be_bytes(metadata_bytes[AMT_MSAT_LEN..].try_into().unwrap());
216
217         // Make sure to check to check the HMAC before doing the other checks below, to mitigate timing
218         // attacks.
219         let mut payment_preimage = None;
220         match payment_type_res {
221                 Ok(Method::UserPaymentHash) => {
222                         let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
223                         hmac.input(&metadata_bytes[..]);
224                         hmac.input(&payment_hash.0);
225                         if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).into_inner().split_at_mut(IV_LEN).0) {
226                                 log_trace!(logger, "Failing HTLC with user-generated payment_hash {}: unexpected payment_secret", log_bytes!(payment_hash.0));
227                                 return Err(())
228                         }
229                 },
230                 Ok(Method::LdkPaymentHash) => {
231                         match derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys) {
232                                 Ok(preimage) => payment_preimage = Some(preimage),
233                                 Err(bad_preimage_bytes) => {
234                                         log_trace!(logger, "Failing HTLC with payment_hash {} due to mismatching preimage {}", log_bytes!(payment_hash.0), log_bytes!(bad_preimage_bytes));
235                                         return Err(())
236                                 }
237                         }
238                 },
239                 Err(unknown_bits) => {
240                         log_trace!(logger, "Failing HTLC with payment hash {} due to unknown payment type {}", log_bytes!(payment_hash.0), unknown_bits);
241                         return Err(());
242                 }
243         }
244
245         if payment_data.total_msat < min_amt_msat {
246                 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);
247                 return Err(())
248         }
249
250         if expiry < highest_seen_timestamp {
251                 log_trace!(logger, "Failing HTLC with payment_hash {}: expired payment", log_bytes!(payment_hash.0));
252                 return Err(())
253         }
254
255         Ok(payment_preimage)
256 }
257
258 pub(super) fn get_payment_preimage(payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey) -> Result<PaymentPreimage, APIError> {
259         let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_secret, keys);
260
261         match Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET) {
262                 Ok(Method::LdkPaymentHash) => {
263                         derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys)
264                                 .map_err(|bad_preimage_bytes| APIError::APIMisuseError {
265                                         err: format!("Payment hash {} did not match decoded preimage {}", log_bytes!(payment_hash.0), log_bytes!(bad_preimage_bytes))
266                                 })
267                 },
268                 Ok(Method::UserPaymentHash) => Err(APIError::APIMisuseError {
269                         err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash".to_string()
270                 }),
271                 Err(other) => Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) }),
272         }
273 }
274
275 fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
276         let mut iv_bytes = [0; IV_LEN];
277         let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
278         iv_bytes.copy_from_slice(iv_slice);
279
280         let chacha_block = ChaCha20::get_single_block(&keys.metadata_key, &iv_bytes);
281         let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
282         for i in 0..METADATA_LEN {
283                 metadata_bytes[i] = chacha_block[i] ^ encrypted_metadata_bytes[i];
284         }
285
286         (iv_bytes, metadata_bytes)
287 }
288
289 // Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
290 // this case.
291 fn derive_ldk_payment_preimage(payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], keys: &ExpandedKey) -> Result<PaymentPreimage, [u8; 32]> {
292         let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
293         hmac.input(iv_bytes);
294         hmac.input(metadata_bytes);
295         let decoded_payment_preimage = Hmac::from_engine(hmac).into_inner();
296         if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).into_inner()) {
297                 return Err(decoded_payment_preimage);
298         }
299         return Ok(PaymentPreimage(decoded_payment_preimage))
300 }