Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify compress_elements #2155

Draft
wants to merge 2 commits into
base: testnet3
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 8 additions & 14 deletions algorithms/src/crypto_hash/poseidon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ impl<F: PrimeField, const RATE: usize> PoseidonSponge<F, RATE, 1> {

/// Compress every two elements if possible.
/// Provides a vector of (limb, num_of_additions), both of which are F.
pub fn compress_elements<TargetField: PrimeField, I: Iterator<Item = (F, F)>>(
fn compress_elements<TargetField: PrimeField, I: Iterator<Item = F>>(
&self,
mut src_limbs: Peekable<I>,
ty: OptimizationType,
Expand All @@ -343,30 +343,25 @@ impl<F: PrimeField, const RATE: usize> PoseidonSponge<F, RATE, 1> {

let params = get_params(TargetField::size_in_bits(), F::size_in_bits(), ty);

// Prepare a reusable vector to be used in overhead calculation.
let mut num_bits = Vec::new();
let overhead = crate::overhead!(F::one() + F::one(), &mut Vec::new());

while let Some(first) = src_limbs.next() {
let second = src_limbs.peek();

let first_max_bits_per_limb = params.bits_per_limb + crate::overhead!(first.1 + F::one(), &mut num_bits);
let second_max_bits_per_limb = if let Some(second) = second {
params.bits_per_limb + crate::overhead!(second.1 + F::one(), &mut num_bits)
} else {
0
};
let first_max_bits_per_limb = params.bits_per_limb + overhead;
let second_max_bits_per_limb = if second.is_some() { first_max_bits_per_limb } else { 0 };

if let Some(second) = second {
if first_max_bits_per_limb + second_max_bits_per_limb <= capacity {
let adjustment_factor = &self.adjustment_factor_lookup_table[second_max_bits_per_limb];

dest_limbs.push(first.0 * adjustment_factor + second.0);
dest_limbs.push(first * adjustment_factor + second);
src_limbs.next();
} else {
dest_limbs.push(first.0);
dest_limbs.push(first);
}
} else {
dest_limbs.push(first.0);
dest_limbs.push(first);
}
}

Expand Down Expand Up @@ -421,8 +416,7 @@ impl<F: PrimeField, const RATE: usize> PoseidonSponge<F, RATE, 1> {
.into_iter()
.flat_map(|elem| {
let limbs = Self::get_limbs_representations(&elem, ty);
limbs.into_iter().map(|limb| (limb, F::one()))
// specifically set to one, since most gadgets in the constraint world would not have zero noise (due to the relatively weak normal form testing in `alloc`)
limbs.into_iter()
})
.peekable();

Expand Down