You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

110 lines
2.3 KiB

  1. package bn128
  2. import (
  3. "math/big"
  4. )
  5. // Fq2 is Field 2
  6. type Fq2 struct {
  7. F Fq
  8. NonResidue *big.Int
  9. }
  10. // NewFq2 generates a new Fq2
  11. func NewFq2(f Fq, nonResidue *big.Int) Fq2 {
  12. fq2 := Fq2{
  13. f,
  14. nonResidue,
  15. }
  16. return fq2
  17. }
  18. // Zero returns a Zero value on the Fq2
  19. func (fq2 Fq2) Zero() [2]*big.Int {
  20. return [2]*big.Int{fq2.F.Zero(), fq2.F.Zero()}
  21. }
  22. // One returns a One value on the Fq2
  23. func (fq2 Fq2) One() [2]*big.Int {
  24. return [2]*big.Int{fq2.F.One(), fq2.F.One()}
  25. }
  26. func (fq2 Fq2) mulByNonResidue(a *big.Int) *big.Int {
  27. return fq2.F.Mul(fq2.NonResidue, a)
  28. }
  29. // Add performs an addition on the Fq2
  30. func (fq2 Fq2) Add(a, b [2]*big.Int) [2]*big.Int {
  31. return [2]*big.Int{
  32. fq2.F.Add(a[0], b[0]),
  33. fq2.F.Add(a[1], b[1]),
  34. }
  35. }
  36. // Double performs a doubling on the Fq2
  37. func (fq2 Fq2) Double(a [2]*big.Int) [2]*big.Int {
  38. return fq2.Add(a, a)
  39. }
  40. // Sub performs a substraction on the Fq2
  41. func (fq2 Fq2) Sub(a, b [2]*big.Int) [2]*big.Int {
  42. return [2]*big.Int{
  43. fq2.F.Sub(a[0], b[0]),
  44. fq2.F.Sub(a[1], b[1]),
  45. }
  46. }
  47. // Neg performs a negation on the Fq2
  48. func (fq2 Fq2) Neg(a [2]*big.Int) [2]*big.Int {
  49. return fq2.Sub(fq2.Zero(), a)
  50. }
  51. // Mul performs a multiplication on the Fq2
  52. func (fq2 Fq2) Mul(a, b [2]*big.Int) [2]*big.Int {
  53. // Multiplication and Squaring on Pairing-Friendly.pdf; Section 3 (Karatsuba)
  54. v0 := fq2.F.Mul(a[0], b[0])
  55. v1 := fq2.F.Mul(a[1], b[1])
  56. return [2]*big.Int{
  57. fq2.F.Add(v0, fq2.mulByNonResidue(v1)),
  58. fq2.F.Sub(
  59. fq2.F.Mul(
  60. fq2.F.Add(a[0], a[1]),
  61. fq2.F.Add(b[0], b[1])),
  62. fq2.F.Add(v0, v1)),
  63. }
  64. }
  65. // Inverse returns the inverse on the Fq2
  66. func (fq2 Fq2) Inverse(a [2]*big.Int) [2]*big.Int {
  67. t0 := fq2.F.Square(a[0])
  68. t1 := fq2.F.Square(a[1])
  69. t2 := fq2.F.Sub(t0, fq2.mulByNonResidue(t1))
  70. t3 := fq2.F.Inverse(t2)
  71. return [2]*big.Int{
  72. fq2.F.Mul(a[0], t3),
  73. fq2.F.Neg(fq2.F.Mul(a[1], t3)),
  74. }
  75. }
  76. // Div performs a division on the Fq2
  77. func (fq2 Fq2) Div(a, b [2]*big.Int) [2]*big.Int {
  78. return fq2.Mul(a, fq2.Inverse(b))
  79. }
  80. // Square performs a square operation on the Fq2
  81. func (fq2 Fq2) Square(a [2]*big.Int) [2]*big.Int {
  82. ab := fq2.F.Mul(a[0], a[1])
  83. return [2]*big.Int{
  84. fq2.F.Sub(
  85. fq2.F.Mul(
  86. fq2.F.Add(a[0], a[1]),
  87. fq2.F.Add(
  88. a[0],
  89. fq2.mulByNonResidue(a[1]))),
  90. fq2.F.Add(
  91. ab,
  92. fq2.mulByNonResidue(ab))),
  93. fq2.F.Add(ab, ab),
  94. }
  95. }