Skip to content

Commit

Permalink
Fix fuzz #1 failure: incorrect reduction of BigInt (#246)
Browse files Browse the repository at this point in the history
  • Loading branch information
mratsim authored Jul 2, 2023
1 parent 72f3653 commit d0f4ad8
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
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()

0 comments on commit d0f4ad8

Please sign in to comment.