Fix squaring in 𝔽p12, mul in 𝔽p6 MUST NOT share buffer (i.e. broken value semantics)

This commit is contained in:
Mamy André-Ratsimbazafy 2020-04-09 02:00:45 +02:00
parent 8c478df0c1
commit f24d87fb00
No known key found for this signature in database
GPG Key ID: 7B88AD1FE79492E1
3 changed files with 40 additions and 29 deletions

View File

@ -59,6 +59,7 @@ func `*`(_: typedesc[Gamma], a: Fp6): Fp6 {.noInit, inline.} =
## Conveniently γ = v with v the factor in for 𝔽p6 coordinate
## and v³ = ξ
## (c0 + c1 v + c2 v²) v => ξ c2 + c0 v + c1 v²
discard
result.c0 = a.c2 * Xi
result.c1 = a.c0
@ -70,7 +71,7 @@ template `*`(a: Fp6, _: typedesc[Gamma]): Fp6 =
func `*=`(a: var Fp6, _: typedesc[Gamma]) {.inline.} =
a = Gamma * a
func square*(r: var Fp12, a: Fp12) =
func square*[C](r: var Fp12[C], a: Fp12[C]) =
## Return a² in ``r``
## ``r`` is initialized/overwritten
# (c0, c1)² => (c0 + c1 w)²
@ -91,17 +92,17 @@ func square*(r: var Fp12, a: Fp12) =
# Alternative 2:
# c0² + γ c1² <=> (c0 + c1)(c0 + γ c1) - γ c0c1 - c0c1
# r0 <- (c0 - c1)(c0 - γ c1)
r.c0.diff(a.c0, a.c1)
r.c1.diff(a.c0, Gamma * a.c1)
r.c0.prod(r.c0, r.c1)
# r0 <- (c0 + c1)(c0 + γ c1)
r.c0.sum(a.c0, a.c1)
r.c1.sum(a.c0, Gamma * a.c1)
r.c0 *= r.c1
# r1 <- c0 c1
r.c1.prod(a.c0, a.c1)
# r0 = (c0 - c1)(c0 - γ c1) + γ c0c1 + c0c1
r.c0 += Gamma * r.c1
r.c0 += r.c1
# r0 = (c0 + c1)(c0 + γ c1) - γ c0c1 - c0c1
r.c0 -= Gamma * r.c1
r.c0 -= r.c1
# r1 = 2 c0c1
r.c1.double()

View File

@ -90,6 +90,8 @@ func square*[C](r: var Fp6[C], a: Fp6[C]) =
func prod*[C](r: var Fp6[C], a, b: Fp6[C]) =
## Returns r = a * b
##
## r MUST not share a buffer with a
# Algorithm is Karatsuba
var v0{.noInit.}, v1{.noInit.}, v2{.noInit.}, t{.noInit.}: Fp2[C]
@ -174,3 +176,11 @@ func inv*[C](r: var Fp6[C], a: Fp6[C]) =
r.c0 *= v3
r.c1.prod(v1, v3)
r.c2.prod(v2, v3)
func `*=`*(a: var Fp6, b: Fp6) {.inline.} =
var t: Fp6
t.prod(a, b)
a = t
func `*`*(a, b: Fp6): Fp6 {.inline.} =
result.prod(a, b)

View File

@ -86,13 +86,13 @@ suite "𝔽p12 = 𝔽p6[√∛(1+𝑖)]":
testInstance()
# test(BN254)
# test(BLS12_377)
# test(BLS12_381)
# test(BN446)
# test(FKM12_447)
# test(BLS12_461)
# test(BN462)
test(BN254)
test(BLS12_377)
test(BLS12_381)
test(BN446)
test(FKM12_447)
test(BLS12_461)
test(BN462)
test "Squaring 3 returns 9":
template test(C: static Curve) =
@ -124,13 +124,13 @@ suite "𝔽p12 = 𝔽p6[√∛(1+𝑖)]":
testInstance()
# test(BN254)
# test(BLS12_377)
# test(BLS12_381)
# test(BN446)
# test(FKM12_447)
# test(BLS12_461)
# test(BN462)
test(BN254)
test(BLS12_377)
test(BLS12_381)
test(BN446)
test(FKM12_447)
test(BLS12_461)
test(BN462)
test "Squaring -3 returns 9":
template test(C: static Curve) =
@ -162,10 +162,10 @@ suite "𝔽p12 = 𝔽p6[√∛(1+𝑖)]":
testInstance()
# test(BN254)
# test(BLS12_377)
# test(BLS12_381)
# test(BN446)
# test(FKM12_447)
# test(BLS12_461)
# test(BN462)
test(BN254)
test(BLS12_377)
test(BLS12_381)
test(BN446)
test(FKM12_447)
test(BLS12_461)
test(BN462)