This repository was archived by the owner on Jun 8, 2026. It is now read-only.
forked from supranational/blst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.me
More file actions
executable file
·324 lines (258 loc) · 10.7 KB
/
Copy pathrun.me
File metadata and controls
executable file
·324 lines (258 loc) · 10.7 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
#!/usr/bin/env python3
import os
import sys
import subprocess
import re
import sysconfig
import hashlib
here = re.split(r'/(?=[^/]*$)', sys.argv[0])
if len(here) > 1:
os.chdir(here[0])
def newer(*files) :
assert len(files) > 1
rh = files[-1]
if not os.path.exists(rh) :
return True
for lh in files[:-1] :
if os.stat(lh).st_ctime > os.stat(rh).st_ctime :
return True
return False
if newer("../blst.h", "../libblst.a") :
print("building libblst.a...") or sys.stdout.flush()
subprocess.check_call(["../build.sh"], cwd="..")
if newer("../blst.swg", "../blst.h", "../blst.hpp", "blst_wrap.cpp") :
print("swig-ing...") or sys.stdout.flush()
subprocess.check_call(["swig", "-c++", "-python", "-O",
"-o", "blst_wrap.cpp", "-outdir", ".",
"../blst.swg"])
if newer("blst_wrap.cpp", "../libblst.a", "_blst.so") :
print("compiling _blst.so...") or sys.stdout.flush()
if sysconfig.get_config_var('MACHDEP') == 'darwin' :
cmd = ["c++", "-bundle", "-undefined", "dynamic_lookup"]
else :
cmd = ["c++", "-shared", "-Wl,-Bsymbolic"]
cmd.extend(["-o", "_blst.so", "-fPIC",
"-I"+sysconfig.get_config_var('INCLUDEPY'), "-I..",
"-O", "-Wall", "blst_wrap.cpp", "../libblst.a"])
subprocess.check_call(cmd)
print("testing...")
########################################################################
import blst
msg = b"assertion" # this what we're signing
DST = b"MY-DST" # domain separation tag
SK = blst.SecretKey()
SK.keygen(b"*"*32) # secret key
########################################################################
# generate public key and signature
pk_for_wire = blst.P1(SK).serialize()
# optional vvvvvvvvvvv augmentation
sig_for_wire = blst.P2().hash_to(msg, DST, pk_for_wire) \
.sign_with(SK) \
.serialize()
########################################################################
# at this point 'pk_for_wire', 'sig_for_wire' and 'msg' are
# "sent over network," so now on "receiver" side
sig = blst.P2_Affine(sig_for_wire)
pk = blst.P1_Affine(pk_for_wire)
if not pk.in_group() : # vet the public key
raise AssertionError("disaster")
ctx = blst.Pairing(True, DST)
ctx.aggregate(pk, sig, msg, pk_for_wire)
ctx.commit()
if not ctx.finalverify() :
raise AssertionError("disaster")
########################################################################
# generate public key and signature
pk_for_wire = blst.P2(SK).serialize()
# optional vvvvvvvvvvv augmentation
sig_for_wire = blst.P1().hash_to(msg, DST, pk_for_wire) \
.sign_with(SK) \
.serialize()
########################################################################
# at this point 'pk_for_wire', 'sig_for_wire' and 'msg' are
# "sent over network," so now on "receiver" side
sig = blst.P1_Affine(sig_for_wire)
pk = blst.P2_Affine(pk_for_wire)
if not pk.in_group() : # vet the public key
raise AssertionError("disaster")
ctx = blst.Pairing(True, DST)
ctx.aggregate(pk, sig, msg, pk_for_wire)
ctx.commit()
if not ctx.finalverify() :
raise AssertionError("disaster")
if sys.version_info.major < 3:
print("OK")
sys.exit(0)
########################################################################
# from https://github.com/supranational/blst/issues/5
pk_for_wire = bytes.fromhex("ab10fc693d038b73d67279127501a05f0072cbb7147c68650ef6ac4e0a413e5cabd1f35c8711e1f7d9d885bbc3b8eddc")
sig_for_wire = bytes.fromhex("a44158c08c8c584477770feec2afa24d5a0b0bab2800414cb9efbb37c40339b6318c9349dad8de27ae644376d71232580ff5102c7a8579a6d2627c6e40b0ced737a60c66c7ebd377c04bf5ac957bf05bc8b6b09fbd7bdd2a7fa1090b5a0760bb")
msg = bytes.fromhex("0000000000000000000000000000000000000000000000000000000000000000")
DST = bytes.fromhex("424c535f5349475f424c53313233383147325f584d443a5348412d3235365f535357555f524f5f504f505f")
sig = blst.P2_Affine(sig_for_wire)
pk = blst.P1_Affine(pk_for_wire)
if not pk.in_group() : # vet the public key
raise AssertionError("disaster")
if sig.core_verify(pk, True, msg, DST) != blst.BLST_SUCCESS :
raise AssertionError("disaster")
########################################################################
# test vectors from draft-irtf-cfrg-hash-to-curve
try:
import json
import glob
coord = re.compile(r'0x([0-9a-f]+)(?:\s*,\s*0x([0-9a-f]+))?', re.IGNORECASE)
def serialize_json_point(P):
ret = b''
x = coord.search(P['x'])
if x.group(2):
ret += bytes.fromhex(x.group(2))
ret += bytes.fromhex(x.group(1))
y = coord.search(P['y'])
if y.group(2):
ret += bytes.fromhex(y.group(2))
ret += bytes.fromhex(y.group(1))
return ret
for file in glob.glob("../vectors/hash_to_curve/*.json"):
print(file)
data = json.load(open(file))
if data['curve'] == "BLS12-381 G1":
point = blst.P1()
else:
point = blst.P2()
DST = bytes(data['dst'], 'ascii')
if data['randomOracle']:
func = "point.hash_to(msg, DST).serialize()"
else:
func = "point.encode_to(msg, DST).serialize()"
for vec in data['vectors']:
msg = bytes(vec['msg'], 'ascii')
if eval(func) != serialize_json_point(vec['P']):
raise AssertionError(msg)
except ModuleNotFoundError:
print("skipping hash-to-curve KATs")
########################################################################
# test multi-scalar multiplication for self-consistency
points = []
scalars = []
total = 0
for _ in range(0, 42):
p = os.urandom(8)
s = int.from_bytes(os.urandom(8), "big")
points.append(blst.G1().mult(p))
scalars.append(s)
total += s * int.from_bytes(p, "little")
a = blst.P1s.mult_pippenger(blst.P1s.to_affine(points), scalars)
if not a.is_equal(blst.G1().mult(total)):
raise AssertionError("disaster")
points = []
scalars = []
total = 0
for _ in range(0, 42):
p = os.urandom(8)
s = int.from_bytes(os.urandom(8), "big")
points.append(blst.G2().mult(p))
scalars.append(s)
total += s * int.from_bytes(p, "little")
a = blst.P2s.mult_pippenger(blst.P2s.to_affine(points), scalars)
if not a.is_equal(blst.G2().mult(total)):
raise AssertionError("disaster")
########################################################################
# rudimentary blind signature PoC
# Signer's public key
PK = blst.P1(SK).to_affine()
# User wants to have |msg| signed, chooses random |r|,
r = blst.Scalar().from_bendian(os.urandom(32))
# blinds the H(|msg|) with |r| and sends it to the Signer.
sig_for_wire = blst.P2().hash_to(msg, DST).sign_with(r).serialize()
# Signer signs and sends the result back to the User.
sig_for_wire = blst.P2(sig_for_wire).sign_with(SK).serialize()
# User unblinds the result with 1/|r| to produce the actual |signature|,
signature = blst.P2(sig_for_wire).sign_with(r.inverse()).to_affine()
# and now it can be verified as following...
ctx = blst.Pairing(True, DST)
ctx.aggregate(PK, signature, msg)
ctx.commit()
if not ctx.finalverify():
raise AssertionError("disaster")
# or as following...
C1 = blst.PT(signature)
C2 = blst.PT(blst.P2().hash_to(msg, DST).to_affine(), PK)
if not blst.PT.finalverify(C1, C2):
raise AssertionError("disaster")
########################################################################
# [a variant of] BBS+ PoC, https://eprint.iacr.org/2008/136.pdf
# Signer's public key
w = blst.P2(SK)
w_for_wire = w.compress()
msgs = ["assertion1", "assertion2", "assertion3", "assertionN"]
count = len(msgs)
g = []
for i in range(count+1):
g.append(blst.P1().hash_to(b"\0" + i.to_bytes(4, "big") +
b"\0" + count.to_bytes(4, "big"),
DST, w_for_wire))
m = []
for msg in msgs:
h = hashlib.sha512()
h.update(msg.encode('utf-8'))
m.append(blst.Scalar().from_bendian(h.digest()))
### Signing block of messages.
e = blst.Scalar().from_bendian(os.urandom(32)) # should be PRF in real life...
s = blst.Scalar().from_bendian(os.urandom(32))
a = blst.G1().add(g[0].dup().mult(s))
for i in range(count):
a.add(g[i+1].dup().mult(m[i]))
A = a.dup().sign_with(e.dup().add(SK).inverse()).to_affine()
signature = [A, e, s] # serialize to application liking
### Signature Verification.
# Verifier deserializes |signature|, recalculates |a| and verifies.
A, e, s = signature # fake deserialization
a = blst.G1().add(g[0].dup().mult(s))
for i in range(count):
a.add(g[i+1].dup().mult(m[i]))
C1 = blst.PT(blst.G2().mult(e).add(w).to_affine(), A)
C2 = blst.PT(a.to_affine())
if not blst.PT.finalverify(C1, C2):
raise AssertionError("disaster")
### Signing Committed Block of Messages.
# User creates |commitment| and sends it Signer.
s_prime = blst.Scalar().from_bendian(os.urandom(32))
commitment = g[0].dup().sign_with(s_prime)
for i in range(count):
commitment.add(g[i+1].dup().mult(m[i]))
# Signer challenges User.
# User provides proof of commitment.
# Signer verifies the proof.
# Signer signs the |commitment| and sends the |blind_signature| back.
e = blst.Scalar().from_bendian(os.urandom(32))
s_pprime = blst.Scalar().from_bendian(os.urandom(32))
A = blst.G1().add(g[0].dup().mult(s_pprime)) \
.add(commitment) \
.sign_with(e.dup().add(SK).inverse()).to_affine()
blind_signature = [A, e, s_pprime] # serialize to application liking
# User unblinds the |blind_signature| by adding |s_prime| and |s_pprime|.
signature = blind_signature.copy() # fake deserialization
signature[2].add(s_prime) # serialize to application liking
### Signature Verification.
# Verifier deserializes |signature|, recalculates |a| and verifies.
A, e, s = signature # fake deserialization
a = blst.G1().add(g[0].dup().mult(s))
for i in range(count):
a.add(g[i+1].dup().mult(m[i]))
C1 = blst.PT(blst.G2().mult(e).add(w).to_affine(), A)
C2 = blst.PT(a.to_affine())
if not blst.PT.finalverify(C1, C2):
raise AssertionError("disaster")
########################################################################
# low-order points
p11 = blst.P1(bytes.fromhex("80d1d1ffc09ffab044764f30fc9a110ca90d1d61505636cedbd76e024f03b4e562dd6beaa4b5b5435f020bcad67a1c12"))
if p11.in_group():
raise AssertionError("disaster")
if not p11.mult(11).is_inf():
raise AssertionError("disaster")
p13 = blst.P2(bytes.fromhex("808514e6f6c41ddb685cd8e351d7cb2ee891d54d5850d42c440365b15dd8ab06b53da9ebb22bc31cea2234d30499b09f01b290cae398ecc1fda3d4beb248af58bd351c3d99a5b6c770fdb54bf46b123261b55cf0762aeef2341e35e90608fc31"))
if p13.in_group():
raise AssertionError("disaster")
if not p13.mult(13).is_inf():
raise AssertionError("disaster")
print("OK")