#!/usr/bin/env python3 """Standalone exact-arithmetic verifier for spsp-psi20 (Hexagon ancillary). Runs the printed Section 1 Python witness box verbatim (when ../main.tex is present) and verifies all 12 Pratt certificate nodes, all 21 strong tests, the exact (10^36, 10^37] input interval, the first-wheel CRT products, the Jacobsthal b mod 8 cell identities for all odd primes 3 <= b <= 73, and the Bleichenbacher (1996) witness ratio. """ # Standard Library import argparse from collections import Counter from math import gcd, isqrt, prod from pathlib import Path import re P1 = 1113813905784150541 Q1 = 2 * P1 - 1 P2 = 1726253494836549181 Q2 = 2 * P2 - 1 PRATT_CERTS = { 13697: (3, [2, 2, 2, 2, 2, 2, 2, 107]), 82183: (21, [2, 3, 13697]), 634511: (11, [2, 5, 107, 593]), 620551759: (6, [2, 3, 163, 634511]), 18563565096402509: (2, [2, 2, 7, 13, 82183, 620551759]), P1: (2, [2, 2, 3, 5, 18563565096402509]), Q1: (101, [2, 2, 2, 3, 5, 18563565096402509]), 52543: (3, [2, 3, 3, 3, 7, 139]), 2101721: (3, [2, 2, 2, 5, 52543]), 158955202102813: (2, [2, 2, 3, 61, 277, 373, 2101721]), P2: (10, [2, 2, 3, 5, 181, 158955202102813]), Q2: (89, [2, 2, 2, 3, 5, 181, 158955202102813]), } def is_small_prime(n): """Exact trial-division primality check for small leaf primes.""" if n < 2: return False if n % 2 == 0: return n == 2 d = 3 while d * d <= n: if n % d == 0: return False d += 2 return True def verify_pratt(p, cache): """Verify Pratt certificate recursively; small leaves by trial division.""" if p in cache: return True if p not in PRATT_CERTS: assert p < 10000 and is_small_prime(p), f'unverified leaf {p}' cache.add(p) return True witness, factors = PRATT_CERTS[p] assert p >= 2 assert prod(factors) == p - 1, f'product mismatch for {p}' assert pow(witness, p - 1, p) == 1, f'Fermat fail for {p}' for q in sorted(set(factors)): verify_pratt(q, cache) assert pow(witness, (p - 1) // q, p) != 1, ( f'order check fail for {p}, factor {q}' ) cache.add(p) return True def v2(m): """Return (2-adic valuation, odd part) of positive integer m.""" s = 0 while m % 2 == 0: m //= 2 s += 1 return s, m def is_sprp(n, a): """Exact Miller-Rabin strong probable prime test for odd n >= 3.""" if n < 3 or n % 2 == 0: return False a_mod = a % n if a_mod == 0: return True if gcd(a_mod, n) > 1: return False s, d = v2(n - 1) x = pow(a_mod, d, n) if x == 1 or x == n - 1: return True for _ in range(s - 1): x = (x * x) % n if x == n - 1: return True return False def legendre(a, p): """Return Legendre symbol (a/p) in {-1, 0, 1} for odd prime p.""" r = pow(a % p, (p - 1) // 2, p) return -1 if r == p - 1 else r def check(tex_path=None): """Execute Section 1 witness box (if TeX present) and all exact checks.""" if not __debug__: raise RuntimeError('Run this verifier without Python optimization.') if tex_path is None: cand = Path(__file__).resolve().parent.parent / 'main.tex' if cand.exists(): tex_path = cand source = None if tex_path is not None and tex_path.exists(): source = tex_path.read_text(encoding='utf-8') matches = re.findall( r'\\begin\{Verbatim\}(?:\[[^\]]*\])?\n(.*?)\\end\{Verbatim\}', source, flags=re.DOTALL, ) assert len(matches) == 1, ( f'Expected exactly 1 Verbatim Python box, got {len(matches)}' ) exec(compile(matches[0], str(tex_path), 'exec'), {}) box_msg = ( 'Printed Section 1 Python box executed verbatim: ' 'both products pass 2..71, fail strong 73, pass Fermat 73.' ) else: bases = ( 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, ) for p in (P1, P2): n = p * (2 * p - 1) d, rem = divmod(n - 1, 4) assert rem == 0 and d % 2 == 1 and 1 < p < n < 2**127 assert all(is_sprp(n, b) for b in bases) assert not is_sprp(n, 73) and pow(73, n - 1, n) == 1 box_msg = ( 'Standalone witness check passed: ' 'both products pass 2..71, fail strong 73, pass Fermat 73.' ) primes = (P1, P2) products = tuple(p * (2 * p - 1) for p in primes) first_20 = [p for p in range(2, 72) if is_small_prime(p)] assert len(first_20) == 20 and first_20[-1] == 71 cache = set() for p, product, bits in zip(primes, products, (121, 123)): for r in (p, 2 * p - 1): assert verify_pratt(r, cache) assert product.bit_length() == bits if source is not None: assert str(product) in source assert (1 << (bits - 1)) < product < (1 << bits) assert all(is_sprp(product, b) for b in first_20) assert not is_sprp(product, 73) assert pow(73, product - 1, product) == 1 assert len(PRATT_CERTS) == 12 assert len(set(PRATT_CERTS) & cache) == 12 first_wheel = [p for p in range(3, 32) if is_small_prime(p)] admissible = [] for b in first_wheel: residues = {x * x % b for x in range(1, b)} count = sum((2 * x - 1) % b in residues for x in range(1, b)) assert count == (b - 2 - legendre(-1, b)) // 2 admissible.append(count) assert 4 * prod(first_wheel) == 401120980260 assert prod(admissible) == 10135125 for b in [p for p in range(3, 74) if is_small_prime(p)]: n_mp = sum( legendre(x, b) == -1 and legendre(2 * x - 1, b) == 1 for x in range(1, b) ) n_pp = sum( legendre(x, b) == 1 and legendre(2 * x - 1, b) == 1 for x in range(1, b) ) assert 4 * n_mp == b - 2 - legendre(-1, b) + 2 * legendre(2, b) assert 4 * n_pp == b - 2 - legendre(-1, b) - 2 * legendre(2, b) lower_root, upper_root = ( (1 + isqrt(1 + 8 * limit)) // 4 for limit in (10**36, 10**37) ) assert upper_root - lower_root == 1528961196313242172 older = 29097303612595780926342159603334420097591 assert (2 * older + products[0]) // (2 * products[0]) == 11727 print(box_msg) print( 'All 12 Pratt certificate nodes verified. ' 'Product sizes: 121 bits (n1) and 123 bits (n2).' ) print('Exact input interval (10^36, 10^37]: 1528961196313242172 integers p.') print( 'First wheel (4 and odd primes 3..31): ' '10135125 classes modulo 401120980260.' ) print('Jacobsthal b mod 8 cell counts verified for all odd primes 3 <= b <= 73.') print('Ratio of Bleichenbacher 1996 witness to n1: 11727 (rounded).') def replay_shards(outdir): """Aggregate all 1,024 archived shard summaries.""" visited = set() totals = Counter() for path in outdir.glob('band-*/*.txt'): lines = path.read_text(encoding='utf-8').splitlines() summary, = [line for line in lines if line.startswith('summary ')] fields = dict(re.findall(r'(\w+)=([0-9]+)', summary)) shard = int(fields['shard']) assert shard not in visited and int(fields['nshards']) == 1024 assert fields['complete'] == '1' and fields['disagree'] == '0' visited.add(shard) for key in ('candidates', 'both', 'F20', 'F21'): totals[key] += int(fields[key]) assert visited == set(range(1024)) assert totals == dict( candidates=52613846073, both=1809514692, F20=2, F21=0 ) print( 'All 1024 archived shard summaries present: ' '52613846073 candidates, 1809514692 prime pairs, 2 hits.' ) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( '-s', '--shards', type=Path, metavar='DIR', help='also replay band-XX/*.txt summaries under DIR', ) parser.add_argument( '-t', '--tex', type=Path, metavar='FILE', help='path to main.tex for verbatim Section 1 box check', ) args = parser.parse_args() check(args.tex) if args.shards is not None: replay_shards(args.shards)