-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenzkp.py.bak
More file actions
656 lines (501 loc) · 17.9 KB
/
genzkp.py.bak
File metadata and controls
656 lines (501 loc) · 17.9 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
## An example of how to implement an engine for Zero-Knowledge
# Proof of Discrete Log representations using Brands' and
# Camenisch's extensions to the basic Schnor proof.
#
# For details of what is doing on see Chapter 3:
# "Rethinking Public Key Infrastructures and Digital Certificates
# Building in Privacy" By Stefan Brands, MIT Press (2000)
# On-line: http://www.credentica.com/the_mit_pressbook.html
from petlib.ec import EcGroup
from petlib.bn import Bn
from hashlib import sha256
import pytest
def challenge(elements):
"""Packages a challenge in a bijective way"""
elem = [len(elements)] + elements
elem_str = map(str, elem)
elem_len = map(lambda x: "%s||%s" % (len(x) , x), elem_str)
state = "|".join(elem_len)
H = sha256()
H.update(state.encode("utf8"))
return H.digest()
class Val:
"""A common ansestor for all values"""
def val(self, env):
return env[self.name]
def tex(self):
return "{%s}" % tex_encode(self.name)
class Pub(Val):
"""Defines a public value, given by the prover"""
def __init__(self, zkp, name):
self.name = name
self.zkp = zkp
assert name not in zkp.Pub
zkp.Pub[name] = self
def tex(self):
return r"{\mathrm{%s}}" % tex_encode(self.name)
class ConstPub(Pub):
"""Defines a public value from the environment"""
def __init__(self, zkp, name):
self.name = name
self.zkp = zkp
assert name not in zkp.Const
zkp.Const[name] = self
class Sec(Val):
"""Defines a secret value of the prover"""
def __init__(self, zkp, name):
self.name = name
self.zkp = zkp
assert name not in zkp.Sec
zkp.Sec[name] = self
class Gen(object):
"""Represents a public generator, given by the prover"""
def __init__(self, zkp, name=None, prove=False, constuction=None):
self.name = name
self.zkp = zkp
if name:
assert name not in zkp.Pub
zkp.Pub[name] = self
self.prove = prove
self.constuction = constuction
def get_repr(self):
if self.name or self.constuction[0] == "Gen*":
return [self]
elif self.constuction[0] == "Gen+":
return self.constuction[1:]
raise Exception("Unknown Gen type")
def __add__(self, other):
assert isinstance(other, Gen)
assert self.zkp == other.zkp
assert self.prove == other.prove
prove = self.prove or other.prove
c = ["Gen+"] + self.get_repr() + other.get_repr()
newG = Gen(self.zkp, prove=prove, constuction=c)
return newG
def __rmul__(self, other):
assert isinstance(other, Val)
assert not self.prove
assert self.zkp == other.zkp
prove = isinstance(other, Sec)
if self.constuction and self.constuction[0] == "Gen*":
c = self.constuction + [other]
else:
c = ["Gen*", self, other]
return Gen(self.zkp, constuction=c, prove=prove)
def tex(self):
## In case of a named value just return it.
if self.name:
return r"{\mathrm{%s}}" % (tex_encode(self.name))
if self.constuction[0] == "Gen+":
gather = [v.tex() for v in self.constuction[1:]]
Sum = " \cdot ".join(gather)
return "{%s}" % Sum
if self.constuction[0] == "Gen*":
base = self.constuction[1].tex()
exps = [v.tex() for v in self.constuction[2:]]
exps = " \cdot ".join(exps)
ret = "{%s}^{%s}" % (base, exps)
return ret
def val(self, env):
"""Returns the value of this variable"""
## In case of a named value just return it.
if self.name:
return env[self.name]
## In case of a "+" add all parts
if self.constuction[0] == "Gen+":
gather = [v.val(env) for v in self.constuction[1:]]
Sum = None
for v in gather:
if Sum is None:
Sum = v
else:
Sum = v + Sum
return Sum
if self.constuction[0] == "Gen*":
base = self.constuction[1].val(env)
exps = [v.val(env) for v in self.constuction[2:]]
Prod = 1
for v in exps:
Prod = v * Prod
return Prod * base
raise Exception("Unknown case")
class ConstGen(Gen):
"""Represents a generator constant in the environment"""
def __init__(self, zkp, name):
Gen.__init__(self, zkp, name=None)
self.name = name
assert name not in self.zkp.Const
self.zkp.Const[name] = self
class ZKProof(object):
"""A class representing a number of associated ZK Proofs."""
def __init__(self, G):
"""Define a proof object, and the group in which the proof
is to be carried."""
self.locked = False
self.G = G
self.Const = {}
self.Pub = {}
self.Sec = {}
self.proofs = []
self.arrays = {}
self.locked = True
def add_proof(self, lhs, rhs):
"""Adds a proof obligation to show the rhs is the representation of the lhs"""
assert isinstance(lhs, Gen)
assert lhs.prove == False
assert isinstance(rhs, Gen)
assert rhs.prove == True
assert self == lhs.zkp == rhs.zkp
self.proofs.append((lhs, rhs))
def _check_name_ok(self, name):
if __debug__:
import re
a = re.compile("^[a-zA-Z][a-zA-Z0-9_]*$")
if a.match(name) is not None:
return True
return False
def get(self, vtype, name, ignore_check = False):
"""Returns a number of proof variables of a certain type"""
assert vtype in [Gen, ConstGen, Sec, Pub, ConstPub]
if isinstance(name, str):
assert self._check_name_ok(name) or ignore_check
return self._get(vtype, name, ignore_check)
if isinstance(name, list):
assert all(map(self._check_name_ok, name)) or ignore_check
return [self._get(vtype, n, ignore_check) for n in name]
raise Exception("Wrong type of names: str or list(str)")
def _get(self, vtype, name, ignore_check = False):
assert isinstance(name, str)
for D in [self.Const, self.Pub, self.Sec]:
if name in D:
assert isinstance(D[name], vtype)
return D[name]
return vtype(self, name)
def __setattr__(self, name, value):
if hasattr(self, "locked") and self.locked:
assert name not in self.__dict__
# Add the name to the zk proof
v = self.get(value, name)
object.__setattr__(self, name, v)
else:
# implement *my* __setattr__
object.__setattr__(self, name, value)
def get_array(self, vtype, name, number, start=0):
"""Returns an array of variables"""
assert vtype in [Gen, ConstGen, Sec, Pub, ConstPub]
assert isinstance(name, str)
assert self._check_name_ok(name)
if name in self.arrays:
assert self.arrays[name] == (number, start)
else:
self.arrays[name] = (number, start)
names = ["%s[%i]" % (name,i) for i in range(start, start+number)]
return self.get(vtype, names, True)
def all_vars(self):
variables = list(self.Const) \
+ list(self.Pub) \
+ list(self.Sec)
return set(variables)
def _check_env(self, env):
if __debug__:
variables = self.all_vars()
for v in variables:
if not v in env:
raise Exception("Could not find variable %s in the environment.\n%s" % (repr(v), repr(variables)))
def render_proof_statement(self):
s = r'$'
if len(self.Const) > 0:
variables = []
for con in sorted(list(self.Const)):
variables += ["{\mathrm{%s}}" % tex_encode(con)]
s += r"\text{Constants: } %s \\" % (', '.join(variables))
if len(self.Pub) > 0:
variables = []
for pub in sorted(list(self.Pub)):
variables += ["{\mathrm{%s}}" % tex_encode(pub)]
s += r"\text{Public: } %s \\" % (', '.join(variables))
s += r"\text{NIZK}\{" + """("""
variables = []
for sec in sorted(list(self.Sec)):
variables += ["{%s}" % tex_encode(sec)]
variables = ', '.join(variables)
s += variables
s += r"): \\ \qquad "
formulas = []
for base, expr in self.proofs:
formulas += ["%s = %s" % (base.tex(), expr.tex())]
s += r" \wedge \\ \qquad ".join(formulas)
s+= r'\}$'
return s
def build_proof(self, env, message=""):
"""Generates a proof within an environment of assigned public and secret variables."""
self._check_env(env)
# Do sanity check on the proofs
if __debug__:
for base, expr in self.proofs:
xGen = base.val(env)
xExpr = expr.val(env)
try:
assert xGen == xExpr
except:
raise Exception("Proof about '%s' does not hold." % base.name)
G = self.G
order = G.order()
## Make a list of all the public state
state = ['ZKP', G.nid(), message]
for v in sorted(self.Const.keys()):
state += [env[v]]
for v in sorted(self.Pub.keys()):
state += [env[v]]
## Set witnesses for all secrets
witnesses = dict(env.items())
for w in self.Sec.keys():
assert w in witnesses
witnesses[w] = order.random()
## Compute the first message and add it to the state
for base, expr in self.proofs:
Cw = expr.val(witnesses)
state += [Cw]
## Compute the challenge using all the state
hash_c = challenge(state)
c = Bn.from_binary(hash_c) % order
## Compute all the resources
responses = dict(env.items())
for w in self.Sec.keys():
responses[w] = (witnesses[w] - c * env[w]) % order
for v in self.Const:
del responses[v]
return (c, responses)
def verify_proof(self, env, sig, message="", strict=True):
"""Verifies a proof within an environment of assigned public only variables."""
## Select the constants for the env
env_l = [(k,v) for k,v in env.items() if k in self.Const]
if __debug__ and strict:
env_not = [k for k,v in env.items() if k not in self.Const]
if len(env_not):
raise Exception("Did not check: " + (", ".join(env_not)))
c, responses = sig
responses = dict(list(responses.items()) + env_l)
## Ensure all variables we need are here
self._check_env(responses)
## Define the maths group we work in
G = self.G
order = G.order()
## Make a list of all the public state
state = ['ZKP', G.nid(), message]
for v in sorted(self.Const.keys()):
state += [responses[v]]
for v in sorted(self.Pub.keys()):
state += [responses[v]]
## Compute the first message and add it to the state
for base, expr in self.proofs:
Cr = expr.val(responses)
Cx = base.val(responses)
Cw = Cr + c * Cx
state += [Cw]
## Compute the challenge using all the state
hash_c = challenge(state)
c_prime = Bn.from_binary(hash_c) % order
## Check equality
return (c == c_prime)
class ZKEnv(object):
""" A class that passes all the ZK environment
state to the proof or verification.
"""
def __init__(self, zkp):
""" Initializes and ties to a specific proof. """
## Watch out for recursive calls, given we
# redefined __setattr__
object.__setattr__(self, "zkp", zkp)
object.__setattr__(self, "env", {})
def __setattr__(self, name, value):
""" Store into a special dictionary """
if isinstance(value, list):
assert name in self.zkp.arrays
number, start = self.zkp.arrays[name]
assert len(value) == number
for i, v in enumerate(value):
n = "%s[%i]" % (name,start+i)
self._set_var(n, v)
else:
self._set_var(name, value)
def _set_var(self, name, value):
if not name in self.zkp.all_vars():
raise Exception("Variable name '%s' not known." % name)
self.env[name] = value
def __getattr__(self, name):
if not name in self.zkp.all_vars():
raise Exception("Variable name '%s' not known." % name)
return self.env[name]
def get(self):
""" Get the environement. """
return self.env
import re
def tex_encode(name):
m = re.match(r"^(.+)i\[([0-9]+)\]$", name)
if m != None:
return r"{%s}_{%s}" % (tex_encode(m.group(1)), m.group(2))
m = re.match(r"^(.+)_prime$", name)
if m != None:
return r"{%s'}" % (tex_encode(m.group(1)))
m = re.match(r"^(.+)_bar$", name)
if m != None:
return r"{\overline{%s}}" % (tex_encode(m.group(1)))
return name
def test_tex():
assert "}_{" in tex_encode("helloi[10]")
assert "'}" in tex_encode("hello_prime")
assert r"\overline" in tex_encode("hello_bar")
def test_basic():
zk = ZKProof(None)
g = zk.get(ConstGen, "g")
# Test: ok to call twice
g2 = zk.get(ConstGen, "g")
# return same object
assert g == g2
# Test: need to be of same type!
with pytest.raises(Exception) as excinfo:
zk.get(Pub, "g")
print str(excinfo.value)
assert "isinstance" in str(excinfo.value)
h = zk.get(ConstGen, "h")
Gone = zk.get(ConstGen, "d1")
x = zk.get(Sec, "x")
o = zk.get(Sec, "o")
y = zk.get(Pub, "y")
one = zk.get(ConstPub, "d1g")
Cx = zk.get(Gen, "Cx")
Cxp = x*g + o*(y * h)
zk.add_proof(Cx, Cxp)
print(zk.Const.keys())
print(zk.Pub.keys())
print(zk.Sec.keys())
def test_Pedersen():
# Define an EC group
G = EcGroup(713)
order = G.order()
## Proof definitions
zk = ZKProof(G)
g, h = zk.get(ConstGen, ["g", "h"])
x, o = zk.get(Sec, ["x", "o"])
Cxo = zk.get(Gen, "Cxo")
zk.add_proof(Cxo, x*g + o*h)
# A concrete Pedersen commitment
ec_g = G.generator()
ec_h = order.random() * ec_g
bn_x = order.random()
bn_o = order.random()
ec_Cxo = bn_x * ec_g + bn_o * ec_h
# Execute the proof
env = {
"g": ec_g,
"h": ec_h,
"Cxo": ec_Cxo,
"x": bn_x,
"o": bn_o
}
sig = zk.build_proof(env)
# Execute the verification
env_verify = {
"g": ec_g,
"h": ec_h
}
assert zk.verify_proof(env_verify, sig)
def test_Pedersen_Env():
# Define an EC group
G = EcGroup(713)
order = G.order()
## Proof definitions
zk = ZKProof(G)
g, h = zk.get(ConstGen, ["g", "h"])
x, o = zk.get(Sec, ["x", "o"])
Cxo = zk.get(Gen, "Cxo")
zk.add_proof(Cxo, x*g + o*h)
print(zk.render_proof_statement())
# A concrete Pedersen commitment
ec_g = G.generator()
ec_h = order.random() * ec_g
bn_x = order.random()
bn_o = order.random()
ec_Cxo = bn_x * ec_g + bn_o * ec_h
env = ZKEnv(zk)
env.g, env.h = ec_g, ec_h
env.Cxo = ec_Cxo
env.x = bn_x
env.o = bn_o
sig = zk.build_proof(env.get())
# Execute the verification
env = ZKEnv(zk)
env.g, env.h = ec_g, ec_h
assert zk.verify_proof(env.get(), sig)
def test_Pedersen_Shorthand():
# Define an EC group
G = EcGroup(713)
order = G.order()
## Proof definitions
zk = ZKProof(G)
zk.g, zk.h = ConstGen, ConstGen
zk.x, zk.o = Sec, Sec
zk.Cxo = Gen
zk.add_proof(zk.Cxo, zk.x*zk.g + zk.o*zk.h)
print(zk.render_proof_statement())
# A concrete Pedersen commitment
ec_g = G.generator()
ec_h = order.random() * ec_g
bn_x = order.random()
bn_o = order.random()
ec_Cxo = bn_x * ec_g + bn_o * ec_h
env = ZKEnv(zk)
env.g, env.h = ec_g, ec_h
env.Cxo = ec_Cxo
env.x = bn_x
env.o = bn_o
sig = zk.build_proof(env.get())
# Execute the verification
env = ZKEnv(zk)
env.g, env.h = ec_g, ec_h
assert zk.verify_proof(env.get(), sig)
def test_Pedersen_Env_missing():
# Define an EC group
G = EcGroup(713)
order = G.order()
## Proof definitions
zk = ZKProof(G)
g, h = zk.get(ConstGen, ["g", "h"])
x, o = zk.get(Sec, ["x", "o"])
Cxo = zk.get(Gen, "Cxo")
zk.add_proof(Cxo, x*g + o*h)
# A concrete Pedersen commitment
ec_g = G.generator()
ec_h = order.random() * ec_g
bn_x = order.random()
bn_o = order.random()
ec_Cxo = bn_x * ec_g + bn_o * ec_h
env = ZKEnv(zk)
env.g, env.h = ec_g, ec_h
env.Cxo = ec_Cxo
env.x = bn_x
# env.o = bn_o ## MISSING THIS ONE
with pytest.raises(Exception) as excinfo:
env.NOTEXISTING = bn_x
assert "Variable name 'NOTEXISTING' not known" in str(excinfo.value)
## Ensure we catch missing variables
with pytest.raises(Exception) as excinfo:
zk.build_proof(env.get())
assert 'Could not find variable' in str(excinfo.value)
## Ensure we catch false statements
env.o = bn_o + 1
with pytest.raises(Exception) as excinfo:
zk.build_proof(env.get())
assert "Proof about 'Cxo' does not hold" in str(excinfo.value)
def test_latex_print():
# Define an EC group
G = EcGroup(713)
order = G.order()
## Proof definitions
zk = ZKProof(G)
g, h = zk.get(ConstGen, ["g", "h"])
x, o = zk.get(Sec, ["x", "o"])
Cxo = zk.get(Gen, "Cxo")
zk.add_proof(Cxo, x*g + o*h)
print(zk.render_proof_statement())