bn256_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. package bn256
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "testing"
  6. )
  7. func TestG1Marshal(t *testing.T) {
  8. _, Ga, err := RandomG1(rand.Reader)
  9. if err != nil {
  10. t.Fatal(err)
  11. }
  12. ma := Ga.Marshal()
  13. Gb := new(G1)
  14. _, err = Gb.Unmarshal(ma)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. mb := Gb.Marshal()
  19. if !bytes.Equal(ma, mb) {
  20. t.Fatal("bytes are different")
  21. }
  22. }
  23. func TestG2Marshal(t *testing.T) {
  24. _, Ga, err := RandomG2(rand.Reader)
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. ma := Ga.Marshal()
  29. Gb := new(G2)
  30. _, err = Gb.Unmarshal(ma)
  31. if err != nil {
  32. t.Fatal(err)
  33. }
  34. mb := Gb.Marshal()
  35. if !bytes.Equal(ma, mb) {
  36. t.Fatal("bytes are different")
  37. }
  38. }
  39. func TestBilinearity(t *testing.T) {
  40. for i := 0; i < 2; i++ {
  41. a, p1, _ := RandomG1(rand.Reader)
  42. b, p2, _ := RandomG2(rand.Reader)
  43. e1 := Pair(p1, p2)
  44. e2 := Pair(&G1{curveGen}, &G2{twistGen})
  45. e2.ScalarMult(e2, a)
  46. e2.ScalarMult(e2, b)
  47. if *e1.p != *e2.p {
  48. t.Fatalf("bad pairing result: %s", e1)
  49. }
  50. }
  51. }
  52. func TestTripartiteDiffieHellman(t *testing.T) {
  53. a, _ := rand.Int(rand.Reader, Order)
  54. b, _ := rand.Int(rand.Reader, Order)
  55. c, _ := rand.Int(rand.Reader, Order)
  56. pa, pb, pc := new(G1), new(G1), new(G1)
  57. qa, qb, qc := new(G2), new(G2), new(G2)
  58. pa.Unmarshal(new(G1).ScalarBaseMult(a).Marshal())
  59. qa.Unmarshal(new(G2).ScalarBaseMult(a).Marshal())
  60. pb.Unmarshal(new(G1).ScalarBaseMult(b).Marshal())
  61. qb.Unmarshal(new(G2).ScalarBaseMult(b).Marshal())
  62. pc.Unmarshal(new(G1).ScalarBaseMult(c).Marshal())
  63. qc.Unmarshal(new(G2).ScalarBaseMult(c).Marshal())
  64. k1 := Pair(pb, qc)
  65. k1.ScalarMult(k1, a)
  66. k1Bytes := k1.Marshal()
  67. k2 := Pair(pc, qa)
  68. k2.ScalarMult(k2, b)
  69. k2Bytes := k2.Marshal()
  70. k3 := Pair(pa, qb)
  71. k3.ScalarMult(k3, c)
  72. k3Bytes := k3.Marshal()
  73. if !bytes.Equal(k1Bytes, k2Bytes) || !bytes.Equal(k2Bytes, k3Bytes) {
  74. t.Errorf("keys didn't agree")
  75. }
  76. }
  77. func BenchmarkG1(b *testing.B) {
  78. x, _ := rand.Int(rand.Reader, Order)
  79. b.ResetTimer()
  80. for i := 0; i < b.N; i++ {
  81. new(G1).ScalarBaseMult(x)
  82. }
  83. }
  84. func BenchmarkG2(b *testing.B) {
  85. x, _ := rand.Int(rand.Reader, Order)
  86. b.ResetTimer()
  87. for i := 0; i < b.N; i++ {
  88. new(G2).ScalarBaseMult(x)
  89. }
  90. }
  91. func BenchmarkPairing(b *testing.B) {
  92. for i := 0; i < b.N; i++ {
  93. Pair(&G1{curveGen}, &G2{twistGen})
  94. }
  95. }