Skip to content

Commit

Permalink
separate add_rc and s_box
Browse files Browse the repository at this point in the history
  • Loading branch information
alxiong committed Jan 14, 2025
1 parent 4cc4b4a commit 8451434
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 11 deletions.
7 changes: 4 additions & 3 deletions poseidon2/src/external.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use ark_ff::PrimeField;

use crate::add_rc_and_sbox;
use crate::{add_rcs, s_box};

/// The fastest 4x4 MDS matrix.
/// [ 2 3 1 1 ]
Expand Down Expand Up @@ -88,8 +88,9 @@ pub(crate) fn permute_state<F: PrimeField, const T: usize>(
rc: &'static [F; T],
d: usize,
) {
for i in 0..T {
add_rc_and_sbox(&mut state[i], rc[i], d)
add_rcs(state, rc);
for s in state.iter_mut() {
s_box(s, d);
}
matmul_external(state);
}
5 changes: 3 additions & 2 deletions poseidon2/src/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use ark_ff::PrimeField;

use crate::add_rc_and_sbox;
use crate::s_box;

/// Matrix multiplication in the internal layers
/// Given a vector v compute the matrix vector product (1 + diag(v))*state
Expand Down Expand Up @@ -55,6 +55,7 @@ pub(crate) fn permute_state<F: PrimeField, const T: usize>(
d: usize,
mat_diag_minus_1: &'static [F; T],
) {
add_rc_and_sbox(&mut state[0], rc, d);
state[0] += rc;
s_box(&mut state[0], d);
matmul_internal(state, mat_diag_minus_1);
}
16 changes: 10 additions & 6 deletions poseidon2/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,14 +122,18 @@ impl<F: PrimeField> Poseidon2<F> {
}
}

/// A generic method performing the transformation, used both in external and
/// internal layers:
///
/// `s -> (s + rc)^d`
// @credit: `add_rc_and_sbox_generic()` in plonky3
/// add RCs to the entire state
#[inline(always)]
pub(crate) fn add_rcs<F: PrimeField, const T: usize>(state: &mut [F; T], rc: &[F; T]) {
for i in 0..T {
state[i] += rc[i];
}
}

/// `s -> s^d`
#[inline(always)]
pub(crate) fn add_rc_and_sbox<F: PrimeField>(val: &mut F, rc: F, d: usize) {
*val += rc;
pub(crate) fn s_box<F: PrimeField>(val: &mut F, d: usize) {
if d == 5 {
// Perform unrolled computation for val^5, faster
let original = *val;
Expand Down

0 comments on commit 8451434

Please sign in to comment.