Skip to content

Commit

Permalink
chore: Add hash_to_field Noir alternative (#3338)
Browse files Browse the repository at this point in the history
  • Loading branch information
kevaundray authored Oct 30, 2023
1 parent 122119b commit 93d41e1
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
17 changes: 17 additions & 0 deletions noir_stdlib/src/field.nr
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,20 @@ pub fn modulus_be_bytes() -> [u8] {}

#[builtin(modulus_le_bytes)]
pub fn modulus_le_bytes() -> [u8] {}

// Convert a 32 byte array to a field element
pub fn bytes32_to_field(bytes32 : [u8; 32]) -> Field {
// Convert it to a field element
let mut v = 1;
let mut high = 0 as Field;
let mut low = 0 as Field;

for i in 0..16 {
high = high + (bytes32[15 - i] as Field) * v;
low = low + (bytes32[16 + 15 - i] as Field) * v;
v = v * 256;
}

// Abuse that a % p + b % p = (a + b) % p and that low < p
low + high * v
}
15 changes: 13 additions & 2 deletions noir_stdlib/src/hash.nr
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,19 @@ pub fn pedersen_hash<N>(input : [Field; N]) -> Field {
#[foreign(pedersen_hash)]
pub fn pedersen_hash_with_separator<N>(_input : [Field; N], _separator : u32) -> Field {}

#[foreign(hash_to_field_128_security)]
pub fn hash_to_field<N>(_input : [Field; N]) -> Field {}
pub fn hash_to_field<N>(_input : [Field; N]) -> Field {
let mut inputs_as_bytes = [];

for i in 0..N {
let input_bytes = _input[i].to_le_bytes(32);
for i in 0..32 {
inputs_as_bytes = inputs_as_bytes.push_back(input_bytes[i]);
}
}

let hashed_input = blake2s(inputs_as_bytes);
crate::field::bytes32_to_field(hashed_input)
}

#[foreign(keccak256)]
pub fn keccak256<N>(_input : [u8; N], _message_size: u32) -> [u8; 32] {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ use dep::std;

fn main(input : Field) -> pub Field {
std::hash::hash_to_field([input])
}
}

0 comments on commit 93d41e1

Please sign in to comment.