github.com/arjunbeliever/ignite@v0.0.0-20220406110515-46bbbbec2587/crypto/bn256/cloudflare/bn256_test.go (about) 1 package bn256 2 3 import ( 4 "bytes" 5 "crypto/rand" 6 "testing" 7 ) 8 9 func TestG1Marshal(t *testing.T) { 10 _, Ga, err := RandomG1(rand.Reader) 11 if err != nil { 12 t.Fatal(err) 13 } 14 ma := Ga.Marshal() 15 16 Gb := new(G1) 17 _, err = Gb.Unmarshal(ma) 18 if err != nil { 19 t.Fatal(err) 20 } 21 mb := Gb.Marshal() 22 23 if !bytes.Equal(ma, mb) { 24 t.Fatal("bytes are different") 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.Fatal("bytes are different") 44 } 45 } 46 47 func TestBilinearity(t *testing.T) { 48 for i := 0; i < 2; i++ { 49 a, p1, _ := RandomG1(rand.Reader) 50 b, p2, _ := RandomG2(rand.Reader) 51 e1 := Pair(p1, p2) 52 53 e2 := Pair(&G1{curveGen}, &G2{twistGen}) 54 e2.ScalarMult(e2, a) 55 e2.ScalarMult(e2, b) 56 57 if *e1.p != *e2.p { 58 t.Fatalf("bad pairing result: %s", e1) 59 } 60 } 61 } 62 63 func TestTripartiteDiffieHellman(t *testing.T) { 64 a, _ := rand.Int(rand.Reader, Order) 65 b, _ := rand.Int(rand.Reader, Order) 66 c, _ := rand.Int(rand.Reader, Order) 67 68 pa, pb, pc := new(G1), new(G1), new(G1) 69 qa, qb, qc := new(G2), new(G2), new(G2) 70 71 pa.Unmarshal(new(G1).ScalarBaseMult(a).Marshal()) 72 qa.Unmarshal(new(G2).ScalarBaseMult(a).Marshal()) 73 pb.Unmarshal(new(G1).ScalarBaseMult(b).Marshal()) 74 qb.Unmarshal(new(G2).ScalarBaseMult(b).Marshal()) 75 pc.Unmarshal(new(G1).ScalarBaseMult(c).Marshal()) 76 qc.Unmarshal(new(G2).ScalarBaseMult(c).Marshal()) 77 78 k1 := Pair(pb, qc) 79 k1.ScalarMult(k1, a) 80 k1Bytes := k1.Marshal() 81 82 k2 := Pair(pc, qa) 83 k2.ScalarMult(k2, b) 84 k2Bytes := k2.Marshal() 85 86 k3 := Pair(pa, qb) 87 k3.ScalarMult(k3, c) 88 k3Bytes := k3.Marshal() 89 90 if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) { 91 t.Errorf("keys didn't agree") 92 } 93 } 94 95 func BenchmarkG1(b *testing.B) { 96 x, _ := rand.Int(rand.Reader, Order) 97 b.ResetTimer() 98 99 for i := 0; i < b.N; i++ { 100 new(G1).ScalarBaseMult(x) 101 } 102 } 103 104 func BenchmarkG2(b *testing.B) { 105 x, _ := rand.Int(rand.Reader, Order) 106 b.ResetTimer() 107 108 for i := 0; i < b.N; i++ { 109 new(G2).ScalarBaseMult(x) 110 } 111 } 112 func BenchmarkPairing(b *testing.B) { 113 for i := 0; i < b.N; i++ { 114 Pair(&G1{curveGen}, &G2{twistGen}) 115 } 116 }