github.com/emmansun/gmsm@v0.29.1/sm9/bn256/g2_test.go (about) 1 package bn256 2 3 import ( 4 "bytes" 5 "crypto/rand" 6 "encoding/hex" 7 "testing" 8 ) 9 10 func TestG2(t *testing.T) { 11 k, Ga, err := RandomG2(rand.Reader) 12 if err != nil { 13 t.Fatal(err) 14 } 15 ma := Ga.Marshal() 16 17 Gb, err := new(G2).ScalarBaseMult(NormalizeScalar(k.Bytes())) 18 if err != nil { 19 t.Fatal(err) 20 } 21 mb := Gb.Marshal() 22 23 if !bytes.Equal(ma, mb) { 24 t.Errorf("bytes are different, expected %v, got %v", hex.EncodeToString(ma), hex.EncodeToString(mb)) 25 } 26 } 27 28 func TestG2Marshal(t *testing.T) { 29 _, Ga, err := RandomG2(rand.Reader) 30 if err != nil { 31 t.Fatal(err) 32 } 33 ma := Ga.Marshal() 34 35 Gb := new(G2) 36 _, err = Gb.Unmarshal(ma) 37 if err != nil { 38 t.Fatal(err) 39 } 40 mb := Gb.Marshal() 41 42 if !bytes.Equal(ma, mb) { 43 t.Errorf("bytes are different, expected %v, got %v", hex.EncodeToString(ma), hex.EncodeToString(mb)) 44 } 45 } 46 47 func Test_G2MarshalCompressed(t *testing.T) { 48 e, e2 := &G2{}, &G2{} 49 ret := e.MarshalCompressed() 50 _, err := e2.UnmarshalCompressed(ret) 51 if err != nil { 52 t.Fatal(err) 53 } 54 if !e2.p.IsInfinity() { 55 t.Errorf("not same") 56 } 57 e.p.Set(twistGen) 58 ret = e.MarshalCompressed() 59 _, err = e2.UnmarshalCompressed(ret) 60 if err != nil { 61 t.Fatal(err) 62 } 63 if e2.p.x != e.p.x || e2.p.y != e.p.y || e2.p.z != e.p.z { 64 t.Errorf("not same") 65 } 66 e.p.Neg(e.p) 67 ret = e.MarshalCompressed() 68 _, err = e2.UnmarshalCompressed(ret) 69 if err != nil { 70 t.Fatal(err) 71 } 72 if e2.p.x != e.p.x || e2.p.y != e.p.y || e2.p.z != e.p.z { 73 t.Errorf("not same") 74 } 75 if e2.p.x == twistGen.x && e2.p.y == twistGen.y && e2.p.z == twistGen.z { 76 t.Errorf("not expected") 77 } 78 } 79 80 func TestScaleMult(t *testing.T) { 81 k, e, err := RandomG2(rand.Reader) 82 if err != nil { 83 t.Fatal(err) 84 } 85 e.p.MakeAffine() 86 87 e2, e3 := &G2{}, &G2{} 88 e3.p = &twistPoint{} 89 e3.p.Mul(twistGen, k) 90 e3.p.MakeAffine() 91 92 _, err = e2.ScalarMult(Gen2, NormalizeScalar(k.Bytes())) 93 if err != nil { 94 t.Fatal(err) 95 } 96 e2.p.MakeAffine() 97 if !e.Equal(e2) { 98 t.Errorf("not same") 99 } 100 } 101 102 func TestG2AddNeg(t *testing.T) { 103 g1, g2 := &G2{}, &G2{} 104 105 g1.Neg(Gen2) 106 g2.Add(g1, Gen2) 107 if !g2.p.IsInfinity() { 108 t.Fail() 109 } 110 g3 := &G2{} 111 g3.Set(Gen2) 112 if !g3.Equal(Gen2) { 113 t.Fail() 114 } 115 } 116 117 func BenchmarkG2(b *testing.B) { 118 x, _ := rand.Int(rand.Reader, Order) 119 xb := NormalizeScalar(x.Bytes()) 120 b.ReportAllocs() 121 b.ResetTimer() 122 123 for i := 0; i < b.N; i++ { 124 new(G2).ScalarBaseMult(xb) 125 } 126 }