Skip to content

Commit

Permalink
refactor: better encapsulation of signature functions
Browse files Browse the repository at this point in the history
  • Loading branch information
bobbinth committed Mar 15, 2024
1 parent 2806bf5 commit 69ee99b
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 77 deletions.
13 changes: 6 additions & 7 deletions src/dsa/rpo_falcon512/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ use super::{
decode_i8, encode_i8, ffldl, ffsampling, gram, normalize_tree, ntru_gen, FalconFelt,
FastFft, LdlTree, Polynomial,
},
signature::SignaturePoly,
ByteReader, ByteWriter, Deserializable, DeserializationError, FalconError, Felt, HashToPoint,
Nonce, Serializable, ShortLatticeBasis, Signature, Word, MODULUS, N, SIGMA, SIG_L2_BOUND,
};
use crate::dsa::rpo_falcon512::{math::compress_signature, SIG_NONCE_LEN, SK_LEN};
use crate::dsa::rpo_falcon512::{SIG_NONCE_LEN, SK_LEN};
use crate::utils::collections::*;
use num::Complex;
use num_complex::Complex64;
Expand Down Expand Up @@ -122,7 +123,7 @@ impl SecretKey {
let t0 = c_over_q_fft.hadamard_mul(&minus_big_f_fft);
let t1 = -c_over_q_fft.hadamard_mul(&minus_f_fft);

let s2_coef = loop {
let s2 = loop {
let bold_s = loop {
let z = ffsampling(&(t0.clone(), t1.clone()), &self.tree, rng);
let t0_min_z0 = t0.clone() - z.0;
Expand Down Expand Up @@ -154,15 +155,13 @@ impl SecretKey {
.try_into()
.expect("The number of coefficients should be equal to N");

if compress_signature(&s2_coef).is_some() {
break s2_coef;
if let Ok(s2) = SignaturePoly::try_from(&s2_coef) {
break s2;
}
};

let pk = self.compute_pub_key_poly();
let s2: Polynomial<FalconFelt> = s2_coef.to_vec().into();

Ok(Signature::new(pk, s2.into(), nonce, htp))
Ok(Signature::new(pk, s2, nonce, htp))
}

/// Serializes the secret key to a vector of bytes.
Expand Down
69 changes: 1 addition & 68 deletions src/dsa/rpo_falcon512/math/codec.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{vec, Vec};

Check failure on line 1 in src/dsa/rpo_falcon512/math/codec.rs

View workflow job for this annotation

GitHub Actions / clippy nightly on ubuntu

the item `Vec` is imported redundantly

Check warning on line 1 in src/dsa/rpo_falcon512/math/codec.rs

View workflow job for this annotation

GitHub Actions / test nightly on ubuntu with --features default,serde

the item `Vec` is imported redundantly
use crate::dsa::rpo_falcon512::{N, SIG_LEN};
use crate::dsa::rpo_falcon512::N;

/// Encodes a sequence of signed integers such that each integer x satisfies |x| < 2^(bits-1)
/// for a given parameter bits. bits can take either the value 6 or 8.
Expand Down Expand Up @@ -75,70 +75,3 @@ pub fn decode_i8(buf: &[u8], bits: usize) -> Option<Vec<i8>> {
None
}
}

/// Takes as input a list of integers x and returns a bytestring that encodes/compress' it.
/// If this is not possible, it returns False.
///
/// For each coefficient of x:
/// - the sign is encoded on 1 bit
/// - the 7 lower bits are encoded naively (binary)
/// - the high bits are encoded in unary encoding
///
/// This method can fail, in which case it returns None.
///
/// Algorithm 17 p. 47 of the specification [1].
///
/// [1]: https://falcon-sign.info/falcon.pdf
pub fn compress_signature(x: &[i16]) -> Option<Vec<u8>> {
let mut buf = vec![0_u8; SIG_LEN];
if x.len() != N {
return None;
}

for &c in x {
if !(-2047..=2047).contains(&c) {
return None;
}
}

let mut acc = 0;
let mut acc_len = 0;
let mut v = 0;
let mut t;
let mut w;

for &c in x {
acc <<= 1;
t = c;

if t < 0 {
t = -t;
acc |= 1;
}
w = t as u16;

acc <<= 7;
let mask = 127_u32;
acc |= (w as u32) & mask;
w >>= 7;

acc_len += 8;

acc <<= w + 1;
acc |= 1;
acc_len += w + 1;

while acc_len >= 8 {
acc_len -= 8;

buf[v] = (acc >> acc_len) as u8;
v += 1;
}
}

if acc_len > 0 {
buf[v] = (acc << (8 - acc_len)) as u8;
}

Some(buf)
}
2 changes: 1 addition & 1 deletion src/dsa/rpo_falcon512/math/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ mod polynomial;
pub use polynomial::Polynomial;

mod codec;
pub use codec::{compress_signature, decode_i8, encode_i8};
pub use codec::{decode_i8, encode_i8};

pub trait Inverse: Copy + Zero + MulAssign + One {
/// Gets the inverse of a, or zero if it is zero.
Expand Down
90 changes: 89 additions & 1 deletion src/dsa/rpo_falcon512/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use core::ops::Deref;

use super::{
keys::PubKeyPoly,
math::{compress_signature, FalconFelt, FastFft, Polynomial},
math::{FalconFelt, FastFft, Polynomial},
ByteReader, ByteWriter, Deserializable, DeserializationError, FalconError, Felt, HashToPoint,
Nonce, Rpo256, Serializable, Word, LOG_N, MODULUS, N, SIG_L2_BOUND, SIG_LEN,
};
Expand Down Expand Up @@ -218,6 +218,18 @@ impl From<Polynomial<FalconFelt>> for SignaturePoly {
}
}

impl TryFrom<&[i16; N]> for SignaturePoly {
type Error = ();

fn try_from(coefficients: &[i16; N]) -> Result<Self, Self::Error> {
if are_coefficients_valid(coefficients) {
Ok(Self(coefficients.to_vec().into()))
} else {
Err(())
}
}
}

impl Serializable for SignaturePoly {
fn write_into<W: ByteWriter>(&self, target: &mut W) {
let sig_coeff: Vec<i16> = self.0.coefficients.iter().map(|a| a.balanced_value()).collect();

Check failure on line 235 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test stable on ubuntu with --no-default-features

cannot find type `Vec` in this scope

Check failure on line 235 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test nightly on ubuntu with --no-default-features

cannot find type `Vec` in this scope
Expand All @@ -238,6 +250,82 @@ impl Deserializable for SignaturePoly {
// HELPER FUNCTIONS
// ================================================================================================

fn are_coefficients_valid(x: &[i16]) -> bool {
if x.len() != N {
return false;
}

for &c in x {
if !(-2047..=2047).contains(&c) {
return false;
}
}

true
}

/// Takes as input a list of integers x and returns a bytestring that encodes/compress' it.
/// If this is not possible, it returns False.
///
/// For each coefficient of x:
/// - the sign is encoded on 1 bit
/// - the 7 lower bits are encoded naively (binary)
/// - the high bits are encoded in unary encoding
///
/// This method can fail, in which case it returns None.
///
/// Algorithm 17 p. 47 of the specification [1].
///
/// [1]: https://falcon-sign.info/falcon.pdf
fn compress_signature(x: &[i16]) -> Option<Vec<u8>> {

Check failure on line 280 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test stable on ubuntu with --no-default-features

cannot find type `Vec` in this scope

Check failure on line 280 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test nightly on ubuntu with --no-default-features

cannot find type `Vec` in this scope
let mut buf = vec![0_u8; SIG_LEN];

Check failure on line 281 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test stable on ubuntu with --no-default-features

cannot find macro `vec` in this scope

Check failure on line 281 in src/dsa/rpo_falcon512/signature.rs

View workflow job for this annotation

GitHub Actions / test nightly on ubuntu with --no-default-features

cannot find macro `vec` in this scope

if !are_coefficients_valid(x) {
return None;
}

let mut acc = 0;
let mut acc_len = 0;
let mut v = 0;
let mut t;
let mut w;

for &c in x {
acc <<= 1;
t = c;

if t < 0 {
t = -t;
acc |= 1;
}
w = t as u16;

acc <<= 7;
let mask = 127_u32;
acc |= (w as u32) & mask;
w >>= 7;

acc_len += 8;

acc <<= w + 1;
acc |= 1;
acc_len += w + 1;

while acc_len >= 8 {
acc_len -= 8;

buf[v] = (acc >> acc_len) as u8;
v += 1;
}
}

if acc_len > 0 {
buf[v] = (acc << (8 - acc_len)) as u8;
}

Some(buf)
}

/// Takes as input an encoding `input` and returns a list of integers x of length N such that
/// `inputs` encodes x. If such a list does not exist, the encoding is invalid and we output
/// an error.
Expand Down

0 comments on commit 69ee99b

Please sign in to comment.