Files

144 lines
4.7 KiB
Python

#!/usr/bin/env python3
"""Independent cross-check of bch_direct_m23_256.csv against gen_large_m.py's
pure-Python reference implementation (different bigint arithmetic from gen_bch.c).
1. Every primitive poly in the CSV is re-tested with Python is_primitive.
2. narrow_g hexes are recomputed in Python for a sample of (m,t).
Usage: python3 verify_csv.py (writes verify_csv.log)"""
import csv, sys, time
sys.path.insert(0, "/home/hatch/workspace/rssearch")
# --- verbatim reference arithmetic from gen_large_m.py ---
def pmul(a, b):
r = 0
while b:
if b & 1: r ^= a
b >>= 1; a <<= 1
return r
def pmod(a, P):
dm = P.bit_length() - 1
while a.bit_length() - 1 >= dm:
a ^= P << (a.bit_length() - 1 - dm)
return a
def pmodmul(a, b, P): return pmod(pmul(a, b), P)
def pmodpow(a, e, P):
r = 1
while e:
if e & 1: r = pmodmul(r, a, P)
a = pmodmul(a, a, P); e >>= 1
return r
def pgcd(a, b):
while b:
a, b = b, pmod(a, b)
return a
def prime_divisors_small(n):
f = []
d = 2
while d * d <= n:
if n % d == 0:
f.append(d)
while n % d == 0: n //= d
d += 1 if d == 2 else 2
if n > 1: f.append(n)
return f
def is_primitive(P, m, N, N_factors):
x = 2
if pmodpow(x, 1 << m, P) != x:
return False
for q in prime_divisors_small(m):
if pgcd(pmodpow(x, 1 << (m // q), P) ^ x, P) != 1:
return False
for p in N_factors:
if pmodpow(x, N // p, P) == 1:
return False
return True
def narrow_g(N, t, P):
def gf_mul(a, b): return pmodmul(a, b, P)
def gf_pow(a, e): return pmodpow(a, e, P)
cosets = []
seen_rep = set()
for a in range(1, 2 * t, 2):
orb = []
x = a
while True:
orb.append(x)
x = (2 * x) % N
if x == a: break
rep = min(orb)
if rep in seen_rep: continue
seen_rep.add(rep)
cosets.append(orb)
def minpoly(orb):
s = min(orb)
betas = []
e = s
for _ in range(len(orb)):
betas.append(gf_pow(2, e)); e = (e * 2) % N
poly = [1]
for b in betas:
new = [0] * (len(poly) + 1)
for i, c in enumerate(poly):
new[i] ^= gf_mul(c, b); new[i + 1] ^= c
poly = new
assert all(c in (0, 1) for c in poly), "non-binary minpoly coeff"
v = 0
for i, c in enumerate(poly):
if c: v |= 1 << i
return v
def gf2_mul(a, b):
r = 0
while b:
if b & 1: r ^= a
b >>= 1; a <<= 1
return r
g = 1
for orb in cosets:
g = gf2_mul(g, minpoly(orb))
return g, len(cosets)
def to_hex(v):
nb = (v.bit_length() + 7) // 8
return bytes((v >> (8 * i)) & 0xff for i in range(nb)).hex()
def main():
t_start = time.time()
fac = {}
for line in open("/home/hatch/workspace/rssearch/factors.txt"):
parts = line.split()
m, comp = int(parts[0]), int(parts[1])
fac[m] = (comp, [int(h, 16) for h in parts[3:]])
rows = list(csv.DictReader(open("/home/hatch/workspace/rssearch/bch_direct_m23_256.csv")))
prim_by_m = {}
for r in rows:
prim_by_m[int(r["m"])] = int.from_bytes(bytes.fromhex(r["primitive_poly_hex"]), "little")
# 1. primitivity of every P
bad_prim = []
for m in sorted(prim_by_m):
comp, primes = fac[m]
assert comp == 1, f"m={m} factors not complete!"
P = prim_by_m[m]
ok = is_primitive(P, m, 2**m - 1, primes)
if not ok:
bad_prim.append(m)
if m % 50 == 0 or m in (23, 256):
print(f"prim check m={m}: {'OK' if ok else 'FAIL'} ({time.time()-t_start:.0f}s)", flush=True)
print(f"PRIMITIVITY: {len(prim_by_m)-len(bad_prim)}/{len(prim_by_m)} pass; failures: {bad_prim}", flush=True)
# 2. narrow_g spot check
sample = [(m, t) for m in (23, 32, 64, 100, 128) for t in (1, 2, 4, 8, 16, 32)]
sample += [(m, t) for m in (200, 251, 256) for t in (1, 2, 4, 8)]
by_mt = {(int(r["m"]), int(r["t"])): r for r in rows}
bad_hex = []
for (m, t) in sample:
P = prim_by_m[m]
g, ncos = narrow_g(2**m - 1, t, P)
got = to_hex(g)
exp = by_mt[(m, t)]["hex"]
ok = got == exp
if not ok:
bad_hex.append((m, t))
print(f"hex check m={m} t={t}: {'OK' if ok else 'FAIL'} r={g.bit_length()-1} ({time.time()-t_start:.0f}s)", flush=True)
print(f"HEX SPOT CHECK: {len(sample)-len(bad_hex)}/{len(sample)} pass; failures: {bad_hex}", flush=True)
print(f"TOTAL {time.time()-t_start:.1f}s", flush=True)
return 0 if not bad_prim and not bad_hex else 1
if __name__ == "__main__":
sys.exit(main())