Skip to content

Commit

Permalink
Small optimization: Invoke hash_from_parts() in only one place
Browse files Browse the repository at this point in the history
  • Loading branch information
optout21 committed Sep 8, 2024
1 parent 70e6563 commit ca0e089
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 18 deletions.
15 changes: 7 additions & 8 deletions lightning-invoice/src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,16 +374,15 @@ impl FromStr for SignedRawBolt11Invoice {

let raw_hrp: RawHrp = hrp.to_string().to_lowercase().parse()?;
let data_part = RawDataPart::from_base32(&data[..data.len() - SIGNATURE_LEN5])?;
let raw_invoice = RawBolt11Invoice {
hrp: raw_hrp,
data: data_part,
};
let hash = raw_invoice.signable_hash();

Ok(SignedRawBolt11Invoice {
raw_invoice: RawBolt11Invoice {
hrp: raw_hrp,
data: data_part,
},
hash: RawBolt11Invoice::hash_from_parts(
hrp.to_string().as_bytes(),
&data[..data.len() - SIGNATURE_LEN5],
),
raw_invoice,
hash,
signature: Bolt11InvoiceSignature::from_base32(&data[data.len() - SIGNATURE_LEN5..])?,
})
}
Expand Down
15 changes: 5 additions & 10 deletions lightning-invoice/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1001,18 +1001,12 @@ macro_rules! find_all_extract {
#[allow(missing_docs)]
impl RawBolt11Invoice {
/// Hash the HRP (as bytes) and signatureless data part (as Fe32 iterator)
fn hash_from_parts_iter<'s>(hrp_bytes: &[u8], data_without_signature_iter: Box<dyn Iterator<Item = Fe32> + 's>) -> [u8; 32] {
let data_part_signature = data_without_signature_iter.collect::<Vec<Fe32>>();
Self::hash_from_parts(hrp_bytes, &data_part_signature[..])
}

/// Hash the HRP as bytes and signatureless data part.
fn hash_from_parts(hrp_bytes: &[u8], data_without_signature: &[Fe32]) -> [u8; 32] {
fn hash_from_parts<'s>(hrp_bytes: &[u8], data_without_signature: Box<dyn Iterator<Item = Fe32> + 's>) -> [u8; 32] {
use crate::de::FromBase32;

let mut preimage = Vec::<u8>::from(hrp_bytes);
let mut data_part = data_without_signature.collect::<Vec<Fe32>>();

let mut data_part = Vec::from(data_without_signature);
// Need to pad before from_base32 conversion
let overhang = (data_part.len() * 5) % 8;
if overhang > 0 {
// add padding if data does not end at a byte boundary
Expand All @@ -1024,6 +1018,7 @@ impl RawBolt11Invoice {
}
}

let mut preimage = Vec::<u8>::from(hrp_bytes);
preimage.extend_from_slice(&Vec::<u8>::from_base32(&data_part)
.expect("No padding error may occur due to appended zero above."));

Expand All @@ -1036,7 +1031,7 @@ impl RawBolt11Invoice {
pub fn signable_hash(&self) -> [u8; 32] {
use crate::ser::Base32Iterable;

RawBolt11Invoice::hash_from_parts_iter(
Self::hash_from_parts(
self.hrp.to_string().as_bytes(),
self.data.fe_iter(),
)
Expand Down

0 comments on commit ca0e089

Please sign in to comment.