#!/usr/bin/env python3 """Verify the rank certificate a route handed in: exact arithmetic, standard library only. Usage: verify.py FOLDER [--metrics PATH] FOLDER/CERTIFICATE.json: {"target": "E-1" | "C-1" | "C-2", "curves": [{"label": "389a1", "ainvs": [a1, a2, a3, a4, a6], "points": [["x", "y"], ...], "torsion": [["x", "y"], ...], "chars": [[p, theta], ...]}, ...]} with x, y rationals written as strings ("3/4") and every other number an integer. For each curve the check verifies, with no floating point anywhere: * the curve is nonsingular and every point lies on it; * every torsion point has order at most 12 (Mazur), and their number is dim E(Q)[2], which the check computes itself from the rational roots of 4x^3 + b2 x^2 + 2 b4 x + b6; * every (p, theta) has p an odd prime not dividing the discriminant and theta a root of that cubic mod p; * the matrix of the characters chi_(p,theta)(P) = [x(P) - theta is not a square mod p] on the points and the torsion points has F_2-rank #points + #torsion. Each chi is the reduction E(Q) -> E(F_p) followed by the 2-descent map at the root theta, so it is a homomorphism to F_2 that kills 2E(Q) (Cremona, "Algorithms for modular elliptic curves", 3.6; the ICARM leaderboard checks ranks this way). E(Q)/2E(Q) has F_2-dimension rank + dim E(Q)[2], so independent images prove rank E(Q) >= #points. Targets: E-1 any curves: the example's target, and a way to certify any curve; C-1 the curves of rank >= 2 and conductor below 10,000 in Cremona's tables (checks/c1-curves.tsv.gz: label, a-invariants, rank); a curve counts when its label and a-invariants are listed and it has as many points as its listed rank; C-2 the three curves of rank >= 32 on the ICARM leaderboard (checks/records.json), as "icarm-", 32 points each. A certificate for another piece's target exits 0 saying no verifier exists for it: a maintainer reads it. Exit 0 with the last line "E-1: …", "C-1: of 2389 curves, rank >= r certified exactly" or "C-2: of 3 records, rank >= 32 certified exactly"; with no CERTIFICATE.json, "Nothing to check yet". Exit 1 with the first problem otherwise. With --metrics PATH, writes {"score": k, "subtasks": {"": k}}. """ from __future__ import annotations import gzip import json import math import sys from fractions import Fraction from pathlib import Path HERE = Path(__file__).resolve().parent MAX_BYTES = 8_000_000 # the whole of C-1 is about 340 KB REVIEWED = {"C-3", "C-4", "V-1", "V-2", "V-3", "V-4", "R-1", "L-1"} class Wrong(Exception): """A certificate the check refuses; its text is what the author reads.""" class NoVerifier(Exception): """A target this check does not verify; a maintainer reads the certificate instead.""" def shown(text, limit=60): clean = "".join(c if c.isprintable() else "?" for c in str(text)) return clean if len(clean) <= limit else clean[:limit] + "..." def is_prime(n: int) -> bool: if n < 2: return False for q in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): if n % q == 0: return n == q if n >= 3_317_044_064_679_887_385_961_981: # the bases below are a proof only up to here raise Wrong(f"prime {n} is too large for this check") d, s = n - 1, 0 while d % 2 == 0: d, s = d // 2, s + 1 for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37): x = pow(a, d, n) if x in (1, n - 1): continue for _ in range(s - 1): x = x * x % n if x == n - 1: break else: return False return True class Curve: def __init__(self, a): self.a1, self.a2, self.a3, self.a4, self.a6 = a a1, a2, a3, a4, a6 = a self.b2, self.b4, self.b6 = a1 * a1 + 4 * a2, 2 * a4 + a1 * a3, a3 * a3 + 4 * a6 b8 = a1 * a1 * a6 + 4 * a2 * a6 - a1 * a3 * a4 + a2 * a3 * a3 - a4 * a4 self.disc = -self.b2 ** 2 * b8 - 8 * self.b4 ** 3 - 27 * self.b6 ** 2 + 9 * self.b2 * self.b4 * self.b6 if self.disc == 0: raise Wrong("the curve is singular") def on(self, P): x, y = P return y * y + self.a1 * x * y + self.a3 * y == x ** 3 + self.a2 * x * x + self.a4 * x + self.a6 def add(self, P, Q): if P is None: return Q if Q is None: return P (x1, y1), (x2, y2) = P, Q if x1 == x2: if y1 + y2 + self.a1 * x2 + self.a3 == 0: return None lam = (3 * x1 * x1 + 2 * self.a2 * x1 + self.a4 - self.a1 * y1) / (2 * y1 + self.a1 * x1 + self.a3) else: lam = (y2 - y1) / (x2 - x1) nu = y1 - lam * x1 x3 = lam * lam + self.a1 * lam - self.a2 - x1 - x2 return (x3, -(lam + self.a1) * x3 - nu - self.a3) def cubic(self, x, p): return (4 * x ** 3 + self.b2 * x * x + 2 * self.b4 * x + self.b6) % p def two_torsion_dim(self): """dim E(Q)[2]: the rational roots of 4x^3 + b2 x^2 + 2 b4 x + b6 are x = u/4 with u an integer root of the monic g(u) = u^3 + b2 u^2 + 8 b4 u + 16 b6. g is monotone between its critical points, so each sign change on such a piece is bisected down to the two integers around it.""" c2, c1, c0 = self.b2, 8 * self.b4, 16 * self.b6 g = lambda u: ((u + c2) * u + c1) * u + c0 bound = 1 + max(abs(c2), abs(c1), abs(c0)) # Cauchy: every real root lies inside cuts = {-bound, bound} d = c2 * c2 - 3 * c1 if d >= 0: # the critical points (-c2 -+ sqrt(d)) / 3, rounded both ways r = math.isqrt(d) for centre in (-c2 - r, -c2 + r): for s in range(centre - 2, centre + 3): cuts.update((s // 3, s // 3 + 1)) cuts = sorted(min(max(c, -bound), bound) for c in cuts) roots = {u for u in cuts if g(u) == 0} for lo, hi in zip(cuts, cuts[1:]): if (g(lo) < 0) != (g(hi) < 0): while hi - lo > 1: m = (lo + hi) // 2 if (g(m) < 0) == (g(lo) < 0): lo = m else: hi = m roots.update(u for u in (lo, hi) if g(u) == 0) return {0: 0, 1: 1, 3: 2}[len(roots)] def finite_order(self, P): Q = P for _ in range(12): if Q is None: return True Q = self.add(Q, P) return Q is None def chi(self, P, p, theta): x = P[0] if x.denominator % p == 0: return 0 # P reduces to the point at infinity v = (x.numerator - theta * x.denominator) % p # the denominator is a square, so it does not change the class if v == 0: # P reduces to the 2-torsion point (theta, *): the map takes the derivative there v = (12 * theta * theta + 2 * self.b2 * theta + 2 * self.b4) % p if v == 0: raise Wrong(f"p = {p} is a bad prime") return 0 if pow(v, (p - 1) // 2, p) == 1 else 1 def f2_rank(rows): basis = {} for row in rows: while row: h = row.bit_length() - 1 if h not in basis: basis[h] = row break row ^= basis[h] return len(basis) def rational(s, where): if not isinstance(s, str): raise Wrong(f"{where}: write coordinates as strings, such as \"3/4\"") try: return Fraction(s) except (ValueError, ZeroDivisionError): raise Wrong(f"{where}: {shown(s)} is not a rational number") from None def ainvs_of(c, label): a = c.get("ainvs") if not (isinstance(a, list) and len(a) == 5 and all(type(v) is int for v in a)): raise Wrong(f"{label}: ainvs must be five integers") return a def certified(c) -> int: """The rank lower bound one curve's entry proves: its number of points, once every condition holds.""" label = shown(c.get("label", "?"), 40) E = Curve(ainvs_of(c, label)) for key in ("points", "torsion", "chars"): if not isinstance(c.get(key, []), list) or not all(isinstance(P, list) and len(P) == 2 for P in c.get(key, [])): raise Wrong(f"{label}: {key} must be a list of pairs") pts = [tuple(rational(v, label) for v in P) for P in c.get("points", [])] tors = [tuple(rational(v, label) for v in P) for P in c.get("torsion", [])] for P in pts + tors: if not E.on(P): raise Wrong(f"{label}: ({', '.join(shown(v, 30) for v in P)}) is not on the curve") for T in tors: if not E.finite_order(T): raise Wrong(f"{label}: the torsion point ({shown(T[0], 30)}, {shown(T[1], 30)}) has no order up to 12") t2 = E.two_torsion_dim() if len(tors) != t2: raise Wrong(f"{label}: give {t2} torsion point(s) whose images span E(Q)_tors/2, found {len(tors)}") rows = [0] * (len(pts) + len(tors)) for j, ch in enumerate(c.get("chars", [])): if not all(type(v) is int for v in ch): raise Wrong(f"{label}: a character is [p, theta], two integers") p, theta = ch if not (p > 2 and is_prime(p)): raise Wrong(f"{label}: the character {ch} needs an odd prime p") if E.disc % p == 0: raise Wrong(f"{label}: p = {p} divides the discriminant") if E.cubic(theta, p) != 0: raise Wrong(f"{label}: {theta} is not a root of 4x^3 + b2 x^2 + 2 b4 x + b6 mod {p}") for i, P in enumerate(pts + tors): rows[i] |= E.chi(P, p, theta) << j got = f2_rank(rows) if got != len(rows): raise Wrong(f"{label}: the characters' matrix has F_2-rank {got}, not {len(rows)}: the points are not shown independent") return len(pts) def listed(target): """The curves a target counts: label -> (a-invariants, the rank a certificate must reach).""" if target == "C-1": with gzip.open(HERE / "c1-curves.tsv.gz", "rt", encoding="utf-8") as f: rows = [line.split("\t") for line in f if line.strip()] return {r[0]: ([int(v) for v in r[1].split(",")], int(r[2])) for r in rows} records = json.loads((HERE / "records.json").read_text(encoding="utf-8"))["records"] return {f"icarm-{r['id']}": ([int(v) for v in r["ainvs"]], r["rank"]) for r in records} def judge(cert): target = cert.get("target") if target in REVIEWED: raise NoVerifier(target) if target not in ("E-1", "C-1", "C-2"): raise Wrong(f"unknown target {shown(target)}: E-1, C-1 and C-2 are checked here (docs/submission.md)") curves = cert.get("curves") if not isinstance(curves, list) or not curves: raise Wrong("curves must be a list of at least one curve") labels = [c.get("label") if isinstance(c, dict) else None for c in curves] if any(not isinstance(l, str) for l in labels): raise Wrong("every curve needs a label") seen = set() for l in labels: if l in seen: raise Wrong(f"{shown(l, 40)} is listed twice") seen.add(l) if target == "E-1": ranks = [certified(c) for c in curves] hist = ", ".join(f"{ranks.count(r)} with r = {r}" for r in sorted(set(ranks))) return len(ranks), f"E-1: {len(ranks)} curve{'s' if len(ranks) != 1 else ''}, rank >= r certified exactly for {hist}" want, k = listed(target), 0 for c in curves: label = c["label"] if label not in want: raise Wrong(f"{shown(label, 40)} is not one of {target}'s curves (checks/{'c1-curves.tsv.gz' if target == 'C-1' else 'records.json'})") a, rank = want[label] if ainvs_of(c, shown(label, 40)) != a: raise Wrong(f"{shown(label, 40)}: its a-invariants are not the listed ones") if certified(c) < rank: raise Wrong(f"{shown(label, 40)}: {target} needs rank >= {rank}, that is {rank} points") k += 1 if target == "C-1": return k, f"C-1: {k} of {len(want)} curves, rank >= r certified exactly" return k, f"C-2: {k} of {len(want)} records, rank >= 32 certified exactly" def main(argv): args = argv[1:] metrics = None if "--metrics" in args: i = args.index("--metrics") metrics = args[i + 1] if i + 1 < len(args) else None del args[i:i + 2] if len(args) != 1 or (metrics is None and "--metrics" in argv): print("usage: verify.py FOLDER [--metrics PATH]", file=sys.stderr) return 2 path = Path(args[0]) / "CERTIFICATE.json" if not path.is_file(): print("Nothing to check yet: no CERTIFICATE.json in the route's folder") return 0 if path.stat().st_size > MAX_BYTES: print(f"FAILED CERTIFICATE.json is over {MAX_BYTES:,} bytes", file=sys.stderr) return 1 try: cert = json.loads(path.read_text(encoding="utf-8")) if not isinstance(cert, dict): raise Wrong("CERTIFICATE.json must hold an object") k, line = judge(cert) except NoVerifier as e: print(f"no automatic verifier for {e} yet: a maintainer reads this certificate") return 0 except (Wrong, ValueError) as e: print(f"FAILED {e}", file=sys.stderr) return 1 print(line) if metrics: Path(metrics).write_text(json.dumps({"score": k, "subtasks": {cert["target"]: k}}) + "\n") return 0 if __name__ == "__main__": sys.exit(main(sys.argv))