Skip to content

Commit d0f4ad8

Browse files
authored
Fix fuzz #1 failure: incorrect reduction of BigInt (#246)
1 parent 72f3653 commit d0f4ad8

File tree

3 files changed

+17
-2
lines changed

3 files changed

+17
-2
lines changed

constantine/math/arithmetic/limbs_montgomery.nim

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -609,7 +609,13 @@ func getMont*(r: var Limbs, a, M, r2modM: Limbs,
609609
## Important: `r` is overwritten
610610
## The result `r` buffer size MUST be at least the size of `M` buffer
611611
# Reference: https://eprint.iacr.org/2017/1057.pdf
612-
mulMont(r, a, r2ModM, M, m0ninv, spareBits)
612+
613+
# For conversion to a field element (in the Montgomery domain), we do not use the "no-carry" optimization:
614+
# While Montgomery Reduction can map inputs [0, 4p²) -> [0, p)
615+
# that range is not valid with the no-carry optimization,
616+
# hence an unreduced input that uses 256-bit while prime is 254-bit
617+
# can have an incorrect representation.
618+
mulMont_FIPS(r, a, r2ModM, M, m0ninv, skipFinalSub = false)
613619

614620
# Montgomery Modular Exponentiation
615621
# ------------------------------------------

constantine/math_arbitrary_precision/arithmetic/bigints_views.nim

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,6 @@ func powOddMod_vartime*(
7070
# if we use redc2xMont (a/R) and montgomery multiplication by R³
7171
# For now, we call explicit reduction as it can handle all sizes.
7272
# TODO: explicit reduction uses constant-time division which is **very** expensive
73-
# TODO: fix https://github.com/mratsim/constantine/issues/241
7473
if a.len != M.len:
7574
let t = allocStackArray(SecretWord, L)
7675
t.LimbsViewMut.reduce(a.view(), aBits, M.view(), mBits)

tests/math_fields/t_io_fields.nim

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,4 +156,14 @@ proc main() =
156156

157157
check: p == hex
158158

159+
test "Fuzz #1 - incorrect reduction of BigInt":
160+
block:
161+
var a{.noInit.}: Fp[BN254_Snarks]
162+
a.fromBig(BigInt[254].fromHex("0xdd1119d0c5b065898a0848e21c209153f4622f06cb763e7ef00eef28b94780f8"))
163+
164+
var b{.noInit.}: Fp[BN254_Snarks]
165+
b.fromBig(BigInt[254].fromHex("0x1b7fe00540e9e4e2a8c73208161b2fdd965c84c129af1449ff8cbecd57538bdc"))
166+
167+
doAssert bool(a == b)
168+
159169
main()

0 commit comments

Comments
 (0)