Skip to content

Commit

Permalink
sm9/bn256: fix twist Frobenius bug due to #144, will further review t…
Browse files Browse the repository at this point in the history
…hose functions usage
  • Loading branch information
emmansun authored Jul 21, 2023
1 parent 16b2a43 commit 5b5b26c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
23 changes: 23 additions & 0 deletions sm9/bn256/twist.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,29 @@ func (c *twistPoint) MakeAffine() {
c.t.SetOne()
}

// MakeAffine reverses the Jacobian transform.
// the Jacobian coordinates are (x1, y1, z1)
// where x = x1/z1² and y = y1/z1³.
func (c *twistPoint) AffineFromJacobian() {
if c.z.IsOne() {
return
} else if c.z.IsZero() {
c.x.SetZero()
c.y.SetOne()
c.t.SetZero()
return
}

zInv := (&gfP2{}).Invert(&c.z)
t := (&gfP2{}).Mul(&c.y, zInv)
zInv2 := (&gfP2{}).Square(zInv)
c.y.Mul(t, zInv2)
t.Mul(&c.x, zInv2)
c.x.Set(t)
c.z.SetOne()
c.t.SetOne()
}

func (c *twistPoint) Neg(a *twistPoint) {
c.x.Set(&a.x)
c.y.Neg(&a.y)
Expand Down
9 changes: 6 additions & 3 deletions sm9/bn256/twist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func TestAddNeg(t *testing.T) {
func Test_TwistFrobeniusP(t *testing.T) {
ret1, ret2 := &twistPoint{}, &twistPoint{}
ret1.Frobenius(twistGen)
ret1.MakeAffine()
ret1.AffineFromJacobian()

ret2.x.Conjugate(&twistGen.x)
ret2.x.MulScalar(&ret2.x, betaToNegPPlus1Over3)
Expand All @@ -49,12 +49,15 @@ func Test_TwistFrobeniusP(t *testing.T) {
func Test_TwistFrobeniusP2(t *testing.T) {
ret1, ret2 := &twistPoint{}, &twistPoint{}
ret1.Frobenius(twistGen)
ret1.AffineFromJacobian()
ret1.Frobenius(ret1)
ret1.AffineFromJacobian()
if !ret1.IsOnCurve() {
t.Errorf("point should be on curve")
}

ret2.FrobeniusP2(twistGen)
ret2.AffineFromJacobian()
if !ret2.IsOnCurve() {
t.Errorf("point should be on curve")
}
Expand All @@ -77,7 +80,7 @@ func Test_TwistFrobeniusP2_Case2(t *testing.T) {
}

ret2.FrobeniusP2(twistGen)
ret2.MakeAffine()
ret2.AffineFromJacobian()
if !ret2.IsOnCurve() {
t.Errorf("point should be on curve")
}
Expand All @@ -100,7 +103,7 @@ func Test_TwistNegFrobeniusP2_Case2(t *testing.T) {
}

ret2.NegFrobeniusP2(twistGen)
ret2.MakeAffine()
ret2.AffineFromJacobian()
if !ret2.IsOnCurve() {
t.Errorf("point should be on curve")
}
Expand Down

0 comments on commit 5b5b26c

Please sign in to comment.