Debian Codegraph @

msp/number.go

raw symbols SCIP
1 // Polynomial fields with coefficients in GF(2)
2 package msp
3
4 import (
5 "bytes"
6 )
7
8 type FieldElem []byte
9
10 var (
11 Modulus FieldElem = []byte{135, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} // x^128 + x^7 + x^2 + x + 1
12 ModulusSize int = 16
13 ModulusBitSize int = 128
14
15 Zero FieldElem = []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
16 One FieldElem = []byte{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
17 )
18
19 // NewFieldElem returns a new zero element.
20 func NewFieldElem() FieldElem {
21 return FieldElem(make([]byte, ModulusSize))
22 }
23
24 // AddM mutates e into e+f.
25 func (e FieldElem) AddM(f FieldElem) {
26 for i := 0; i < ModulusSize; i++ {
27 e[i] ^= f[i]
28 }
29 }
30
31 // Add returns e+f.
32 func (e FieldElem) Add(f FieldElem) FieldElem {
33 out := e.Dup()
34 out.AddM(f)
35
36 return out
37 }
38
39 // Mul returns e*f.
40 func (e FieldElem) Mul(f FieldElem) FieldElem {
41 out := NewFieldElem()
42
43 for i := 0; i < ModulusBitSize; i++ { // Foreach bit e_i in e:
44 if e.getCoeff(i) == 1 { // where e_i equals 1:
45 temp := f.Dup() // Multiply f * x^i mod M(x):
46
47 for j := 0; j < i; j++ { // Multiply f by x mod M(x), i times.
48 carry := temp.shift()
49
50 if carry {
51 temp[0] ^= Modulus[0]
52 }
53 }
54
55 out.AddM(temp) // Add f * x^i to the output
56 }
57 }
58
59 return out
60 }
61
62 // Exp returns e^i.
63 func (e FieldElem) Exp(i int) FieldElem {
64 out := One.Dup()
65
66 for j := 0; j < i; j++ {
67 out = out.Mul(e)
68 }
69
70 return out
71 }
72
73 // Invert returns the multiplicative inverse of e.
74 func (e FieldElem) Invert() FieldElem {
75 out, temp := e.Dup(), e.Dup()
76
77 for i := 0; i < 126; i++ {
78 temp = temp.Mul(temp)
79 out = out.Mul(temp)
80 }
81
82 return out.Mul(out)
83 }
84
85 // getCoeff returns the ith coefficient of the field element: either 0 or 1.
86 func (e FieldElem) getCoeff(i int) byte {
87 return (e[i/8] >> (uint(i) % 8)) & 1
88 }
89
90 // shift multiplies e by 2 and returns true if there was overflow and false if there wasn't.
91 func (e FieldElem) shift() bool {
92 carry := false
93
94 for i := 0; i < ModulusSize; i++ {
95 nextCarry := e[i] >= 128
96
97 e[i] = e[i] << 1
98 if carry {
99 e[i]++
100 }
101 carry = nextCarry
102 }
103
104 return carry
105 }
106
107 func (e FieldElem) IsZero() bool { return bytes.Compare(e, Zero) == 0 }
108 func (e FieldElem) IsOne() bool { return bytes.Compare(e, One) == 0 }
109
110 // Dup returns a duplicate of e.
111 func (e FieldElem) Dup() FieldElem {
112 out := FieldElem(make([]byte, ModulusSize))
113 copy(out, e)
114
115 return out
116 }