Fix fuzz #1 failure: incorrect reduction of BigInt (#246)

This commit is contained in:
Mamy Ratsimbazafy 2023-07-02 17:15:02 +02:00 committed by GitHub
parent 72f36530ba
commit d0f4ad8cda
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 2 deletions

View File

@ -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
# ------------------------------------------

View File

@ -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)

View File

@ -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()