-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsumcheck.sage
305 lines (244 loc) · 7.36 KB
/
sumcheck.sage
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# example taken from [thaler's](https://people.cs.georgetown.edu/jthaler/ProofsArgsAndZK.pdf) book chapter 3.7
# randomness in this file is completely twisted and not advisable to follow. transcript isn't implemented.
from sage.all import *
from sage.rings.polynomial.polydict import PolyDict
import unittest
p = 19
F = GF(p)
R.<x,y> = F['x, y']
G.<x> = F['x']
# G.<x> = F[]
# print(G)
# unipoly = G([0])
# print(unipoly)
# unipoly1 = G([1, 2])
# print(unipoly + unipoly1)
def fun(x, y):
return ((1-x)*(1-y)) + (2*(1-x)*y) + (8*x*(1-y)) + (10*x*y)
P = R.interpolation(2, fun)
# print(R.interpolation(2, fun))
# print("poly:", P)
# print("monomials:", P.monomials())
# print("coefficients:", P.coefficients())
# print("variables:", P.variables())
# print(P(1, 1))
fw = [1, 2, 8, 10]
r = [int(F.random_element()), int(F.random_element())]
def to_bin(i, num):
return list(f'{i:0{num}b}')
def to_int_list_bin(i, num):
return [int(x) for x in to_bin(i, num)]
def delta_w(a, b):
return (a*b)+((1-a)*(1-b))
def delta_step(i, r):
res = 1
len_r = len(r)
# print(len_r, f'{i:0{len_r}b}')
bin_i = to_bin(i, len_r)
for j in range(len_r):
res *= delta_w(r[j], int(bin_i[j]))
# print("res: ", res)
return res
def mle(fw, r, p):
delta_w = 0
for i in range(len(fw)):
delta_w += fw[i] * delta_step(i, r)
return delta_w % p
assert(mle(fw, r, p) == int(P(r)))
def memoize(r, n):
if n == 1:
return [delta_w(0, r[n-1]), delta_w(1, r[n-1])]
else:
vals = memoize(r, n-1)
val = []
for i in range(len(vals)):
val.append(vals[i] * delta_w(0, r[n-1]))
val.append(vals[i] * delta_w(1, r[n-1]))
return val
def dynamic_mle(fw, r, p):
delta_lookup = memoize(r, len(r))
delta_w = 0
for i in range(len(fw)):
delta_w += fw[i] * delta_lookup[i]
return delta_w % p
assert(dynamic_mle(fw, r, p) == int(P(r)))
def num_vars(P: PolyDict):
"""
returns number of variables in a multiliear polynomial
"""
return len(P.exponents()[0])
def max_degree(P: PolyDict):
"""
params:
- `P`: multilinear polynomial
returns:
- `lookup_degree`: list containing max degree of each variable
"""
lookup_degree = [0] * num_vars(P)
for term in P.dict():
for i in range(len(term)):
if term[i] > lookup_degree[i]:
lookup_degree[i] = term[i]
return lookup_degree
def evaluate(P: PolyDict, F, r):
"""
params:
- `P`: multilinear polynomial
- `F`: field
- `r`: list of random variables
returns:
- `result`: evaluation of multilinear polynomial at a specific point
"""
terms = P.dict()
result = F(0)
for term, coeff in terms.items():
prod = 1
for i in range(len(term)):
prod *= F(int(r[i])) ** term[i]
result += coeff * prod
return result
def evaluate_multipoly_hypercube(F, P):
"""
evaluate multilinear polynomial at all points in hypercube
"""
result = F(0)
n = 2**num_vars(P)
for i in range(n):
result += evaluate(P, F, to_bin(i, num_vars(P)))
return result
# use this: https://doc.sagemath.org/html/en/reference/polynomial_rings/sage/rings/polynomial/polydict.html#sage.rings.polynomial.polydict.PolyDict
class Sumcheck:
def __init__(self, F, P: PolyDict):
"""
params:
- `F`: field
- `P`: multilinear poly
"""
self.F = F
self.P = P
self.r = [] # random vars
G.<x> = F['x'] # unipoly
self.G = G
self.x = x # poly invariate
def evaluate_term(self, term, points):
"""
evaluate a monomial in multilinear polynomial at a specific point and substitue
initial variables with random variables generated by verifier.
"""
len_r = len(self.r)
coeff = F(1)
poly = self.G([0])
for i in range(len(term)):
if i < len_r:
coeff = coeff * self.r[i] ** (term[i])
elif i == len_r:
poly = self.x ** (term[i])
else:
coeff = coeff * (int(points[i - len_r]) ** (term[i]))
poly = poly * coeff
return poly
def evaluate_gj(self, points):
"""
evaluate multilinear polynomial at a specific point and substitue initial
variables with random vars provided by verifier
"""
terms = self.P.dict()
uniPoly = self.G([0])
for term, coeff in terms.items():
unipoly_term = self.evaluate_term(term, points)
uniPoly = uniPoly + coeff*unipoly_term
return uniPoly
def prove_interactive(self, r):
"""
takes a random variable r and creates univariate polynomial by evaluating
poly `G(r0, r1, ..., rk, xk+1, ..., xn)`.
"""
if r != None:
self.r.append(r)
v = num_vars(self.P) - len(self.r)
unipoly = self.G([0])
for i in range(0, 2**(v-1)):
poly = self.evaluate_gj(to_bin(i, v))
# print(poly)
unipoly = unipoly + poly
return unipoly
def prove_non_interactive(self):
randomness = []
uni_polys = []
r = None
for i in range(num_vars(self.P)):
unipoly = self.prove_interactive(r)
uni_polys.append(unipoly)
r = F.random_element()
randomness.append(r)
return (uni_polys, randomness)
def verify_interactive(self, c):
"""
runs sumcheck protocol and verifies the result
"""
lookup_degree_table = max_degree(self.P)
gi = self.prove_interactive(None)
print("round 0: ", gi)
# print(gi, gi(0), gi(1))
expected = gi(0) + gi(1)
# print(expected)
assert(expected == c)
assert(gi.degree() <= lookup_degree_table[0])
for i in range(1, num_vars(self.P)):
r = F.random_element()
actual = gi(r)
gi = self.prove_interactive(r)
print(f"round {i}: {gi}")
expected = gi(0) + gi(1)
assert(actual == expected)
assert(gi.degree() <= lookup_degree_table[i])
r = F.random_element()
expected = gi(r)
self.r.append(r)
actual = evaluate(self.P, self.F, self.r)
print("last round: ", actual, expected)
return actual == expected
def verify_non_interactive(self, proof, r, sum):
"""
runs sumcheck protocol non interactively and verifies the result
TODO: implement transcript
"""
lookup_degree_table = max_degree(self.P)
for i in range(num_vars(self.P)):
unipoly = proof[i]
expected = unipoly(0) + unipoly(1)
assert(expected == sum)
assert(unipoly.degree() <= lookup_degree_table[i])
sum = unipoly(r[i])
expected = sum
actual = evaluate(self.P, self.F, r)
assert(expected == actual)
class TestSumcheck(unittest.TestCase):
def test_sumcheck(self):
multipoly1 = PolyDict({(3, 0, 0): F(2), (1, 0, 1): F(1), (0, 1, 1): F(1)})
print("starting sumcheck with poly: ", multipoly1.latex(['x1', 'x2', 'x3']))
sumcheck = Sumcheck(F, multipoly1)
evaluation = evaluate_multipoly_hypercube(sumcheck.F, sumcheck.P)
assert(sumcheck.verify_interactive(evaluation))
multipoly = PolyDict({(2, 3, 2): F(2), (1, 0, 1): F(3), (2, 1, 0): F(4)})
print("starting sumcheck with poly: ", multipoly1.latex(['x1', 'x2', 'x3']))
sumcheck = Sumcheck(F, multipoly)
evaluation = evaluate_multipoly_hypercube(sumcheck.F, sumcheck.P)
assert(sumcheck.verify_interactive(evaluation))
def test_poly_funcs(self):
multipoly1 = PolyDict({(3, 0, 0): F(2), (1, 0, 1): F(1), (0, 1, 1): F(1)})
num = num_vars(multipoly1)
assert(num == 3)
degree = max_degree(multipoly1)
assert(degree == [3, 1, 1])
evaluation = evaluate(multipoly1, F, [1, 0, 1])
assert(evaluation == F(3))
def test_non_interactive(self):
multipoly1 = PolyDict({(3, 0, 0): F(2), (1, 0, 1): F(1), (0, 1, 1): F(1)})
print("starting sumcheck with poly: ", multipoly1.latex(['x1', 'x2', 'x3']))
sumcheck = Sumcheck(F, multipoly1)
proof, r = sumcheck.prove_non_interactive()
sum = evaluate_multipoly_hypercube(sumcheck.F, sumcheck.P)
sumcheck.verify_non_interactive(proof, r, sum)
# if __name__ == '__main__':
# unittest.main()