Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix fuzz 1 failure: incorrect reduction of BigInt #246

Merged
merged 1 commit into from
Jul 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion constantine/math/arithmetic/limbs_montgomery.nim
Original file line number Diff line number Diff line change
Expand Up @@ -609,7 +609,13 @@ func getMont*(r: var Limbs, a, M, r2modM: Limbs,
## Important: `r` is overwritten
## The result `r` buffer size MUST be at least the size of `M` buffer
# Reference: https://eprint.iacr.org/2017/1057.pdf
mulMont(r, a, r2ModM, M, m0ninv, spareBits)

# For conversion to a field element (in the Montgomery domain), we do not use the "no-carry" optimization:
# While Montgomery Reduction can map inputs [0, 4p²) -> [0, p)
# that range is not valid with the no-carry optimization,
# hence an unreduced input that uses 256-bit while prime is 254-bit
# can have an incorrect representation.
mulMont_FIPS(r, a, r2ModM, M, m0ninv, skipFinalSub = false)

# Montgomery Modular Exponentiation
# ------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ func powOddMod_vartime*(
# if we use redc2xMont (a/R) and montgomery multiplication by R³
# For now, we call explicit reduction as it can handle all sizes.
# TODO: explicit reduction uses constant-time division which is **very** expensive
# TODO: fix https://github.com/mratsim/constantine/issues/241
if a.len != M.len:
let t = allocStackArray(SecretWord, L)
t.LimbsViewMut.reduce(a.view(), aBits, M.view(), mBits)
Expand Down
10 changes: 10 additions & 0 deletions tests/math_fields/t_io_fields.nim
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,14 @@ proc main() =

check: p == hex

test "Fuzz #1 - incorrect reduction of BigInt":
block:
var a{.noInit.}: Fp[BN254_Snarks]
a.fromBig(BigInt[254].fromHex("0xdd1119d0c5b065898a0848e21c209153f4622f06cb763e7ef00eef28b94780f8"))

var b{.noInit.}: Fp[BN254_Snarks]
b.fromBig(BigInt[254].fromHex("0x1b7fe00540e9e4e2a8c73208161b2fdd965c84c129af1449ff8cbecd57538bdc"))

doAssert bool(a == b)

main()