"""Verify fixed-twin covering tuples directly by CRT and primorial gcds.""" import argparse from collections import Counter import hashlib import importlib.util import json import math from pathlib import Path NATAL = (5, 7, 11, 13, 17, 19, 23, 29, 31, 37) SCOUR = (41, 43, 47, 53, 59, 61, 67, 71, 73) PRIMES = NATAL+SCOUR P37 = 6*math.prod(NATAL) P73 = P37*math.prod(SCOUR) def verify(line, reference=None): parts = line.split() if (len(parts) != 24 or parts[0] != "TUPLE" or parts[20] != "length" or parts[22] != "restart"): raise ValueError("Malformed tuple record") residues = [] for token, p in zip(parts[1:20], PRIMES): r, prime = map(int, token.split("/")) if prime != p or not 0 < r < p or r == 2*pow(6, -1, p) % p: raise ValueError("Wrong prime, residue or left-boundary condition") residues.append(r) length, restart = int(parts[21]), int(parts[23]) if length < 11 or length % 6 != 5 or restart < 1: raise ValueError("Invalid covering length or restart") pairs = [(6, 5)]+[(p, -6*r % p) for p, r in zip(PRIMES, residues)] start = sum(a*(P73//p)*pow(P73//p, -1, p) for p, a in pairs) % P73 gap = length+1 end = start+gap if math.gcd(start*(start+2), P73) != 1 or math.gcd(end*(end+2), P73) != 1: raise ValueError("An advertised gap endpoint is not a T73 slot") offset = start % P37 natal_indices = [] for j in range(1, gap//6): value = start+6*j if math.gcd(value*(value+2), P73) == 1: raise ValueError("An interior T73 survivor breaks the covering") if math.gcd(value*(value+2), P37) == 1: natal_indices.append(j) slots = [offset+6*j for j in natal_indices] if reference: other = reference(dict(zip(PRIMES, residues)), length) if (other["count"] != len(slots) or other["slots"] != slots or other["modulus_6x37sharp"] != P37 or not other["all_killed"] or not other["consecutive"]): raise ValueError("The independent legacy decoder disagrees") phases = {str(p): (6*r+offset) % p for p, r in zip(PRIMES, residues) if p in SCOUR} if not all(any(x % p == phases[str(p)] or (x+2) % p == phases[str(p)] for p in SCOUR) for x in slots): raise ValueError("Normalized scour phases do not kill every natal slot") canonical = " ".join(parts[:22]) return { "key": hashlib.sha256(canonical.encode()).hexdigest(), "tuple": line.strip(), "cover_length": length, "gap_length": gap, "count": len(slots), "natal_indices": natal_indices, "natal_offset_mod_P37": offset, "natal_slots": slots, "scour_phases": phases, "full_start_mod_P73": str(start), "P37": P37, "P73": str(P73), "checks": {"both_T73_endpoints": True, "no_interior_T73_survivor": True, "all_interior_T37_slots_counted": True, "all_scoured": True, "legacy_decoder_agrees": reference is not None}, "published_gap_control_exceeded": gap > 1530, } def selftest(): residues = [1]*len(PRIMES) residues[len(NATAL)] = 2 j = 1 while any(j % p == r or (6*j+2) % p == 6*r % p for p, r in zip(PRIMES, residues)): j += 1 line = "TUPLE "+" ".join(f"{r}/{p}" for p, r in zip(PRIMES, residues)) line += f" length {6*j-1} restart 1" result = verify(line) assert result["count"] > 0 for changed in ( line.replace(f"length {6*j-1}", f"length {6*j+5}"), line.replace(f"length {6*j-1}", f"length {6*j-7}"), line.replace("1/5", "0/5"), line.replace("restart 1", "restart 0"), ): try: verify(changed) except ValueError: pass else: raise AssertionError("A malformed or false certificate was accepted") print(json.dumps({"synthetic_gap": result["gap_length"], "synthetic_interior_count": result["count"], "negative_controls": 4})) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("input", nargs="?", type=Path) parser.add_argument("--reference", type=Path) parser.add_argument("--selftest", action="store_true") args = parser.parse_args() if args.selftest: selftest() else: if args.input is None: parser.error("input is required") reference = None if args.reference: spec = importlib.util.spec_from_file_location("legacy_certificate", args.reference) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) reference = module.certificate data = args.input.read_bytes() records = [verify(line, reference) for line in data.decode().splitlines() if line.strip()] histogram = Counter(row["count"] for row in records) best = max(records, key=lambda row: row["count"], default=None) print(json.dumps({ "tuples": len(records), "input_sha256": hashlib.sha256(data).hexdigest(), "histogram": dict(sorted(histogram.items())), "best": best, "rows": [[row["key"], row["cover_length"], row["gap_length"], row["count"]] for row in records], "all_definition_checks_passed": True, "legacy_decoder_used": reference is not None, "published_gap_control_exceeded": any(row["published_gap_control_exceeded"] for row in records), }, sort_keys=True))