Skip to content

Commit 01f50bc

Browse files
committed
Run rustfmt on inbound_payment.rs
1 parent aadff79 commit 01f50bc

File tree

2 files changed

+141
-60
lines changed

2 files changed

+141
-60
lines changed

lightning/src/ln/inbound_payment.rs

+141-59
Original file line numberDiff line numberDiff line change
@@ -9,18 +9,18 @@
99

1010
//! Utilities to generate inbound payment information in service of invoice creation.
1111
12-
use bitcoin::hashes::{Hash, HashEngine};
1312
use bitcoin::hashes::cmp::fixed_time_eq;
1413
use bitcoin::hashes::hmac::{Hmac, HmacEngine};
1514
use bitcoin::hashes::sha256::Hash as Sha256;
15+
use bitcoin::hashes::{Hash, HashEngine};
1616

1717
use crate::crypto::chacha20::ChaCha20;
1818
use crate::crypto::utils::hkdf_extract_expand_6x;
1919
use crate::ln::msgs;
2020
use crate::ln::msgs::MAX_VALUE_MSAT;
21-
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
2221
use crate::offers::nonce::Nonce;
2322
use crate::sign::EntropySource;
23+
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
2424
use crate::util::errors::APIError;
2525
use crate::util::logger::Logger;
2626

@@ -112,8 +112,12 @@ impl Method {
112112
match bits {
113113
bits if bits == Method::LdkPaymentHash as u8 => Ok(Method::LdkPaymentHash),
114114
bits if bits == Method::UserPaymentHash as u8 => Ok(Method::UserPaymentHash),
115-
bits if bits == Method::LdkPaymentHashCustomFinalCltv as u8 => Ok(Method::LdkPaymentHashCustomFinalCltv),
116-
bits if bits == Method::UserPaymentHashCustomFinalCltv as u8 => Ok(Method::UserPaymentHashCustomFinalCltv),
115+
bits if bits == Method::LdkPaymentHashCustomFinalCltv as u8 => {
116+
Ok(Method::LdkPaymentHashCustomFinalCltv)
117+
},
118+
bits if bits == Method::UserPaymentHashCustomFinalCltv as u8 => {
119+
Ok(Method::UserPaymentHashCustomFinalCltv)
120+
},
117121
bits if bits == Method::SpontaneousPayment as u8 => Ok(Method::SpontaneousPayment),
118122
unknown => Err(unknown),
119123
}
@@ -139,16 +143,24 @@ fn min_final_cltv_expiry_delta_from_metadata(bytes: [u8; METADATA_LEN]) -> u16 {
139143
///
140144
/// [phantom node payments]: crate::sign::PhantomKeysManager
141145
/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
142-
pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>,
143-
invoice_expiry_delta_secs: u32, entropy_source: &ES, current_time: u64,
144-
min_final_cltv_expiry_delta: Option<u16>) -> Result<(PaymentHash, PaymentSecret), ()>
145-
where ES::Target: EntropySource
146+
pub fn create<ES: Deref>(
147+
keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
148+
entropy_source: &ES, current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
149+
) -> Result<(PaymentHash, PaymentSecret), ()>
150+
where
151+
ES::Target: EntropySource,
146152
{
147-
let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
153+
let metadata_bytes = construct_metadata_bytes(
154+
min_value_msat,
155+
if min_final_cltv_expiry_delta.is_some() {
148156
Method::LdkPaymentHashCustomFinalCltv
149157
} else {
150158
Method::LdkPaymentHash
151-
}, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
159+
},
160+
invoice_expiry_delta_secs,
161+
current_time,
162+
min_final_cltv_expiry_delta,
163+
)?;
152164

153165
let mut iv_bytes = [0 as u8; IV_LEN];
154166
let rand_bytes = entropy_source.get_secure_random_bytes();
@@ -174,13 +186,21 @@ pub fn create<ES: Deref>(keys: &ExpandedKey, min_value_msat: Option<u64>,
174186
/// on versions of LDK prior to 0.0.114.
175187
///
176188
/// [phantom node payments]: crate::sign::PhantomKeysManager
177-
pub fn create_from_hash(keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash,
178-
invoice_expiry_delta_secs: u32, current_time: u64, min_final_cltv_expiry_delta: Option<u16>) -> Result<PaymentSecret, ()> {
179-
let metadata_bytes = construct_metadata_bytes(min_value_msat, if min_final_cltv_expiry_delta.is_some() {
189+
pub fn create_from_hash(
190+
keys: &ExpandedKey, min_value_msat: Option<u64>, payment_hash: PaymentHash,
191+
invoice_expiry_delta_secs: u32, current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
192+
) -> Result<PaymentSecret, ()> {
193+
let metadata_bytes = construct_metadata_bytes(
194+
min_value_msat,
195+
if min_final_cltv_expiry_delta.is_some() {
180196
Method::UserPaymentHashCustomFinalCltv
181197
} else {
182198
Method::UserPaymentHash
183-
}, invoice_expiry_delta_secs, current_time, min_final_cltv_expiry_delta)?;
199+
},
200+
invoice_expiry_delta_secs,
201+
current_time,
202+
min_final_cltv_expiry_delta,
203+
)?;
184204

185205
let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
186206
hmac.input(&metadata_bytes);
@@ -196,11 +216,14 @@ pub fn create_from_hash(keys: &ExpandedKey, min_value_msat: Option<u64>, payment
196216
#[cfg(async_payments)]
197217
pub(super) fn create_for_spontaneous_payment(
198218
keys: &ExpandedKey, min_value_msat: Option<u64>, invoice_expiry_delta_secs: u32,
199-
current_time: u64, min_final_cltv_expiry_delta: Option<u16>
219+
current_time: u64, min_final_cltv_expiry_delta: Option<u16>,
200220
) -> Result<PaymentSecret, ()> {
201221
let metadata_bytes = construct_metadata_bytes(
202-
min_value_msat, Method::SpontaneousPayment, invoice_expiry_delta_secs, current_time,
203-
min_final_cltv_expiry_delta
222+
min_value_msat,
223+
Method::SpontaneousPayment,
224+
invoice_expiry_delta_secs,
225+
current_time,
226+
min_final_cltv_expiry_delta,
204227
)?;
205228

206229
let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
@@ -213,7 +236,9 @@ pub(super) fn create_for_spontaneous_payment(
213236
Ok(construct_payment_secret(&iv_bytes, &metadata_bytes, &keys.metadata_key))
214237
}
215238

216-
pub(super) fn calculate_absolute_expiry(highest_seen_timestamp: u64, invoice_expiry_delta_secs: u32) -> u64 {
239+
pub(super) fn calculate_absolute_expiry(
240+
highest_seen_timestamp: u64, invoice_expiry_delta_secs: u32,
241+
) -> u64 {
217242
// We assume that highest_seen_timestamp is pretty close to the current time - it's updated when
218243
// we receive a new block with the maximum time we've seen in a header. It should never be more
219244
// than two hours in the future. Thus, we add two hours here as a buffer to ensure we
@@ -222,8 +247,10 @@ pub(super) fn calculate_absolute_expiry(highest_seen_timestamp: u64, invoice_exp
222247
highest_seen_timestamp + invoice_expiry_delta_secs as u64 + 7200
223248
}
224249

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], ()> {
250+
fn construct_metadata_bytes(
251+
min_value_msat: Option<u64>, payment_type: Method, invoice_expiry_delta_secs: u32,
252+
highest_seen_timestamp: u64, min_final_cltv_expiry_delta: Option<u16>,
253+
) -> Result<[u8; METADATA_LEN], ()> {
227254
if min_value_msat.is_some() && min_value_msat.unwrap() > MAX_VALUE_MSAT {
228255
return Err(());
229256
}
@@ -234,18 +261,23 @@ fn construct_metadata_bytes(min_value_msat: Option<u64>, payment_type: Method,
234261
};
235262
min_amt_msat_bytes[0] |= (payment_type as u8) << METHOD_TYPE_OFFSET;
236263

237-
let expiry_timestamp = calculate_absolute_expiry(highest_seen_timestamp, invoice_expiry_delta_secs);
264+
let expiry_timestamp =
265+
calculate_absolute_expiry(highest_seen_timestamp, invoice_expiry_delta_secs);
238266
let mut expiry_bytes = expiry_timestamp.to_be_bytes();
239267

240268
// `min_value_msat` should fit in (64 bits - 3 payment type bits =) 61 bits as an unsigned integer.
241269
// This should leave us with a maximum value greater than the 21M BTC supply cap anyway.
242-
if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) { return Err(()); }
270+
if min_value_msat.is_some() && min_value_msat.unwrap() > ((1u64 << 61) - 1) {
271+
return Err(());
272+
}
243273

244274
// `expiry_timestamp` should fit in (64 bits - 2 delta bytes =) 48 bits as an unsigned integer.
245275
// Bitcoin's block header timestamps are actually `u32`s, so we're technically already limited to
246276
// the much smaller maximum timestamp of `u32::MAX` for now, but we check the u64 `expiry_timestamp`
247277
// for future-proofing.
248-
if min_final_cltv_expiry_delta.is_some() && expiry_timestamp > ((1u64 << 48) - 1) { return Err(()); }
278+
if min_final_cltv_expiry_delta.is_some() && expiry_timestamp > ((1u64 << 48) - 1) {
279+
return Err(());
280+
}
249281

250282
if let Some(min_final_cltv_expiry_delta) = min_final_cltv_expiry_delta {
251283
let bytes = min_final_cltv_expiry_delta.to_be_bytes();
@@ -261,13 +293,19 @@ fn construct_metadata_bytes(min_value_msat: Option<u64>, payment_type: Method,
261293
Ok(metadata_bytes)
262294
}
263295

264-
fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], metadata_key: &[u8; METADATA_KEY_LEN]) -> PaymentSecret {
296+
fn construct_payment_secret(
297+
iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN],
298+
metadata_key: &[u8; METADATA_KEY_LEN],
299+
) -> PaymentSecret {
265300
let mut payment_secret_bytes: [u8; 32] = [0; 32];
266301
let (iv_slice, encrypted_metadata_slice) = payment_secret_bytes.split_at_mut(IV_LEN);
267302
iv_slice.copy_from_slice(iv_bytes);
268303

269304
ChaCha20::encrypt_single_block(
270-
metadata_key, iv_bytes, encrypted_metadata_slice, metadata_bytes
305+
metadata_key,
306+
iv_bytes,
307+
encrypted_metadata_slice,
308+
metadata_bytes,
271309
);
272310
PaymentSecret(payment_secret_bytes)
273311
}
@@ -308,14 +346,17 @@ fn construct_payment_secret(iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METAD
308346
/// [`NodeSigner::get_inbound_payment_key`]: crate::sign::NodeSigner::get_inbound_payment_key
309347
/// [`create_inbound_payment`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment
310348
/// [`create_inbound_payment_for_hash`]: crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash
311-
pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData,
312-
highest_seen_timestamp: u64, keys: &ExpandedKey, logger: &L) -> Result<
313-
(Option<PaymentPreimage>, Option<u16>), ()>
314-
where L::Target: Logger
349+
pub(super) fn verify<L: Deref>(
350+
payment_hash: PaymentHash, payment_data: &msgs::FinalOnionHopData, highest_seen_timestamp: u64,
351+
keys: &ExpandedKey, logger: &L,
352+
) -> Result<(Option<PaymentPreimage>, Option<u16>), ()>
353+
where
354+
L::Target: Logger,
315355
{
316356
let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_data.payment_secret, keys);
317357

318-
let payment_type_res = Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
358+
let payment_type_res =
359+
Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET);
319360
let mut amt_msat_bytes = [0; AMT_MSAT_LEN];
320361
let mut expiry_bytes = [0; METADATA_LEN - AMT_MSAT_LEN];
321362
amt_msat_bytes.copy_from_slice(&metadata_bytes[..AMT_MSAT_LEN]);
@@ -332,102 +373,143 @@ pub(super) fn verify<L: Deref>(payment_hash: PaymentHash, payment_data: &msgs::F
332373
let mut hmac = HmacEngine::<Sha256>::new(&keys.user_pmt_hash_key);
333374
hmac.input(&metadata_bytes[..]);
334375
hmac.input(&payment_hash.0);
335-
if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0) {
336-
log_trace!(logger, "Failing HTLC with user-generated payment_hash {}: unexpected payment_secret", &payment_hash);
337-
return Err(())
376+
if !fixed_time_eq(
377+
&iv_bytes,
378+
&Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0,
379+
) {
380+
log_trace!(
381+
logger,
382+
"Failing HTLC with user-generated payment_hash {}: unexpected payment_secret",
383+
&payment_hash
384+
);
385+
return Err(());
338386
}
339387
},
340388
Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
341389
match derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys) {
342390
Ok(preimage) => payment_preimage = Some(preimage),
343391
Err(bad_preimage_bytes) => {
344-
log_trace!(logger, "Failing HTLC with payment_hash {} due to mismatching preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes));
345-
return Err(())
346-
}
392+
log_trace!(
393+
logger,
394+
"Failing HTLC with payment_hash {} due to mismatching preimage {}",
395+
&payment_hash,
396+
log_bytes!(bad_preimage_bytes)
397+
);
398+
return Err(());
399+
},
347400
}
348401
},
349402
Ok(Method::SpontaneousPayment) => {
350403
let mut hmac = HmacEngine::<Sha256>::new(&keys.spontaneous_pmt_key);
351404
hmac.input(&metadata_bytes[..]);
352-
if !fixed_time_eq(&iv_bytes, &Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0) {
405+
if !fixed_time_eq(
406+
&iv_bytes,
407+
&Hmac::from_engine(hmac).to_byte_array().split_at_mut(IV_LEN).0,
408+
) {
353409
log_trace!(logger, "Failing async payment HTLC with sender-generated payment_hash {}: unexpected payment_secret", &payment_hash);
354-
return Err(())
410+
return Err(());
355411
}
356412
},
357413
Err(unknown_bits) => {
358-
log_trace!(logger, "Failing HTLC with payment hash {} due to unknown payment type {}", &payment_hash, unknown_bits);
414+
log_trace!(
415+
logger,
416+
"Failing HTLC with payment hash {} due to unknown payment type {}",
417+
&payment_hash,
418+
unknown_bits
419+
);
359420
return Err(());
360-
}
421+
},
361422
}
362423

363424
match payment_type_res {
364425
Ok(Method::UserPaymentHashCustomFinalCltv) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
365-
min_final_cltv_expiry_delta = Some(min_final_cltv_expiry_delta_from_metadata(metadata_bytes));
426+
min_final_cltv_expiry_delta =
427+
Some(min_final_cltv_expiry_delta_from_metadata(metadata_bytes));
366428
// Zero out first two bytes of expiry reserved for `min_final_cltv_expiry_delta`.
367429
expiry_bytes[0] &= 0;
368430
expiry_bytes[1] &= 0;
369-
}
370-
_ => {}
431+
},
432+
_ => {},
371433
}
372434

373435
let min_amt_msat: u64 = u64::from_be_bytes(amt_msat_bytes.into());
374436
let expiry = u64::from_be_bytes(expiry_bytes.try_into().unwrap());
375437

376438
if payment_data.total_msat < min_amt_msat {
377439
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);
378-
return Err(())
440+
return Err(());
379441
}
380442

381443
if expiry < highest_seen_timestamp {
382444
log_trace!(logger, "Failing HTLC with payment_hash {}: expired payment", &payment_hash);
383-
return Err(())
445+
return Err(());
384446
}
385447

386448
Ok((payment_preimage, min_final_cltv_expiry_delta))
387449
}
388450

389-
pub(super) fn get_payment_preimage(payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey) -> Result<PaymentPreimage, APIError> {
451+
pub(super) fn get_payment_preimage(
452+
payment_hash: PaymentHash, payment_secret: PaymentSecret, keys: &ExpandedKey,
453+
) -> Result<PaymentPreimage, APIError> {
390454
let (iv_bytes, metadata_bytes) = decrypt_metadata(payment_secret, keys);
391455

392456
match Method::from_bits((metadata_bytes[0] & 0b1110_0000) >> METHOD_TYPE_OFFSET) {
393457
Ok(Method::LdkPaymentHash) | Ok(Method::LdkPaymentHashCustomFinalCltv) => {
394-
derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys)
395-
.map_err(|bad_preimage_bytes| APIError::APIMisuseError {
396-
err: format!("Payment hash {} did not match decoded preimage {}", &payment_hash, log_bytes!(bad_preimage_bytes))
397-
})
458+
derive_ldk_payment_preimage(payment_hash, &iv_bytes, &metadata_bytes, keys).map_err(
459+
|bad_preimage_bytes| APIError::APIMisuseError {
460+
err: format!(
461+
"Payment hash {} did not match decoded preimage {}",
462+
&payment_hash,
463+
log_bytes!(bad_preimage_bytes)
464+
),
465+
},
466+
)
467+
},
468+
Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => {
469+
Err(APIError::APIMisuseError {
470+
err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash"
471+
.to_string(),
472+
})
398473
},
399-
Ok(Method::UserPaymentHash) | Ok(Method::UserPaymentHashCustomFinalCltv) => Err(APIError::APIMisuseError {
400-
err: "Expected payment type to be LdkPaymentHash, instead got UserPaymentHash".to_string()
401-
}),
402474
Ok(Method::SpontaneousPayment) => Err(APIError::APIMisuseError {
403-
err: "Can't extract payment preimage for spontaneous payments".to_string()
475+
err: "Can't extract payment preimage for spontaneous payments".to_string(),
404476
}),
405-
Err(other) => Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) }),
477+
Err(other) => {
478+
Err(APIError::APIMisuseError { err: format!("Unknown payment type: {}", other) })
479+
},
406480
}
407481
}
408482

409-
fn decrypt_metadata(payment_secret: PaymentSecret, keys: &ExpandedKey) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
483+
fn decrypt_metadata(
484+
payment_secret: PaymentSecret, keys: &ExpandedKey,
485+
) -> ([u8; IV_LEN], [u8; METADATA_LEN]) {
410486
let mut iv_bytes = [0; IV_LEN];
411487
let (iv_slice, encrypted_metadata_bytes) = payment_secret.0.split_at(IV_LEN);
412488
iv_bytes.copy_from_slice(iv_slice);
413489

414490
let mut metadata_bytes: [u8; METADATA_LEN] = [0; METADATA_LEN];
415491
ChaCha20::encrypt_single_block(
416-
&keys.metadata_key, &iv_bytes, &mut metadata_bytes, encrypted_metadata_bytes
492+
&keys.metadata_key,
493+
&iv_bytes,
494+
&mut metadata_bytes,
495+
encrypted_metadata_bytes,
417496
);
418497

419498
(iv_bytes, metadata_bytes)
420499
}
421500

422501
// Errors if the payment preimage doesn't match `payment_hash`. Returns the bad preimage bytes in
423502
// this case.
424-
fn derive_ldk_payment_preimage(payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN], keys: &ExpandedKey) -> Result<PaymentPreimage, [u8; 32]> {
503+
fn derive_ldk_payment_preimage(
504+
payment_hash: PaymentHash, iv_bytes: &[u8; IV_LEN], metadata_bytes: &[u8; METADATA_LEN],
505+
keys: &ExpandedKey,
506+
) -> Result<PaymentPreimage, [u8; 32]> {
425507
let mut hmac = HmacEngine::<Sha256>::new(&keys.ldk_pmt_hash_key);
426508
hmac.input(iv_bytes);
427509
hmac.input(metadata_bytes);
428510
let decoded_payment_preimage = Hmac::from_engine(hmac).to_byte_array();
429511
if !fixed_time_eq(&payment_hash.0, &Sha256::hash(&decoded_payment_preimage).to_byte_array()) {
430512
return Err(decoded_payment_preimage);
431513
}
432-
return Ok(PaymentPreimage(decoded_payment_preimage))
514+
return Ok(PaymentPreimage(decoded_payment_preimage));
433515
}

rustfmt_excluded_files

-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ lightning/src/ln/channel.rs
1616
lightning/src/ln/channelmanager.rs
1717
lightning/src/ln/functional_test_utils.rs
1818
lightning/src/ln/functional_tests.rs
19-
lightning/src/ln/inbound_payment.rs
2019
lightning/src/ln/max_payment_path_len_tests.rs
2120
lightning/src/ln/mod.rs
2221
lightning/src/ln/monitor_tests.rs

0 commit comments

Comments
 (0)