Skip to content

Commit

Permalink
Fix Felt::from_bytes_be + add proptest (#756)
Browse files Browse the repository at this point in the history
* Fix Felt::from_bytes_be + add proptest

* Clippy

* Apply suggested changes
  • Loading branch information
fmoletta authored Jan 25, 2023
1 parent 65c20b6 commit 3fb2bdc
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions felt/proptest-regressions/lib.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@
# It is recommended to check this file in to source control so that
# everyone who runs the test benefits from these saved cases.
cc 1bf12114a6bfc70e8f949318158595883c33bc6fb35862852bc5144547ac3557 # shrinks to ref x = "0"
cc 3a938be1bdfbb188c7c1f0dc097d8089fe8b26a98b76c013014651353d2926d0 # shrinks to ref x = "10000000000000000000000000000000"
6 changes: 5 additions & 1 deletion felt/src/bigint_felt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,11 @@ impl FeltOps for FeltBigInt<FIELD_HIGH, FIELD_LOW> {
}

fn from_bytes_be(bytes: &[u8]) -> FeltBigInt<FIELD_HIGH, FIELD_LOW> {
FeltBigInt::<FIELD_HIGH, FIELD_LOW>::new(BigUint::from_bytes_be(bytes))
let mut value = BigUint::from_bytes_be(bytes);
if value >= *CAIRO_PRIME {
value = value.mod_floor(&CAIRO_PRIME);
}
Self::from(value)
}

fn to_str_radix(&self, radix: u32) -> String {
Expand Down
10 changes: 10 additions & 0 deletions felt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -788,6 +788,16 @@ mod test {
let p = &BigUint::parse_bytes(PRIME_STR[2..].as_bytes(), 16).unwrap();
prop_assert!(&x.to_biguint() < p);
}

#[test]
// Property-based test that ensures, for 100 felt values that are randomly generated each time tests are run, that a felt created using Felt::from_bytes_be doesn't fall outside the range [0, p].
// In this and some of the following tests, The value of {x} can be either [0] or a very large number, in order to try to overflow the value of {p} and thus ensure the modular arithmetic is working correctly.
fn from_bytes_be_in_range(ref x in "(0|[1-9][0-9]*)") {
let x = &Felt::from_bytes_be(x.as_bytes());
let max_felt = &Felt::max_value();
prop_assert!(x <= max_felt);
}

#[test]
// Property-based test that ensures, for 100 felt values that are randomly generated each time tests are run, that the negative of a felt doesn't fall outside the range [0, p].
fn neg_in_range(ref x in "(0|[1-9][0-9]*)") {
Expand Down

0 comments on commit 3fb2bdc

Please sign in to comment.