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