"""Verify Giraudin's two tile comparisons from coordinates, configurations and flows. Python 3.10+. No imports from the certificate generator or proof author's code. """ import argparse from collections import Counter, defaultdict from functools import lru_cache from hashlib import sha256 from itertools import combinations, product import json from math import lcm from pathlib import Path import platform import sys from time import perf_counter def require(ok, reason): if not ok: raise ValueError(reason) def adjacent(first, second, graph, offset): x, y = first u, v = second dx, dy = abs(u - x), abs(v - y) if dx + dy == 1: return True if (dx, dy) != (1, 1): return False i = (min(x, u) + offset[0]) % 2 j = (min(y, v) + offset[1]) % 2 return (graph == 'LG' and i == j) or (graph == 'H' and i == j == 1) def sym(point, w, k): x, y = point if k >= 4: x, y = y, x if k & 1: x = w - 1 - x if k & 2: y = w - 1 - y return x, y def geometry(w, graph, offset): sites = [(x, y) for y in range(w) for x in range(w)] inside = set(sites) outside = set(product(range(-1, w + 1), repeat=2)) - inside edges = {frozenset((u, v)) for u, v in combinations(sites, 2) if adjacent(u, v, graph, offset)} ports = sorted(u + v for u in sites for v in outside if adjacent(u, v, graph, offset)) neighbors = [[sites.index(v) for v in sites if frozenset((u, v)) in edges] for u in sites] actions = [] for k in range(8): require(all(frozenset(sym(u, w, k) for u in edge) in edges for edge in edges), 'D4 did not preserve internal edges') perm = [ports.index(sym(g[:2], w, k) + sym(g[2:], w, k)) for g in ports] require(sorted(perm) == list(range(len(ports))), 'D4 failed to permute ports') actions.append(perm) return ports, neighbors, actions def rgs(seq): names = {} return bytes(names.setdefault(i, len(names)) for i in seq) def partition(mask, w, neighbors, port_sites): # A depth-first walk on open vertices labels components. Every port of a # closed vertex has a distinct key; even coincident endpoints are distinct. labels = [-1] * (w*w) for start in range(w*w): if mask >> start & 1 and labels[start] == -1: labels[start] = start stack = [start] while stack: for v in neighbors[stack.pop()]: if labels[v] == -1 and mask >> v & 1: labels[v] = start stack.append(v) return rgs(labels[v] if labels[v] != -1 else -2-i for i, v in enumerate(port_sites)) @lru_cache(maxsize=12) def enumerate_law(w, graph, offset, a, b): ports, neighbors, actions = geometry(w, graph, offset) weights = [a**k * (b-a)**(w*w-k) for k in range(w*w+1)] port_sites = [x+w*y for x,y,_,_ in ports] mass = Counter() h = sha256() for mask in range(1 << (w*w)): state = partition(mask, w, neighbors, port_sites) h.update(state) mass[state] += weights[mask.bit_count()] require(sum(mass.values()) == b**(w*w), 'configuration law has wrong mass') return mass, h.hexdigest(), ports, actions def read_law(law, w, offset, ports, compressed, total): a, b = law['p'] raw, digest, reconstructed_ports, actions = enumerate_law(w, law['graph'], offset, a, b) require(reconstructed_ports == ports, 'crossing edges or port labelling differ') require(digest == law['mask_rgs_sha256'], 'configuration-by-configuration digest differs') require(len(raw) == law['raw_count'], 'raw partition count differs') reps = [bytes(row) for row in law['states']] covered = set() orbits, masses = [], [] scale, rem = divmod(total, b**(w*w)) require(rem == 0, 'bad common denominator') for s in reps: require(s in raw, 'proposed representative is not realized') images = sorted({rgs(s[i] for i in action) for action in actions}) if compressed else [s] require(s == images[0], 'representative not canonical') require(covered.isdisjoint(images), 'duplicate orbit') require(all(raw[t] == raw[s] for t in images), 'nonuniform raw law on orbit') covered.update(images) orbits.append(images) masses.append(len(images)*raw[s]*scale) require(covered == set(raw), 'partition law incomplete') return reps, orbits, masses def equals_pairs(state): groups = defaultdict(list) for i, block in enumerate(state): groups[block].append(i) for indices in groups.values(): yield from combinations(indices, 2) def allowed_orbits(src_reps, dst_orbits): # Eight bit positions per target orbit. Each target image gets one bit. # Enforce all source equalities on the SAME target image before folding # the eight positions together. Remaining low bits index target orbits. pair_index = defaultdict(int) valid = 0 for j, imgs in enumerate(dst_orbits): for h, t in enumerate(imgs): bit = 1 << (8*j+h) valid |= bit for pair in equals_pairs(t): pair_index[pair] |= bit low_bits = int.from_bytes(b'\x01' * len(dst_orbits), 'little') for s in src_reps: mask = valid for pair in equals_pairs(s): mask &= pair_index[pair] for shift in (1, 2, 4): mask |= mask >> shift yield mask & low_bits def verify_flow(c, left, right, allowed, total): sent, received = [0]*len(left), [0]*len(right) for i, j, val in c['edges']: require(type(i) is int and 0 <= i < len(left) and type(j) is int and 0 <= j < len(right), 'out-of-range arc') f = int(val) require(str(f) == val and f > 0, 'flow is not a canonical positive integer') require((allowed[i] >> (8*j)) & 1, 'flow on incomparable partitions') sent[i] += f received[j] += f if c['feasible']: require(sent == left and received == right, 'flow marginal differs') return 0 require(all(x <= y for x,y in zip(sent,left)) and all(x <= y for x,y in zip(received,right)), 'partial flow exceeds capacity') cut_l, cut_r = set(c['cut_left']), set(c['cut_right']) require(all(type(i) is int and 0 <= i < len(left) for i in cut_l), 'bad left cut') require(all(type(j) is int and 0 <= j < len(right) for j in cut_r), 'bad right cut') mask = sum(1 << (8*j) for j in cut_r) require(all(allowed[i] & ~mask == 0 for i in cut_l), 'Hall witness misses a neighbor') gap = sum(left[i] for i in cut_l) - sum(right[j] for j in cut_r) require(gap == int(c['deficit']) == total-sum(sent) and gap > 0, 'Hall deficit is incorrect') return gap def check(c): w = c['width'] offset = tuple(c['offset']) src, dst = c['source'], c['target'] stage = (src['graph'], dst['graph']) require(w in (2,4) and type(c['compressed']) is bool and c['compressed'] == (w == 4), 'unexpected geometry') require(type(c['feasible']) is bool, 'invalid feasible flag') if w == 2: require(stage == ('H','S') and offset == (1,1) and src['p'] == [146667,250000] and dst['p'] in ([1359,2000], [3397,5000]), 'small calibration parameters') elif stage == ('LG', 'H'): require(offset == (0,0) and src['p'] == [50001,100000] and dst['p'] in ([1151,2000],[2877,5000]), 'first-stage parameters') else: require(stage == ('H','S') and offset == (1,1) and src['p'] in ([1151,2000],[2877,5000]) and dst['p'] in ([6463,10000], [64629,100000]), 'second-stage parameters') total = lcm(src['p'][1], dst['p'][1])**(w*w) require(int(c['total']) == total, 'common denominator') ports = [tuple(g) for g in c['ports']] s, _, left = read_law(src, w, offset, ports, c['compressed'], total) _, t, right = read_law(dst, w, offset, ports, c['compressed'], total) allowed = list(allowed_orbits(s,t)) order_edges = sum(row.bit_count() for row in allowed) require(order_edges == c['order_edges'], 'number of comparable arcs differs') gap = verify_flow(c,left,right,allowed,total) return dict(width=w, graphs=list(stage), offset=offset, p=[src['p'],dst['p']], ports=len(ports), port_multiplicities=sorted(Counter(g[:2] for g in ports).values()), raw_counts=[src['raw_count'],dst['raw_count']], orbit_counts=[len(s),len(t)], mask_rgs_sha256=[src['mask_rgs_sha256'],dst['mask_rgs_sha256']], allowed=order_edges, arcs_used=len(c['edges']), total=str(total), gap=str(gap), feasible=c['feasible']) def peak_memory(): if sys.platform == 'win32': import ctypes from ctypes import wintypes class Counters(ctypes.Structure): _fields_ = [('cb',wintypes.DWORD),('faults',wintypes.DWORD)] + [ (name,ctypes.c_size_t) for name in ('peak','working','quota_peak','quota','pool_peak','pool','page','page_peak')] v = Counters() v.cb = ctypes.sizeof(v) ok = ctypes.windll.psapi.GetProcessMemoryInfo(ctypes.c_void_p(-1),ctypes.byref(v),v.cb) return v.peak if ok else None import resource peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss return peak if sys.platform == 'darwin' else peak*1024 def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('certificate', nargs='+', type=Path) parser.add_argument('--receipt', type=Path) opts = parser.parse_args() start = perf_counter() results = [] for path in opts.certificate: data = path.read_bytes() t = perf_counter() row = check(json.loads(data)) row.update(file=path.name, sha256=sha256(data).hexdigest(), seconds=perf_counter()-t) results.append(row) print(f"{path.name} passed, feasible={row['feasible']}, arcs={row['allowed']}",flush=True) receipt = dict(verifier_sha256=sha256(Path(__file__).read_bytes()).hexdigest(), python=sys.version, platform=platform.platform(), seconds=perf_counter()-start, peak_working_set_bytes=peak_memory(), results=results) if opts.receipt: opts.receipt.write_text(json.dumps(receipt,indent=2)+'\n', encoding='utf-8') if __name__ == '__main__': main()