-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_sympy_examples.py
370 lines (330 loc) · 11.8 KB
/
generate_sympy_examples.py
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
from sympy import Symbol, Poly, gcd as sympy_gcd, gcdex as sympy_gcdex
import random
import math
def sample_polynomial(indeterminate, degree, modulus):
"""Sample a polynomial up to the specified degree, with coefficients in the
specified modulus
"""
expr = 0
for p in range(degree + 1):
coeff = random.randint(0, modulus - 1)
term = coeff * (indeterminate**p)
expr += term
return Poly(expr, modulus=modulus)
def hex_encode_coeffs(poly, gf_bits):
"""Convert the coefficients of polynomial into a left-padded hexadecimal
string. Coeff of higher-power term will be encoded at the beginning of the
string
For example:
in GF(2 ** 128), the polynomial (x ** 16 + 1) will be encoded as:
0x0000_0000_0000_0000_0000_0000_0001_0001
"""
digits = math.ceil(gf_bits / 4)
encoding_num = 0
for p in range(gf_bits):
if poly.as_expr().coeff(Symbol("x"), p):
encoding_num += 2**p
hex_str = f"{encoding_num:X}"
pad = digits - len(hex_str)
hex_str = "0" * pad + hex_str
return hex_str
def convert_to_limbs(hex_str, word_bits) -> list[str]:
"""Split the hexadecimal string according to word size in bits"""
assert (word_bits % 4) == 0, "Word bits must be multiples of 4"
word_hex_size = word_bits // 4
i = 0
limbs = []
while i + word_hex_size <= len(hex_str):
limb = hex_str[i : i + word_hex_size]
limbs.append(f"0x{limb}")
i += word_hex_size
return limbs
def generate_extfield_widening_mul(gf_bits: int):
lhs = sample_polynomial(Symbol("x"), gf_bits - 1, 2)
rhs = sample_polynomial(Symbol("x"), gf_bits - 1, 2)
prod = lhs * rhs
lhs_limbs = convert_to_limbs(hex_encode_coeffs(lhs, gf_bits), 16)
lhs_str = ", ".join(lhs_limbs)
rhs_limbs = convert_to_limbs(hex_encode_coeffs(rhs, gf_bits), 16)
rhs_str = ", ".join(rhs_limbs)
prod_limbs = convert_to_limbs(hex_encode_coeffs(prod, gf_bits * 2), 16)
prod_high_tokens = prod_limbs[: len(prod_limbs) // 2]
prod_low_tokens = prod_limbs[len(prod_limbs) // 2 :]
prod_high_str = ", ".join(prod_high_tokens)
prod_low_str = ", ".join(prod_low_tokens)
print(
f"""
let lhs = GF_2_{gf_bits}::from_limbs([
{lhs_str}
]);
let rhs = GF_2_{gf_bits}::from_limbs([
{rhs_str}
]);
let prod = (
GF_2_{gf_bits}::from_limbs([
{prod_high_str}
]),
GF_2_{gf_bits}::from_limbs([
{prod_low_str}
]),
);
assert_eq!(lhs.widening_gf_mul(&rhs), prod);"""
)
def random_f2x_checked_mul(gf_bits: int):
lhs = sample_polynomial(Symbol("x"), gf_bits // 2 - 1, 2)
rhs = sample_polynomial(Symbol("x"), gf_bits // 2 - 1, 2)
prod = lhs * rhs
lhs_limbs = convert_to_limbs(hex_encode_coeffs(lhs, gf_bits), 16)
lhs_str = ", ".join(lhs_limbs)
rhs_limbs = convert_to_limbs(hex_encode_coeffs(rhs, gf_bits), 16)
rhs_str = ", ".join(rhs_limbs)
prod_limbs = convert_to_limbs(hex_encode_coeffs(prod, gf_bits), 16)
prod_str = ", ".join(prod_limbs)
print(
f"""
let lhs = F2_128::from_limbs([
{lhs_str}
]);
let rhs = F2_128::from_limbs([
{rhs_str}
]);
let prod = F2_128::from_limbs([
{prod_str}
]);
assert_eq!(lhs.checked_mul(&rhs).unwrap(), prod);
"""
)
def generate_short_euclidean_division(gf_bits: int):
lhs = sample_polynomial(Symbol("x"), gf_bits - 1, 2)
rhs = sample_polynomial(Symbol("x"), (gf_bits - 1) // 2, 2)
rem = lhs % rhs
quot = (lhs - rem) // rhs
assert (rhs * quot + rem) == lhs
lhs_limbs = convert_to_limbs(hex_encode_coeffs(lhs, gf_bits), 16)
lhs_str = ", ".join(lhs_limbs)
rhs_limbs = convert_to_limbs(hex_encode_coeffs(rhs, gf_bits), 16)
rhs_str = ", ".join(rhs_limbs)
quot_limbs = convert_to_limbs(hex_encode_coeffs(quot, gf_bits), 16)
quot_str = ", ".join(quot_limbs)
rem_limbs = convert_to_limbs(hex_encode_coeffs(rem, gf_bits), 16)
rem_str = ", ".join(rem_limbs)
print(
f""" assert_eq!(
GF_2_128::from_limbs([
{lhs_str}
]).euclidean_div(&GF_2_128::from_limbs([
{rhs_str}
])),
(GF_2_128::from_limbs([
{quot_str}
]), GF_2_128::from_limbs([
{rem_str}
]))
);"""
)
def random_gf2_128_modmul():
x = Symbol("x")
gf_bits, wordsize = 128, 16
lhs = sample_polynomial(x, gf_bits - 1, 2)
rhs = sample_polynomial(x, gf_bits - 1, 2)
gf2_128_modulus = Poly(x**128 + x**77 + x**35 + x**11 + 1, modulus=2)
lhs_limbs = convert_to_limbs(hex_encode_coeffs(lhs, gf_bits), wordsize)
lhs_str = ", ".join(lhs_limbs)
rhs_limbs = convert_to_limbs(hex_encode_coeffs(rhs, gf_bits), wordsize)
rhs_str = ", ".join(rhs_limbs)
modulus_limbs = convert_to_limbs(
hex_encode_coeffs(gf2_128_modulus, 2 * gf_bits), wordsize
)
# modulus_high_limbs = modulus_limbs[:len(modulus_limbs) // 2]
modulus_low_limbs = modulus_limbs[len(modulus_limbs) // 2 :]
modulus_low_str = ", ".join(modulus_low_limbs)
rem = lhs * rhs % gf2_128_modulus
rem_limbs = convert_to_limbs(hex_encode_coeffs(rem, 128), wordsize)
rem_str = ", ".join(rem_limbs)
# print(
# f""" let lhs = F2_128::from_limbs([
# {lhs_str}
# ]);
# let rhs = F2_128::from_limbs([
# {rhs_str}
# ]);
# let modulus = WideF2X::<8>::from_f2x(
# F2_128::ONE,
# F2_128::from_limbs([
# {modulus_low_str}
# ]),
# );
# let rem = F2_128::from_limbs([
# {rem_str}
# ]);
# assert_eq!(lhs.modmul(&rhs, &modulus), rem);"""
# )
print(
f"""
let lhs = GF2_128::from_poly(F2x::<8>::from_limbs([
{lhs_str}
]));
let rhs = GF2_128::from_poly(F2x::<8>::from_limbs([
{rhs_str}
]));
let rem = GF2_128::from_poly(F2x::<8>::from_limbs([
{rem_str}
]));
assert_eq!(lhs.mul(&rhs), rem);"""
)
def random_gf2_128_modinv():
x = Symbol("x")
gf_bits, wordsize = 128, 16
lhs = sample_polynomial(x, gf_bits - 1, 2)
gf2_128_modulus = Poly(x**128 + x**77 + x**35 + x**11 + 1, modulus=2)
inverse, _, _ = sympy_gcdex(lhs, gf2_128_modulus)
assert lhs * inverse % gf2_128_modulus == 1, "Sympy Extended GCD is incorrect"
rhs = inverse
lhs_limbs = convert_to_limbs(hex_encode_coeffs(lhs, gf_bits), wordsize)
lhs_str = ", ".join(lhs_limbs)
rhs_limbs = convert_to_limbs(hex_encode_coeffs(rhs, gf_bits), wordsize)
rhs_str = ", ".join(rhs_limbs)
print(
f"""
let lhs = GF2_128::from_poly(F2x::<8>::from_limbs([
{lhs_str}
]));
let rhs = GF2_128::from_poly(F2x::<8>::from_limbs([
{rhs_str}
]));
assert_eq!(lhs.inv().unwrap(), rhs);"""
)
def generate_f2x_gcd_test_case():
"""Sample two random polynomials and compute their GCD"""
poly1 = sample_polynomial(Symbol("x"), 127, 2)
poly2 = sample_polynomial(Symbol("x"), 127, 2)
divisor = sympy_gcd(poly1, poly2)
assert (poly1 % divisor == 0) and (poly2 % divisor == 0), "Sympy GCD is incorrect"
poly1_limbs = convert_to_limbs(hex_encode_coeffs(poly1, 128), 16)
poly1_str = ", ".join(poly1_limbs)
poly2_limbs = convert_to_limbs(hex_encode_coeffs(poly2, 128), 16)
poly2_str = ", ".join(poly2_limbs)
divisor_limbs = convert_to_limbs(hex_encode_coeffs(divisor, 128), 16)
divisor_str = ", ".join(divisor_limbs)
print(
f"""
assert_eq!(
F2_128::gcd(
&F2_128::from_limbs([
{poly1_str}
]),
&F2_128::from_limbs([
{poly2_str}
]),
),
F2_128::from_limbs([{divisor_str}])
);"""
)
def random_f2x_xgcd_test_case():
"""Sample two random polynomials and compute their GCD"""
poly1 = sample_polynomial(Symbol("x"), 127, 2)
poly2 = sample_polynomial(Symbol("x"), 127, 2)
from sympy import gcdex as sympy_xgcd
(poly_s, poly_t, divisor) = sympy_xgcd(poly1, poly2)
assert (poly1 % divisor == 0) and (poly2 % divisor == 0), "Sympy GCD is incorrect"
assert poly_s * poly1 + poly_t * poly2 == divisor, "Sympy GCD is incorrect"
poly1_limbs = convert_to_limbs(hex_encode_coeffs(poly1, 128), 16)
poly1_str = ", ".join(poly1_limbs)
poly2_limbs = convert_to_limbs(hex_encode_coeffs(poly2, 128), 16)
poly2_str = ", ".join(poly2_limbs)
poly_s_limbs = convert_to_limbs(hex_encode_coeffs(poly_s, 128), 16)
poly_s_str = ", ".join(poly_s_limbs)
poly_t_limbs = convert_to_limbs(hex_encode_coeffs(poly_t, 128), 16)
poly_t_str = ", ".join(poly_t_limbs)
divisor_limbs = convert_to_limbs(hex_encode_coeffs(divisor, 128), 16)
divisor_str = ", ".join(divisor_limbs)
print(
f"""
let lhs = F2_128::from_limbs([
{poly1_str}
]);
let rhs = F2_128::from_limbs([
{poly2_str}
]);
let expected_s = F2_128::from_limbs([
{poly_s_str}
]);
let expected_t = F2_128::from_limbs([
{poly_t_str}
]);
let expected_d = F2_128::from_limbs([
{divisor_str}
]);
let (s, t, divisor) = F2_128::xgcd(&lhs, &rhs);
assert_eq!((s, t, divisor), (expected_s, expected_t, expected_d));
"""
)
def generate_widef2x_gcd_test_case():
"""Sample two random polynomials and compute their GCD"""
poly1 = sample_polynomial(Symbol("x"), 255, 2)
poly2 = sample_polynomial(Symbol("x"), 255, 2)
divisor = sympy_gcd(poly1, poly2)
assert (poly1 % divisor == 0) and (poly2 % divisor == 0), "Sympy GCD is incorrect"
nlimbs = 256 // 16
poly1_limbs = convert_to_limbs(hex_encode_coeffs(poly1, 256), 16)
poly1_high_limbs, poly1_low_limbs = (
poly1_limbs[: nlimbs // 2],
poly1_limbs[nlimbs // 2 :],
)
poly1_high_str, poly1_low_str = ", ".join(poly1_high_limbs), ", ".join(
poly1_low_limbs
)
poly2_limbs = convert_to_limbs(hex_encode_coeffs(poly2, 256), 16)
poly2_high_limbs, poly2_low_limbs = (
poly2_limbs[: nlimbs // 2],
poly2_limbs[nlimbs // 2 :],
)
poly2_high_str, poly2_low_str = ", ".join(poly2_high_limbs), ", ".join(
poly2_low_limbs
)
divisor_limbs = convert_to_limbs(hex_encode_coeffs(divisor, 256), 16)
divisor_high_limbs, divisor_low_limbs = (
divisor_limbs[: nlimbs // 2],
divisor_limbs[nlimbs // 2 :],
)
divisor_high_str, divisor_low_str = ", ".join(divisor_high_limbs), ", ".join(
divisor_low_limbs
)
print(
f"""
let lhs = WideF2x::<8>::from_f2x(
F2x::<8>::from_limbs([
{poly1_high_str}
]),
F2x::<8>::from_limbs([
{poly1_low_str}
]),
);
let rhs = WideF2x::<8>::from_f2x(
F2x::<8>::from_limbs([
{poly2_high_str}
]),
F2x::<8>::from_limbs([
{poly2_low_str}
]),
);
let gcd = WideF2x::<8>::from_f2x(
F2x::<8>::from_limbs([
{divisor_high_str}
]),
F2x::<8>::from_limbs([
{divisor_low_str}
]),
);
assert_eq!(WideF2x::<8>::gcd(&lhs, &rhs), gcd);
"""
)
if __name__ == "__main__":
n_tests = 5
# generate_extfield_widening_mul(128)
# generate_short_euclidean_division(128)
# [random_gf2_128_modmul() for _ in range(n_tests)]
[random_gf2_128_modinv() for _ in range(n_tests)]
# generate_widef2x_gcd_test_case()
# random_f2x_xgcd_test_case()
# [random_f2x_checked_mul(128) for _ in range(5)]