Compare commits

..

7 Commits

Author SHA1 Message Date
sydhds
2749be14c6 Fix fr_to_bytes_be function 2025-07-11 09:37:16 +02:00
sydhds
0f67f0ecd5 Add be functions in ffi 2025-07-10 08:24:45 +02:00
sydhds
acf313e032 Add hash_be and poseidon_hash_be functions 2025-06-30 12:18:47 +02:00
sydhds
2e3528c9b2 Add BE functions in public API too 2025-06-30 12:18:47 +02:00
sydhds
833bbd1fc3 Cargo fmt pass 2025-06-30 12:18:47 +02:00
sydhds
ce9e05484e Add BE serialization for Fr and identity pair/tuple 2025-06-30 12:18:47 +02:00
Sydhds
baf474e747 Use Vec::with_capacity for bytes_le_to_vec_fr (#321) 2025-06-23 10:13:39 +02:00
10 changed files with 259 additions and 170 deletions

23
Cargo.lock generated
View File

@@ -828,27 +828,6 @@ dependencies = [
"syn 1.0.109",
]
[[package]]
name = "derive_more"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "093242cf7570c207c83073cf82f79706fe7b8317e98620a47d5be7c3d8497678"
dependencies = [
"derive_more-impl",
]
[[package]]
name = "derive_more-impl"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bda628edc44c4bb645fbe0f758797143e4e07926f7ebf4e9bdfbd3d2ce621df3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.101",
"unicode-xid",
]
[[package]]
name = "digest"
version = "0.9.0"
@@ -1661,7 +1640,6 @@ dependencies = [
"byteorder",
"cfg-if",
"criterion",
"derive_more",
"document-features",
"lazy_static",
"num-bigint",
@@ -1675,7 +1653,6 @@ dependencies = [
"serde_json",
"thiserror",
"tiny-keccak",
"zeroize",
"zerokit_utils",
]

View File

@@ -12,7 +12,7 @@ use rln::{
hashers::{hash_to_field, poseidon_hash},
protocol::{keygen, prepare_prove_input, prepare_verify_input},
public::RLN,
utils::{bytes_le_to_fr, fr_to_bytes_le, generate_input_buffer, IdSecret},
utils::{bytes_le_to_fr, fr_to_bytes_le, generate_input_buffer},
};
const MESSAGE_LIMIT: u32 = 1;
@@ -44,7 +44,7 @@ enum Commands {
#[derive(Debug, Clone)]
struct Identity {
identity_secret_hash: IdSecret,
identity_secret_hash: Fr,
id_commitment: Fr,
}
@@ -143,7 +143,7 @@ impl RLNSystem {
};
let serialized = prepare_prove_input(
identity.identity_secret_hash.clone(),
identity.identity_secret_hash,
user_index,
Fr::from(MESSAGE_LIMIT),
Fr::from(message_id),
@@ -211,8 +211,7 @@ impl RLNSystem {
{
Ok(_) => {
let output_data = output.into_inner();
let (leaked_identity_secret_hash_, _) = bytes_le_to_fr(&output_data);
let leaked_identity_secret_hash = IdSecret::from(leaked_identity_secret_hash_);
let (leaked_identity_secret_hash, _) = bytes_le_to_fr(&output_data);
if let Some((user_index, identity)) = self
.local_identities
@@ -222,7 +221,7 @@ impl RLNSystem {
})
.map(|(index, identity)| (*index, identity))
{
let real_identity_secret_hash = identity.identity_secret_hash.clone();
let real_identity_secret_hash = identity.identity_secret_hash;
if leaked_identity_secret_hash != real_identity_secret_hash {
Err(eyre!("identity secret hash mismatch {leaked_identity_secret_hash} != {real_identity_secret_hash}"))
} else {

View File

@@ -54,8 +54,6 @@ rand_chacha = "0.3.1"
ruint = { version = "1.15.0", features = ["rand", "serde", "ark-ff-04"] }
tiny-keccak = { version = "2.0.2", features = ["keccak"] }
utils = { package = "zerokit_utils", version = "0.6.0", path = "../utils", default-features = false }
zeroize = "1.8.1"
derive_more = { version = "2.0.1", features = ["from", "into", "display"] }
# serialization
prost = "0.13.5"

View File

@@ -466,6 +466,12 @@ pub extern "C" fn key_gen(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, key_gen, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn key_gen_be(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, key_gen_be, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_key_gen(
@@ -476,12 +482,28 @@ pub extern "C" fn seeded_key_gen(
call_with_output_arg!(ctx, seeded_key_gen, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_key_gen_be(
ctx: *const RLN,
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(ctx, seeded_key_gen_be, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn extended_key_gen(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, extended_key_gen, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn extended_key_gen_be(ctx: *const RLN, output_buffer: *mut Buffer) -> bool {
call_with_output_arg!(ctx, extended_key_gen_be, output_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_extended_key_gen(
@@ -492,6 +514,16 @@ pub extern "C" fn seeded_extended_key_gen(
call_with_output_arg!(ctx, seeded_extended_key_gen, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn seeded_extended_key_gen_be(
ctx: *const RLN,
input_buffer: *const Buffer,
output_buffer: *mut Buffer,
) -> bool {
call_with_output_arg!(ctx, seeded_extended_key_gen_be, output_buffer, input_buffer)
}
#[allow(clippy::not_unsafe_ptr_arg_deref)]
#[no_mangle]
pub extern "C" fn recover_id_secret(

View File

@@ -10,8 +10,9 @@ use num_bigint::BigInt;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use serde::{Deserialize, Serialize};
#[cfg(test)]
use std::time::Instant;
use tiny_keccak::{Hasher as _, Keccak};
use zeroize::Zeroize;
use crate::circuit::{calculate_rln_witness, qap::CircomReduction, Curve};
use crate::error::{ComputeIdSecretError, ConversionError, ProofError, ProtocolError};
@@ -19,11 +20,10 @@ use crate::hashers::{hash_to_field, poseidon_hash};
use crate::poseidon_tree::{MerkleProof, PoseidonTree};
use crate::public::RLN_IDENTIFIER;
use crate::utils::{
bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, fr_byte_size, fr_to_bytes_le,
normalize_usize, to_bigint, vec_fr_to_bytes_le, vec_u8_to_bytes_le, IdSecret,
bytes_be_to_fr, bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, fr_byte_size,
fr_to_bytes_be, fr_to_bytes_le, normalize_usize, to_bigint, vec_fr_to_bytes_le,
vec_u8_to_bytes_le,
};
#[cfg(test)]
use std::time::Instant;
use utils::{ZerokitMerkleProof, ZerokitMerkleTree};
///////////////////////////////////////////////////////
// RLN Witness data structure and utility functions
@@ -32,7 +32,7 @@ use utils::{ZerokitMerkleProof, ZerokitMerkleTree};
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct RLNWitnessInput {
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
identity_secret: IdSecret,
identity_secret: Fr,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
user_message_limit: Fr,
#[serde(serialize_with = "ark_se", deserialize_with = "ark_de")]
@@ -61,9 +61,17 @@ pub fn serialize_field_element(element: Fr) -> Vec<u8> {
fr_to_bytes_le(&element)
}
pub fn serialize_field_element_be(element: Fr) -> Vec<u8> {
fr_to_bytes_be(&element)
}
pub fn deserialize_field_element(serialized: Vec<u8>) -> Fr {
let (element, _) = bytes_le_to_fr(&serialized);
element
}
pub fn deserialize_field_element_be(serialized: Vec<u8>) -> Fr {
let (element, _) = bytes_be_to_fr(&serialized);
element
}
@@ -74,6 +82,13 @@ pub fn deserialize_identity_pair(serialized: Vec<u8>) -> (Fr, Fr) {
(identity_secret_hash, id_commitment)
}
pub fn deserialize_identity_pair_be(serialized: Vec<u8>) -> (Fr, Fr) {
let (identity_secret_hash, read) = bytes_be_to_fr(&serialized);
let (id_commitment, _) = bytes_be_to_fr(&serialized[read..]);
(identity_secret_hash, id_commitment)
}
pub fn deserialize_identity_tuple(serialized: Vec<u8>) -> (Fr, Fr, Fr, Fr) {
let mut all_read = 0;
@@ -96,6 +111,28 @@ pub fn deserialize_identity_tuple(serialized: Vec<u8>) -> (Fr, Fr, Fr, Fr) {
)
}
pub fn deserialize_identity_tuple_be(serialized: Vec<u8>) -> (Fr, Fr, Fr, Fr) {
let mut all_read = 0;
let (identity_trapdoor, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_nullifier, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_secret_hash, read) = bytes_be_to_fr(&serialized[all_read..]);
all_read += read;
let (identity_commitment, _) = bytes_be_to_fr(&serialized[all_read..]);
(
identity_trapdoor,
identity_nullifier,
identity_secret_hash,
identity_commitment,
)
}
/// Serializes witness
///
/// # Errors
@@ -133,9 +170,7 @@ pub fn serialize_witness(rln_witness: &RLNWitnessInput) -> Result<Vec<u8>, Proto
pub fn deserialize_witness(serialized: &[u8]) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut all_read: usize = 0;
let (mut identity_secret_, read) = bytes_le_to_fr(&serialized[all_read..]);
let identity_secret = IdSecret::from(identity_secret_);
identity_secret_.zeroize();
let (identity_secret, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let (user_message_limit, read) = bytes_le_to_fr(&serialized[all_read..]);
@@ -186,10 +221,7 @@ pub fn proof_inputs_to_rln_witness(
) -> Result<(RLNWitnessInput, usize), ProtocolError> {
let mut all_read: usize = 0;
let (mut identity_secret_, read) = bytes_le_to_fr(&serialized[all_read..]);
let identity_secret = IdSecret::from(identity_secret_);
identity_secret_.zeroize();
let (identity_secret, read) = bytes_le_to_fr(&serialized[all_read..]);
all_read += read;
let id_index = usize::try_from(u64::from_le_bytes(
@@ -245,7 +277,7 @@ pub fn proof_inputs_to_rln_witness(
///
/// Returns an error if `message_id` is not within `user_message_limit`.
pub fn rln_witness_from_values(
identity_secret: IdSecret,
identity_secret: Fr,
merkle_proof: &MerkleProof,
x: Fr,
external_nullifier: Fr,
@@ -271,9 +303,7 @@ pub fn rln_witness_from_values(
pub fn random_rln_witness(tree_height: usize) -> RLNWitnessInput {
let mut rng = thread_rng();
let mut identity_secret_ = hash_to_field(&rng.gen::<[u8; 32]>());
let identity_secret = IdSecret::from(identity_secret_);
identity_secret_.zeroize();
let identity_secret = hash_to_field(&rng.gen::<[u8; 32]>());
let x = hash_to_field(&rng.gen::<[u8; 32]>());
let epoch = hash_to_field(&rng.gen::<[u8; 32]>());
let rln_identifier = hash_to_field(RLN_IDENTIFIER); //hash_to_field(&rng.gen::<[u8; 32]>());
@@ -306,10 +336,9 @@ pub fn proof_values_from_witness(
message_id_range_check(&rln_witness.message_id, &rln_witness.user_message_limit)?;
// y share
let a_0: &Fr = &rln_witness.identity_secret;
let mut a_1 = poseidon_hash(&[*a_0, rln_witness.external_nullifier, rln_witness.message_id]);
let y = *a_0 + rln_witness.x * a_1;
a_1.zeroize();
let a_0 = rln_witness.identity_secret;
let a_1 = poseidon_hash(&[a_0, rln_witness.external_nullifier, rln_witness.message_id]);
let y = a_0 + rln_witness.x * a_1;
// Nullifier
let nullifier = poseidon_hash(&[a_1]);
@@ -380,7 +409,7 @@ pub fn deserialize_proof_values(serialized: &[u8]) -> (RLNProofValues, usize) {
// input_data is [ identity_secret<32> | id_index<8> | user_message_limit<32> | message_id<32> | external_nullifier<32> | signal_len<8> | signal<var> ]
pub fn prepare_prove_input(
identity_secret: IdSecret,
identity_secret: Fr,
id_index: usize,
user_message_limit: Fr,
message_id: Fr,
@@ -424,12 +453,12 @@ pub fn prepare_verify_input(proof_data: Vec<u8>, signal: &[u8]) -> Vec<u8> {
///////////////////////////////////////////////////////
pub fn compute_tree_root(
identity_secret: &IdSecret,
identity_secret: &Fr,
user_message_limit: &Fr,
path_elements: &[Fr],
identity_path_index: &[u8],
) -> Fr {
let id_commitment = poseidon_hash(&[**identity_secret]);
let id_commitment = poseidon_hash(&[*identity_secret]);
let mut root = poseidon_hash(&[id_commitment, *user_message_limit]);
for i in 0..identity_path_index.len() {
@@ -450,11 +479,11 @@ pub fn compute_tree_root(
// Generates a tuple (identity_secret_hash, id_commitment) where
// identity_secret_hash is random and id_commitment = PoseidonHash(identity_secret_hash)
// RNG is instantiated using thread_rng()
pub fn keygen() -> (IdSecret, Fr) {
pub fn keygen() -> (Fr, Fr) {
let mut rng = thread_rng();
let identity_secret_hash = Fr::rand(&mut rng);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(IdSecret::from(identity_secret_hash), id_commitment)
(identity_secret_hash, id_commitment)
}
// Generates a tuple (identity_trapdoor, identity_nullifier, identity_secret_hash, id_commitment) where
@@ -463,14 +492,12 @@ pub fn keygen() -> (IdSecret, Fr) {
// id_commitment = PoseidonHash(identity_secret_hash),
// RNG is instantiated using thread_rng()
// Generated credentials are compatible with Semaphore credentials
pub fn extended_keygen() -> (Fr, Fr, IdSecret, Fr) {
pub fn extended_keygen() -> (Fr, Fr, Fr, Fr) {
let mut rng = thread_rng();
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let mut identity_secret_hash_ = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let identity_secret_hash = IdSecret::from(identity_secret_hash_);
let id_commitment = poseidon_hash(&[identity_secret_hash_]);
identity_secret_hash_.zeroize();
let identity_secret_hash = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(
identity_trapdoor,
identity_nullifier,
@@ -482,7 +509,7 @@ pub fn extended_keygen() -> (Fr, Fr, IdSecret, Fr) {
// Generates a tuple (identity_secret_hash, id_commitment) where
// identity_secret_hash is random and id_commitment = PoseidonHash(identity_secret_hash)
// RNG is instantiated using 20 rounds of ChaCha seeded with the hash of the input
pub fn seeded_keygen(signal: &[u8]) -> (IdSecret, Fr) {
pub fn seeded_keygen(signal: &[u8]) -> (Fr, Fr) {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
@@ -491,11 +518,8 @@ pub fn seeded_keygen(signal: &[u8]) -> (IdSecret, Fr) {
hasher.finalize(&mut seed);
let mut rng = ChaCha20Rng::from_seed(seed);
let mut identity_secret_hash_ = Fr::rand(&mut rng);
let id_commitment = poseidon_hash(&[identity_secret_hash_]);
let identity_secret_hash = IdSecret::from(identity_secret_hash_);
identity_secret_hash_.zeroize();
let identity_secret_hash = Fr::rand(&mut rng);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(identity_secret_hash, id_commitment)
}
@@ -505,7 +529,7 @@ pub fn seeded_keygen(signal: &[u8]) -> (IdSecret, Fr) {
// id_commitment = PoseidonHash(identity_secret_hash),
// RNG is instantiated using 20 rounds of ChaCha seeded with the hash of the input
// Generated credentials are compatible with Semaphore credentials
pub fn extended_seeded_keygen(signal: &[u8]) -> (Fr, Fr, IdSecret, Fr) {
pub fn extended_seeded_keygen(signal: &[u8]) -> (Fr, Fr, Fr, Fr) {
// ChaCha20 requires a seed of exactly 32 bytes.
// We first hash the input seed signal to a 32 bytes array and pass this as seed to ChaCha20
let mut seed = [0; 32];
@@ -516,11 +540,8 @@ pub fn extended_seeded_keygen(signal: &[u8]) -> (Fr, Fr, IdSecret, Fr) {
let mut rng = ChaCha20Rng::from_seed(seed);
let identity_trapdoor = Fr::rand(&mut rng);
let identity_nullifier = Fr::rand(&mut rng);
let mut identity_secret_hash_ = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let id_commitment = poseidon_hash(&[identity_secret_hash_]);
let identity_secret_hash = IdSecret::from(identity_secret_hash_);
identity_secret_hash_.zeroize();
let identity_secret_hash = poseidon_hash(&[identity_trapdoor, identity_nullifier]);
let id_commitment = poseidon_hash(&[identity_secret_hash]);
(
identity_trapdoor,
identity_nullifier,
@@ -529,10 +550,7 @@ pub fn extended_seeded_keygen(signal: &[u8]) -> (Fr, Fr, IdSecret, Fr) {
)
}
pub fn compute_id_secret(
share1: (Fr, Fr),
share2: (Fr, Fr),
) -> Result<IdSecret, ComputeIdSecretError> {
pub fn compute_id_secret(share1: (Fr, Fr), share2: (Fr, Fr)) -> Result<Fr, ComputeIdSecretError> {
// Assuming a0 is the identity secret and a1 = poseidonHash([a0, external_nullifier]),
// a (x,y) share satisfies the following relation
// y = a_0 + x * a_1
@@ -548,7 +566,7 @@ pub fn compute_id_secret(
let a_0 = y1 - x1 * a_1;
// If shares come from the same polynomial, a0 is correctly recovered and a1 = poseidonHash([a0, external_nullifier])
Ok(IdSecret::from(a_0))
Ok(a_0)
} else {
Err(ComputeIdSecretError::DivisionByZero)
}
@@ -638,11 +656,7 @@ pub fn inputs_for_witness_calculation(
.for_each(|v| identity_path_index.push(Fr::from(*v)));
Ok([
// FIXME ?
(
"identitySecret",
vec![rln_witness.identity_secret.clone().into()],
),
("identitySecret", vec![rln_witness.identity_secret]),
("userMessageLimit", vec![rln_witness.user_message_limit]),
("messageId", vec![rln_witness.message_id]),
("pathElements", rln_witness.path_elements.clone()),
@@ -806,10 +820,8 @@ pub fn rln_witness_to_bigint_json(
.iter()
.for_each(|v| identity_path_index.push(BigInt::from(*v).to_str_radix(10)));
let mut identity_secret: Fr = rln_witness.identity_secret.clone().into();
let inputs = serde_json::json!({
"identitySecret": to_bigint(&identity_secret).to_str_radix(10),
"identitySecret": to_bigint(&rln_witness.identity_secret).to_str_radix(10),
"userMessageLimit": to_bigint(&rln_witness.user_message_limit).to_str_radix(10),
"messageId": to_bigint(&rln_witness.message_id).to_str_radix(10),
"pathElements": path_elements,
@@ -818,8 +830,6 @@ pub fn rln_witness_to_bigint_json(
"externalNullifier": to_bigint(&rln_witness.external_nullifier).to_str_radix(10),
});
identity_secret.zeroize();
Ok(inputs)
}

View File

@@ -7,8 +7,8 @@ use crate::protocol::{
serialize_proof_values, serialize_witness, verify_proof,
};
use crate::utils::{
bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, fr_byte_size, fr_to_bytes_le,
vec_fr_to_bytes_le, vec_u8_to_bytes_le,
bytes_be_to_vec_fr, bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, fr_byte_size,
fr_to_bytes_be, fr_to_bytes_le, vec_fr_to_bytes_le, vec_u8_to_bytes_le,
};
#[cfg(not(target_arch = "wasm32"))]
use {
@@ -37,7 +37,6 @@ use ark_serialize::{CanonicalDeserialize, CanonicalSerialize, Read, Write};
use num_bigint::BigInt;
use std::io::Cursor;
use utils::error::ZerokitMerkleTreeError;
use zeroize::Zeroize;
/// The application-specific RLN identifier.
///
@@ -1134,14 +1133,21 @@ impl RLN {
/// ```
pub fn key_gen<W: Write>(&self, mut output_data: W) -> Result<(), RLNError> {
let (identity_secret_hash, id_commitment) = keygen();
let mut identity_secret_hash_: Fr = identity_secret_hash.into();
output_data.write_all(&fr_to_bytes_le(&identity_secret_hash_))?;
identity_secret_hash_.zeroize();
output_data.write_all(&fr_to_bytes_le(&identity_secret_hash))?;
output_data.write_all(&fr_to_bytes_le(&id_commitment))?;
Ok(())
}
/// Same as key_gen but serialized in BE format
pub fn key_gen_be<W: Write>(&self, mut output_data: W) -> Result<(), RLNError> {
let (identity_secret_hash, id_commitment) = keygen();
output_data.write_all(&fr_to_bytes_be(&identity_secret_hash))?;
output_data.write_all(&fr_to_bytes_be(&id_commitment))?;
Ok(())
}
/// Returns an identity trapdoor, nullifier, secret and commitment tuple.
///
/// The identity secret is the Poseidon hash of the identity trapdoor and identity nullifier.
@@ -1175,6 +1181,18 @@ impl RLN {
Ok(())
}
/// Same as extend_key_gen but serialized in BE format.
pub fn extended_key_gen_be<W: Write>(&self, mut output_data: W) -> Result<(), RLNError> {
let (identity_trapdoor, identity_nullifier, identity_secret_hash, id_commitment) =
extended_keygen();
output_data.write_all(&fr_to_bytes_be(&identity_trapdoor))?;
output_data.write_all(&fr_to_bytes_be(&identity_nullifier))?;
output_data.write_all(&fr_to_bytes_be(&identity_secret_hash))?;
output_data.write_all(&fr_to_bytes_be(&id_commitment))?;
Ok(())
}
/// Returns an identity secret and identity commitment pair generated using a seed.
///
/// The identity commitment is the Poseidon hash of the identity secret.
@@ -1214,6 +1232,22 @@ impl RLN {
Ok(())
}
/// Same as seeded_key_gen but in BE format
pub fn seeded_key_gen_be<R: Read, W: Write>(
&self,
mut input_data: R,
mut output_data: W,
) -> Result<(), RLNError> {
let mut serialized: Vec<u8> = Vec::new();
input_data.read_to_end(&mut serialized)?;
let (identity_secret_hash, id_commitment) = seeded_keygen(&serialized);
output_data.write_all(&fr_to_bytes_be(&identity_secret_hash))?;
output_data.write_all(&fr_to_bytes_be(&id_commitment))?;
Ok(())
}
/// Returns an identity trapdoor, nullifier, secret and commitment tuple generated using a seed.
///
/// The identity secret is the Poseidon hash of the identity trapdoor and identity nullifier.
@@ -1260,6 +1294,25 @@ impl RLN {
Ok(())
}
/// same as seeded_extended_key_gen but in BE format
pub fn seeded_extended_key_gen_be<R: Read, W: Write>(
&self,
mut input_data: R,
mut output_data: W,
) -> Result<(), RLNError> {
let mut serialized: Vec<u8> = Vec::new();
input_data.read_to_end(&mut serialized)?;
let (identity_trapdoor, identity_nullifier, identity_secret_hash, id_commitment) =
extended_seeded_keygen(&serialized);
output_data.write_all(&fr_to_bytes_be(&identity_trapdoor))?;
output_data.write_all(&fr_to_bytes_be(&identity_nullifier))?;
output_data.write_all(&fr_to_bytes_be(&identity_secret_hash))?;
output_data.write_all(&fr_to_bytes_be(&id_commitment))?;
Ok(())
}
/// Recovers the identity secret from two set of proof values computed for same secret in same epoch with same rln identifier.
///
/// Input values are:
@@ -1327,7 +1380,7 @@ impl RLN {
compute_id_secret(share1, share2).map_err(RLNError::RecoverSecret)?;
// If an identity secret hash is recovered, we write it to output_data, otherwise nothing will be written.
output_data.write_all(&fr_to_bytes_le(&recovered_identity_secret_hash.into()))?;
output_data.write_all(&fr_to_bytes_le(&recovered_identity_secret_hash))?;
}
Ok(())
@@ -1440,6 +1493,20 @@ pub fn hash<R: Read, W: Write>(
Ok(())
}
/// same as hash function but in BE format
pub fn hash_be<R: Read, W: Write>(
mut input_data: R,
mut output_data: W,
) -> Result<(), std::io::Error> {
let mut serialized: Vec<u8> = Vec::new();
input_data.read_to_end(&mut serialized)?;
let hash = hash_to_field(&serialized);
output_data.write_all(&fr_to_bytes_be(&hash))?;
Ok(())
}
/// Hashes a set of elements to a single element in the working prime field, using Poseidon.
///
/// The result is computed as the Poseidon Hash of the input signal.
@@ -1476,3 +1543,18 @@ pub fn poseidon_hash<R: Read, W: Write>(
Ok(())
}
/// same as poseidon_hash function but in BE format. Note that input is expected in BE format too.
pub fn poseidon_hash_be<R: Read, W: Write>(
mut input_data: R,
mut output_data: W,
) -> Result<(), RLNError> {
let mut serialized: Vec<u8> = Vec::new();
input_data.read_to_end(&mut serialized)?;
let (inputs, _) = bytes_be_to_vec_fr(&serialized)?;
let hash = utils_poseidon_hash(inputs.as_ref());
output_data.write_all(&fr_to_bytes_be(&hash))?;
Ok(())
}

View File

@@ -880,7 +880,7 @@ mod tree_test {
// We prepare input for generate_rln_proof API
// input_data is [ identity_secret<32> | id_index<8> | user_message_limit<32> | message_id<32> | external_nullifier<32> | signal_len<8> | signal<var> ]
let prove_input1 = prepare_prove_input(
identity_secret_hash.clone(),
identity_secret_hash,
identity_index,
user_message_limit,
message_id,
@@ -889,7 +889,7 @@ mod tree_test {
);
let prove_input2 = prepare_prove_input(
identity_secret_hash.clone(),
identity_secret_hash,
identity_index,
user_message_limit,
message_id,
@@ -932,10 +932,7 @@ mod tree_test {
// We check if the recovered identity secret hash corresponds to the original one
let (recovered_identity_secret_hash, _) = bytes_le_to_fr(&serialized_identity_secret_hash);
assert_eq!(
recovered_identity_secret_hash,
identity_secret_hash.clone().into()
);
assert_eq!(recovered_identity_secret_hash, identity_secret_hash);
// We now test that computing identity_secret_hash is unsuccessful if shares computed from two different identity secret hashes but within same epoch are passed
@@ -985,10 +982,7 @@ mod tree_test {
// ensure that the recovered secret does not match with either of the
// used secrets in proof generation
assert_ne!(
recovered_identity_secret_hash_new,
identity_secret_hash_new.into()
);
assert_ne!(recovered_identity_secret_hash_new, identity_secret_hash_new);
}
}

View File

@@ -3,16 +3,10 @@
use crate::circuit::Fr;
use crate::error::ConversionError;
use ark_ff::PrimeField;
use ark_serialize::{
CanonicalDeserialize, CanonicalSerialize, Compress, SerializationError, Valid, Validate,
};
use derive_more::{Display, From, Into};
use num_bigint::{BigInt, BigUint};
use num_traits::Num;
use serde_json::json;
use std::io::{Cursor, Read, Write};
use std::ops::Deref;
use zeroize::{Zeroize, ZeroizeOnDrop};
use std::io::Cursor;
#[inline(always)]
pub fn to_bigint(el: &Fr) -> BigInt {
@@ -20,7 +14,7 @@ pub fn to_bigint(el: &Fr) -> BigInt {
}
#[inline(always)]
pub fn fr_byte_size() -> usize {
pub const fn fr_byte_size() -> usize {
let mbs = <Fr as PrimeField>::MODULUS_BIT_SIZE;
((mbs + 64 - (mbs % 64)) / 8) as usize
}
@@ -53,6 +47,15 @@ pub fn bytes_le_to_fr(input: &[u8]) -> (Fr, usize) {
)
}
#[inline(always)]
pub fn bytes_be_to_fr(input: &[u8]) -> (Fr, usize) {
let el_size = fr_byte_size();
(
Fr::from(BigUint::from_bytes_be(&input[0..el_size])),
el_size,
)
}
#[inline(always)]
pub fn fr_to_bytes_le(input: &Fr) -> Vec<u8> {
let input_biguint: BigUint = (*input).into();
@@ -62,6 +65,19 @@ pub fn fr_to_bytes_le(input: &Fr) -> Vec<u8> {
res
}
#[inline(always)]
pub fn fr_to_bytes_be(input: &Fr) -> Vec<u8> {
let input_biguint: BigUint = (*input).into();
let mut res = input_biguint.to_bytes_be();
// For BE, insert 0 at the start of the Vec (see also fr_to_bytes_le comments)
let to_insert_count = fr_byte_size().saturating_sub(res.len());
if to_insert_count > 0 {
// Insert multi 0 at index 0
res.splice(0..0, std::iter::repeat_n(0, to_insert_count));
}
res
}
#[inline(always)]
pub fn vec_fr_to_bytes_le(input: &[Fr]) -> Vec<u8> {
// Calculate capacity for Vec:
@@ -112,10 +128,9 @@ pub fn bytes_le_to_vec_u8(input: &[u8]) -> Result<(Vec<u8>, usize), ConversionEr
#[inline(always)]
pub fn bytes_le_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionError> {
let mut read: usize = 0;
let mut res: Vec<Fr> = Vec::new();
let len = usize::try_from(u64::from_le_bytes(input[0..8].try_into()?))?;
read += 8;
let mut res: Vec<Fr> = Vec::with_capacity(len);
let el_size = fr_byte_size();
for i in 0..len {
@@ -127,6 +142,24 @@ pub fn bytes_le_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionEr
Ok((res, read))
}
#[inline(always)]
pub fn bytes_be_to_vec_fr(input: &[u8]) -> Result<(Vec<Fr>, usize), ConversionError> {
let mut read: usize = 0;
let mut res: Vec<Fr> = Vec::new();
let len = usize::try_from(u64::from_be_bytes(input[0..8].try_into()?))?;
read += 8;
let el_size = fr_byte_size();
for i in 0..len {
let (curr_el, _) = bytes_be_to_fr(&input[8 + el_size * i..8 + el_size * (i + 1)]);
res.push(curr_el);
read += el_size;
}
Ok((res, read))
}
#[inline(always)]
pub fn bytes_le_to_vec_usize(input: &[u8]) -> Result<Vec<usize>, ConversionError> {
let nof_elem = usize::try_from(u64::from_le_bytes(input[0..8].try_into()?))?;
@@ -157,43 +190,16 @@ pub fn generate_input_buffer() -> Cursor<String> {
Cursor::new(json!({}).to_string())
}
#[derive(Debug, Zeroize, ZeroizeOnDrop, From, Into, Clone, PartialEq, Display)]
pub struct IdSecret(ark_bn254::Fr);
#[cfg(test)]
mod test {
use super::*;
impl Deref for IdSecret {
type Target = Fr;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl CanonicalSerialize for IdSecret {
fn serialize_with_mode<W: Write>(
&self,
writer: W,
compress: Compress,
) -> Result<(), SerializationError> {
todo!()
}
fn serialized_size(&self, compress: Compress) -> usize {
todo!()
}
}
impl Valid for IdSecret {
fn check(&self) -> Result<(), SerializationError> {
self.0.check()
}
}
impl CanonicalDeserialize for IdSecret {
fn deserialize_with_mode<R: Read>(
reader: R,
compress: Compress,
validate: Validate,
) -> Result<Self, SerializationError> {
todo!()
#[test]
fn test_fr_be() {
let fr_1 = Fr::from(255);
let b = fr_to_bytes_be(&fr_1);
let fr_1_de = bytes_be_to_fr(&b).0;
assert_eq!(fr_1, fr_1_de);
}
}

View File

@@ -49,16 +49,15 @@ mod test {
root
}
fn identity_pair_gen(rln_pointer: &mut RLN) -> (IdSecret, Fr) {
fn identity_pair_gen(rln_pointer: &mut RLN) -> (Fr, Fr) {
let mut output_buffer = MaybeUninit::<Buffer>::uninit();
let success = key_gen(rln_pointer, output_buffer.as_mut_ptr());
assert!(success, "key gen call failed");
let output_buffer = unsafe { output_buffer.assume_init() };
let result_data = <&[u8]>::from(&output_buffer).to_vec();
// FIXME: zeroize?
let (identity_secret_hash, read) = bytes_le_to_fr(&result_data);
let (id_commitment, _) = bytes_le_to_fr(&result_data[read..].to_vec());
(IdSecret::from(identity_secret_hash), id_commitment)
(identity_secret_hash, id_commitment)
}
fn rln_proof_gen(rln_pointer: &mut RLN, serialized: &[u8]) -> Vec<u8> {
@@ -274,7 +273,6 @@ mod test {
// generate identity
let identity_secret_hash = hash_to_field(b"test-merkle-proof");
let id_commitment = utils_poseidon_hash(&[identity_secret_hash]);
let identity_secret_hash = IdSecret::from(identity_secret_hash);
let user_message_limit = Fr::from(100);
let rate_commitment = utils_poseidon_hash(&[id_commitment, user_message_limit]);
@@ -676,7 +674,7 @@ mod test {
// We prepare input for generate_rln_proof API
// input_data is [ identity_secret<32> | id_index<8> | user_message_limit<32> | message_id<32> | external_nullifier<32> | signal_len<8> | signal<var> ]
let prove_input1 = prepare_prove_input(
identity_secret_hash.clone(),
identity_secret_hash,
identity_index,
user_message_limit,
message_id,
@@ -685,7 +683,7 @@ mod test {
);
let prove_input2 = prepare_prove_input(
identity_secret_hash.clone(),
identity_secret_hash,
identity_index,
user_message_limit,
message_id,
@@ -720,10 +718,7 @@ mod test {
// We check if the recovered identity secret hash corresponds to the original one
let (recovered_identity_secret_hash, _) = bytes_le_to_fr(&serialized_identity_secret_hash);
assert_eq!(
recovered_identity_secret_hash,
identity_secret_hash.clone().into()
);
assert_eq!(recovered_identity_secret_hash, identity_secret_hash);
// We now test that computing identity_secret_hash is unsuccessful if shares computed from two different identity secret hashes but within same epoch are passed
@@ -746,7 +741,7 @@ mod test {
// input_data is [ identity_secret<32> | id_index<8> | epoch<32> | signal_len<8> | signal<var> ]
// Note that epoch is the same as before
let prove_input3 = prepare_prove_input(
identity_secret_hash.clone(),
identity_secret_hash,
identity_index_new,
user_message_limit,
message_id,
@@ -777,10 +772,7 @@ mod test {
// ensure that the recovered secret does not match with either of the
// used secrets in proof generation
assert_ne!(
recovered_identity_secret_hash_new,
identity_secret_hash_new.into()
);
assert_ne!(recovered_identity_secret_hash_new, identity_secret_hash_new);
}
#[test]

View File

@@ -10,7 +10,7 @@ mod test {
use rand::Rng;
use rln::circuit::Fr;
use rln::hashers::{hash_to_field, poseidon_hash as utils_poseidon_hash, ROUND_PARAMS};
use rln::protocol::{deserialize_identity_tuple, IdSecret};
use rln::protocol::deserialize_identity_tuple;
use rln::public::{hash as public_hash, poseidon_hash as public_poseidon_hash, RLN};
use rln::utils::{
bytes_le_to_fr, bytes_le_to_vec_fr, bytes_le_to_vec_u8, bytes_le_to_vec_usize,
@@ -30,7 +30,6 @@ mod test {
// generate identity
let identity_secret_hash = hash_to_field(b"test-merkle-proof");
let id_commitment = utils_poseidon_hash(&vec![identity_secret_hash]);
let identity_secret_hash = IdSecret::from(identity_secret_hash);
let rate_commitment = utils_poseidon_hash(&[id_commitment, user_message_limit.into()]);
// check that leaves indices is empty