Skip to content

Commit

Permalink
test: Add more tests for light_utils main module
Browse files Browse the repository at this point in the history
Achieve full coverage there.
  • Loading branch information
vadorovsky committed Jun 21, 2024
1 parent 269730b commit 0cf0ec3
Showing 1 changed file with 23 additions and 6 deletions.
29 changes: 23 additions & 6 deletions utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,12 @@ impl From<UtilsError> for solana_program::program_error::ProgramError {
}
}

pub fn is_smaller_than_bn254_field_size_be(bytes: &[u8; 32]) -> Result<bool, UtilsError> {
pub fn is_smaller_than_bn254_field_size_be(bytes: &[u8; 32]) -> bool {
let bigint = BigUint::from_bytes_be(bytes);
if bigint < ark_bn254::Fr::MODULUS.into() {
Ok(true)
true
} else {
Ok(false)
false
}
}

Expand All @@ -67,7 +67,7 @@ pub fn hash_to_bn254_field_size_be(bytes: &[u8]) -> Option<([u8; 32], u8)> {
// Truncates to 31 bytes so that value is less than bn254 Fr modulo
// field size.
hashed_value[0] = 0;
if let Ok(true) = is_smaller_than_bn254_field_size_be(&hashed_value) {
if is_smaller_than_bn254_field_size_be(&hashed_value) {
return Some((hashed_value, bump_seed[0]));
}
}
Expand Down Expand Up @@ -109,11 +109,28 @@ pub fn rustfmt(code: String) -> Result<Vec<u8>, anyhow::Error> {

#[cfg(test)]
mod tests {

use num_bigint::ToBigUint;
use solana_program::pubkey::Pubkey;

use crate::bigint::bigint_to_be_bytes_array;

use super::*;

#[test]
fn test_is_smaller_than_bn254_field_size_be() {
let modulus: BigUint = ark_bn254::Fr::MODULUS.into();
let modulus_bytes: [u8; 32] = bigint_to_be_bytes_array(&modulus).unwrap();
assert!(!is_smaller_than_bn254_field_size_be(&modulus_bytes));

let bigint = modulus.clone() - 1.to_biguint().unwrap();
let bigint_bytes: [u8; 32] = bigint_to_be_bytes_array(&bigint).unwrap();
assert!(is_smaller_than_bn254_field_size_be(&bigint_bytes));

let bigint = modulus + 1.to_biguint().unwrap();
let bigint_bytes: [u8; 32] = bigint_to_be_bytes_array(&bigint).unwrap();
assert!(!is_smaller_than_bn254_field_size_be(&bigint_bytes));
}

#[test]
fn test_hash_to_bn254_field_size_be() {
for _ in 0..10_000 {
Expand All @@ -122,7 +139,7 @@ mod tests {
.expect("Failed to find a hash within BN254 field size");
assert_eq!(bump, 255, "Bump seed should be 0");
assert!(
is_smaller_than_bn254_field_size_be(&hashed_value).unwrap(),
is_smaller_than_bn254_field_size_be(&hashed_value),
"Hashed value should be within BN254 field size"
);
}
Expand Down

0 comments on commit 0cf0ec3

Please sign in to comment.