From 6db719b65ab9081dd2cf17010d3f296422083b5f Mon Sep 17 00:00:00 2001 From: sifnoc Date: Mon, 19 Aug 2024 09:04:47 +0000 Subject: [PATCH] feat: checking maximum value of converted username --- prover/src/entry.rs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/prover/src/entry.rs b/prover/src/entry.rs index daaef76c..e9810b7d 100644 --- a/prover/src/entry.rs +++ b/prover/src/entry.rs @@ -1,6 +1,7 @@ +use halo2_proofs::halo2curves::bn256::Fr as Fp; use num_bigint::BigUint; -use crate::utils::big_intify_username; +use crate::utils::{big_intify_username, fp_to_big_uint}; /// An entry in the Merkle Sum Tree from the database of the CEX. /// It contains the username and the balances of the user. @@ -13,8 +14,19 @@ pub struct Entry { impl Entry { pub fn new(username: String, balances: [BigUint; N_CURRENCIES]) -> Result { + let username_as_big_uint = big_intify_username(&username); + let max_allowed_value = fp_to_big_uint(Fp::zero() - Fp::one()); + + // Ensure the username, when converted to a BigUint, does not exceed the field modulus + // This prevents potential overflow issues by asserting that the username's numeric value + // is within the allowable range defined by the field modulus + // Please refer to https://github.com/zBlock-2/audit-report/blob/main/versionB.md#4-high-missing-username-range-check-in-big_intify_username--big_uint_to_fp + if username_as_big_uint > max_allowed_value { + return Err("The value that converted username should not exceed field modulus"); + } + Ok(Entry { - username_as_big_uint: big_intify_username(&username), + username_as_big_uint, balances, username, }) @@ -42,3 +54,16 @@ impl Entry { &self.username } } + +#[cfg(test)] +#[test] +fn test_entry_new() { + let short_username_entry = Entry::new(String::from("userA"), [BigUint::from(0u32)]); + assert!(short_username_entry.is_ok()); + + let long_username_entry = Entry::new( + String::from("userABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"), + [BigUint::from(0u32)], + ); + assert!(long_username_entry.is_err()) +}