Repository navigation
Expand file tree
/
Copy pathtests.py
More file actions
442 lines (344 loc) · 19.1 KB
/
Copy pathtests.py
File metadata and controls
442 lines (344 loc) · 19.1 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
# Author: Brian Soltani
# Date: 08/13/2026
# Description:
# Unit tests for the concrete, single-row Binius64 MUL-reduction model.
#
# Layered bottom-up, because each layer only means anything if the one below it holds:
# 1. field_tools -- is the field right, and does the generator have full order?
# 2. mul_constraints -- does the integer statement split and recombine correctly?
# 3. gkr_tree -- does the product tree agree with a direct product, and catch tampering?
# 4. exponentiation -- does the bit-decomposed exponentiation match direct exponentiation?
# 5. mul_reduction -- completeness (honest constraints accept) and
# soundness (tampered and forged ones are rejected)
# 6. multilinear -- do the eq and MLE helpers agree with their definitions?
# 7. gkr_product -- does an honest grand-product proof verify, and is every way of
# forging one rejected?
#
# Run: python3 tests.py
import copy
import random
import unittest
from simple_binius.binary_fields import BinaryFieldElement
from multiplication_reduction.exponentiation import (
bits_to_int,
direct_exponentiate,
fixed_base_exponentiate,
fixed_base_leaves,
variable_base_exponentiate,
variable_base_leaves,
)
from multiplication_reduction.field_tools import (
FIELD_ORDER,
WORD_BITS,
field_element,
frobenius,
is_generator,
is_nonzero,
)
from multiplication_reduction.gkr_tree import (
build_product_tree,
direct_product,
root,
tree_is_consistent,
)
from multiplication_reduction.gkr_product import (
prove_and_verify,
prove_grand_product,
verify_grand_product,
)
from multiplication_reduction.mul_constraints import MulConstraint
from multiplication_reduction.mul_reduction import (
accepts,
explain_failure,
exponent_relation_holds,
run_mul_reduction,
)
from multiplication_reduction.multilinear import (
equality_evaluate,
equality_weights,
evaluate_multilinear,
interpolate,
)
from multiplication_reduction.sumcheck import Transcript
# This candidate was checked with is_generator() for this binary-field model.
TEST_GENERATOR_VALUE = 232049208081000448880823049508552026573
def int_to_bits(value: int) -> list[int]:
"""Return a 64-bit, least-significant-bit-first representation."""
return [(value >> index) & 1 for index in range(WORD_BITS)]
class TestFieldTools(unittest.TestCase):
"""Layer 1: the ambient field, its generator, and the Frobenius map."""
def test_field_element_bounds(self) -> None:
"""field_element accepts the full 128-bit range and nothing outside it."""
self.assertEqual(field_element(0), BinaryFieldElement(0))
self.assertEqual(field_element((1 << 128) - 1), BinaryFieldElement((1 << 128) - 1))
with self.assertRaises(ValueError):
field_element(-1)
with self.assertRaises(ValueError):
field_element(1 << 128)
def test_is_nonzero(self) -> None:
"""is_nonzero separates the additive identity from everything else."""
self.assertFalse(is_nonzero(BinaryFieldElement(0)))
self.assertTrue(is_nonzero(BinaryFieldElement(1)))
def test_generator_has_full_order(self) -> None:
"""The hardcoded candidate generates the whole multiplicative group, so e -> g^e is injective."""
generator = BinaryFieldElement(TEST_GENERATOR_VALUE)
self.assertTrue(is_generator(generator))
self.assertEqual(generator ** FIELD_ORDER, BinaryFieldElement(1))
def test_frobenius_is_repeated_squaring(self) -> None:
"""Frobenius^k is k squarings, and its period on a full-width element is exactly 128."""
value = BinaryFieldElement(TEST_GENERATOR_VALUE)
self.assertEqual(frobenius(value, 0), value)
self.assertEqual(frobenius(value, 1), value * value)
self.assertEqual(frobenius(value, 2), (value * value) * (value * value))
# A genuine 128-bit element, so the period really is 128 and not a proper divisor of it.
# B(13) lives in GF(2^4), where Frobenius has period 4, and would pass this vacuously.
self.assertNotEqual(frobenius(value, 64), value)
self.assertEqual(frobenius(frobenius(value, 64), 64), value)
class TestMulConstraints(unittest.TestCase):
"""Layer 2: the integer statement p * q = 2^64 * hi + lo, before any field encoding."""
def test_known_64_bit_product(self) -> None:
"""A small product fits entirely in the low word, so hi is zero and lo is the product."""
constraint = MulConstraint.from_operands(173, 201)
self.assertEqual(constraint.product(), 34_773)
self.assertEqual(constraint.hi, 0)
self.assertEqual(constraint.lo, 34_773)
self.assertEqual(constraint.recombined_product(), 34_773)
self.assertTrue(constraint.holds_over_integers())
self.assertTrue(constraint.lsb_constraint_holds())
def test_maximum_word_product(self) -> None:
"""The largest 64-bit product, (2^64 - 1)^2, splits as hi = 2^64 - 2, lo = 1."""
max_word = (1 << WORD_BITS) - 1
constraint = MulConstraint.from_operands(max_word, max_word)
self.assertEqual(constraint.hi, max_word - 1)
self.assertEqual(constraint.lo, 1)
self.assertTrue(constraint.holds_over_integers())
self.assertTrue(constraint.lsb_constraint_holds())
def test_bit_decomposition_round_trip(self) -> None:
"""Every word survives the trip out to 64 bits and back, which the exponentiation layer relies on."""
constraint = MulConstraint.from_operands(5, 10)
self.assertEqual(bits_to_int(constraint.p_bits()), constraint.p)
self.assertEqual(bits_to_int(constraint.q_bits()), constraint.q)
self.assertEqual(bits_to_int(constraint.hi_bits()), constraint.hi)
self.assertEqual(bits_to_int(constraint.lo_bits()), constraint.lo)
def test_tampered_hi_rejected(self) -> None:
"""Shifting the high half by one moves the claimed product by 2^64, which the integer check sees."""
original = MulConstraint.from_operands(173, 201)
tampered = MulConstraint(original.p, original.q, original.hi + 1, original.lo)
self.assertFalse(tampered.holds_over_integers())
def test_tampered_lo_rejected(self) -> None:
"""Same for the low half: off by one is still off."""
original = MulConstraint.from_operands(173, 201)
tampered = MulConstraint(original.p, original.q, original.hi, original.lo + 1)
self.assertFalse(tampered.holds_over_integers())
def test_wraparound_forgery_fails_integer_and_lsb_checks(self) -> None:
"""The 2^128 - 1 forgery is false over the integers and, crucially, flips the low bit."""
forged = MulConstraint.forged_wraparound_constraint()
self.assertFalse(forged.holds_over_integers())
self.assertFalse(forged.lsb_constraint_holds())
class TestProductTree(unittest.TestCase):
"""Layer 3: the 64-leaf grand product a GKR argument would run over."""
def test_tree_root_matches_direct_product(self) -> None:
"""The tree has the expected seven layers and its root is the plain product of the leaves."""
leaves = [BinaryFieldElement(index + 1) for index in range(64)]
tree = build_product_tree(leaves)
self.assertEqual([len(layer) for layer in tree.layers], [64, 32, 16, 8, 4, 2, 1])
self.assertTrue(tree_is_consistent(tree))
self.assertEqual(root(tree), direct_product(leaves))
def test_tampered_tree_is_inconsistent(self) -> None:
"""Rewriting one intermediate node breaks the parent-equals-product-of-children relation."""
leaves = [BinaryFieldElement(index + 1) for index in range(64)]
tree = build_product_tree(leaves)
tree.layers[1][0] = BinaryFieldElement(0)
self.assertFalse(tree_is_consistent(tree))
def test_tree_rejects_wrong_leaf_count(self) -> None:
"""The tree is fixed at 64 leaves, matching one machine word of exponent bits."""
with self.assertRaises(ValueError):
build_product_tree([BinaryFieldElement(1)] * 63)
class TestExponentiation(unittest.TestCase):
"""Layer 4: turning a 64-bit exponent into 64 multiplicands, checked against direct exponentiation."""
def test_bits_to_int_rejects_bad_input(self) -> None:
"""Wrong length and non-binary entries are both rejected, since bits_to_int doubles as validation."""
with self.assertRaises(ValueError):
bits_to_int([0] * 63)
with self.assertRaises(ValueError):
bits_to_int([0] * 63 + [2])
def test_fixed_base_matches_direct_exponentiation(self) -> None:
"""The 64-leaf grand product must agree with g^e for a public base, at both ends of the range."""
generator = BinaryFieldElement(TEST_GENERATOR_VALUE)
for exponent in (0, 1, 5, (1 << 63) + 17):
bits = int_to_bits(exponent)
leaves = fixed_base_leaves(generator, bits)
self.assertEqual(len(leaves), 64)
self.assertEqual(fixed_base_exponentiate(generator, bits), direct_exponentiate(generator, exponent))
def test_variable_base_matches_direct_exponentiation(self) -> None:
"""Same for a witness base, the case that appears as Q = P^q."""
base = BinaryFieldElement(13)
for exponent in (0, 1, 5, (1 << 63) + 17):
bits = int_to_bits(exponent)
leaves = variable_base_leaves(base, bits)
self.assertEqual(len(leaves), 64)
self.assertEqual(variable_base_exponentiate(base, bits), direct_exponentiate(base, exponent))
class TestMulReduction(unittest.TestCase):
"""Layer 5: the reduction itself, both completeness and soundness."""
@classmethod
def setUpClass(cls) -> None:
"""Builds the generator once. Verifying a generator costs a handful of 128-bit exponentiations."""
cls.generator = BinaryFieldElement(TEST_GENERATOR_VALUE)
def test_valid_constraint_accepts(self) -> None:
"""Completeness: an honest constraint satisfies the exponent identity and is accepted."""
constraint = MulConstraint.from_operands(173, 201)
trace = run_mul_reduction(constraint, self.generator)
self.assertTrue(exponent_relation_holds(trace))
self.assertTrue(accepts(constraint, self.generator))
self.assertEqual(explain_failure(constraint, self.generator), "valid MUL constraint")
def test_tampered_high_half_rejects(self) -> None:
"""Soundness: an altered hi lands on a different exponent, so the field identity breaks."""
original = MulConstraint.from_operands(173, 201)
tampered = MulConstraint(original.p, original.q, original.hi + 1, original.lo)
self.assertFalse(accepts(tampered, self.generator))
self.assertEqual(explain_failure(tampered, self.generator), "exponent relation failed")
def test_tampered_low_half_rejects(self) -> None:
"""Same for an altered lo."""
original = MulConstraint.from_operands(173, 201)
tampered = MulConstraint(original.p, original.q, original.hi, original.lo + 1)
self.assertFalse(accepts(tampered, self.generator))
self.assertEqual(explain_failure(tampered, self.generator), "exponent relation failed")
def test_wraparound_passes_exponent_relation_but_rejects(self) -> None:
"""
The one forgery the field identity cannot see. Claiming 2^128 - 1 is claiming 0 modulo the
group order, so the exponent relation holds; the low-bit check is what rejects it.
"""
forged = MulConstraint.forged_wraparound_constraint()
trace = run_mul_reduction(forged, self.generator)
self.assertTrue(exponent_relation_holds(trace))
self.assertFalse(accepts(forged, self.generator))
self.assertEqual(
explain_failure(forged, self.generator),
"wraparound ambiguity rejected by LSB",
)
def test_random_valid_constraints(self) -> None:
"""Completeness on random operands, seeded so a failure is reproducible."""
rng = random.Random(20260812)
# Keep this small: each trial performs real 128-bit field exponentiations.
for _ in range(5):
p = rng.randrange(1 << WORD_BITS)
q = rng.randrange(1 << WORD_BITS)
constraint = MulConstraint.from_operands(p, q)
self.assertTrue(accepts(constraint, self.generator))
class TestMultilinear(unittest.TestCase):
"""Layer 6: the eq and multilinear-extension helpers the GKR argument is built out of."""
def setUp(self) -> None:
"""Fresh seeded RNG per test, so each one is reproducible on its own."""
self.rng = random.Random(20260812)
def random_element(self) -> BinaryFieldElement:
"""A full-width random field element."""
return BinaryFieldElement(self.rng.getrandbits(128))
def test_equality_weights_match_the_product_form(self) -> None:
"""Entry w of the eq table is the product of point_i or its complement, bit by bit."""
point = [self.random_element() for _ in range(3)]
weights = equality_weights(point)
self.assertEqual(len(weights), 8)
for index in range(8):
expected = BinaryFieldElement(1)
for i, coordinate in enumerate(point):
bit = (index >> i) & 1
expected = expected * (coordinate if bit else BinaryFieldElement(1) - coordinate)
self.assertEqual(weights[index], expected)
def test_multilinear_extension_interpolates_the_corners(self) -> None:
"""On the hypercube the extension reproduces the table, least significant bit first."""
values = [self.random_element() for _ in range(8)]
for index in range(8):
corner = [BinaryFieldElement((index >> i) & 1) for i in range(3)]
self.assertEqual(evaluate_multilinear(values, corner), values[index])
def test_multilinear_extension_is_the_eq_weighted_sum(self) -> None:
"""Off the hypercube it is the eq-weighted sum, which is what makes sumcheck work."""
values = [self.random_element() for _ in range(8)]
point = [self.random_element() for _ in range(3)]
weights = equality_weights(point)
weighted = sum([weights[i] * values[i] for i in range(8)], BinaryFieldElement(0))
self.assertEqual(evaluate_multilinear(values, point), weighted)
def test_equality_evaluate_agrees_with_the_table(self) -> None:
"""The verifier's linear-time eq must agree with the prover's exponential-size table."""
point = [self.random_element() for _ in range(4)]
weights = equality_weights(point)
for index in range(16):
corner = [BinaryFieldElement((index >> i) & 1) for i in range(4)]
self.assertEqual(equality_evaluate(point, corner), weights[index])
def test_interpolate_recovers_a_cubic(self) -> None:
"""Four points determine the degree-three round polynomials, so this must be exact."""
coefficients = [self.random_element() for _ in range(4)]
def evaluate(x: BinaryFieldElement) -> BinaryFieldElement:
total = BinaryFieldElement(0)
for power, coefficient in enumerate(coefficients):
term = coefficient
for _ in range(power):
term = term * x
total += term
return total
samples = [evaluate(BinaryFieldElement(i)) for i in range(4)]
point = self.random_element()
self.assertEqual(interpolate(samples, point), evaluate(point))
class TestGrandProduct(unittest.TestCase):
"""
Layer 7: the GKR argument. Completeness is one test; the rest are the ways a prover could
try to forge a proof, since a grand-product argument that accepts anything is worthless.
"""
def setUp(self) -> None:
"""Builds a tree over random 128-bit leaves and an honest proof of it."""
self.rng = random.Random(20260812)
self.leaves = [BinaryFieldElement(self.rng.getrandbits(128)) for _ in range(64)]
self.tree = build_product_tree(self.leaves)
self.proof = prove_grand_product(self.tree, Transcript())
def rejects(self, forged) -> bool:
"""
Whether a forged proof fails. A proof only counts as accepted if verification passes AND
the leaf claim it lands on is the true one, since the protocol deliberately stops one
step short of the leaves.
"""
accepted, point, claim = verify_grand_product(forged, len(self.tree.layers), Transcript())
if not accepted:
return True
return evaluate_multilinear(self.tree.layers[0], point) != claim
def test_honest_proof_verifies(self) -> None:
"""Completeness, including the final leaf-evaluation check."""
self.assertTrue(prove_and_verify(self.tree))
def test_layer_shape(self) -> None:
"""One layer proof per level below the root, with round counts 0, 1, 2, ... down the tree."""
self.assertEqual(len(self.proof.layers), len(self.tree.layers) - 1)
self.assertEqual([len(layer.round_polynomials) for layer in self.proof.layers],
list(range(len(self.tree.layers) - 1)))
def test_forged_root_rejected(self) -> None:
"""Claiming a different product breaks the very first sumcheck."""
forged = copy.deepcopy(self.proof)
forged.claimed_root = forged.claimed_root + BinaryFieldElement(1)
self.assertTrue(self.rejects(forged))
def test_forged_round_polynomial_rejected(self) -> None:
"""g(0) + g(1) must equal the running claim, so any altered round is caught."""
forged = copy.deepcopy(self.proof)
forged.layers[3].round_polynomials[0][0] = BinaryFieldElement(12345)
self.assertTrue(self.rejects(forged))
def test_forged_child_value_rejected(self) -> None:
"""The two child values are pinned by the sumcheck's final eq * left * right check."""
forged = copy.deepcopy(self.proof)
forged.layers[4].left = forged.layers[4].left + BinaryFieldElement(1)
self.assertTrue(self.rejects(forged))
def test_truncated_sumcheck_rejected(self) -> None:
"""Dropping a round would leave the claim on a shorter point, so the count is checked."""
forged = copy.deepcopy(self.proof)
forged.layers[5].round_polynomials.pop()
self.assertTrue(self.rejects(forged))
def test_padded_sumcheck_rejected(self) -> None:
"""Extra rounds are rejected by the same count check."""
forged = copy.deepcopy(self.proof)
forged.layers[2].round_polynomials.append([BinaryFieldElement(0)] * 4)
self.assertTrue(self.rejects(forged))
def test_proof_does_not_carry_the_leaves(self) -> None:
"""
The verifier finishes holding a claim about the leaf polynomial, not the leaves. That is
the property a polynomial commitment would build on, so it is worth pinning down.
"""
accepted, point, _ = verify_grand_product(self.proof, len(self.tree.layers), Transcript())
self.assertTrue(accepted)
self.assertEqual(len(point), 6) # log2(64), one coordinate per tree layer
if __name__ == "__main__":
unittest.main(verbosity=2)