#!/usr/bin/env python3
"""The zero-energy states of the 39 relations are exactly the graph of the AES S-box.

E(x, y) = number of violated relations in aes_sbox_mq.txt. This script finds every (x, y) with
E = 0 over all 2¹⁶ pairs and checks y = S(x) for the AES S-box, S(a) = A·a⁻¹ ⊕ 0x63 in
GF(2⁸) = GF(2)[t]/(t⁸ + t⁴ + t³ + t + 1), with x0 and y0 the least significant bits.
"""
from pathlib import Path

names = [f"{a}{i}" for a in "xy" for i in range(8)]
rel = [[0 if t == "1" else sum(1 << names.index(v) for v in t.split("*"))
        for t in line.split(" =")[0].split(" + ")]
       for line in Path(__file__).with_name("aes_sbox_mq.txt").read_text().splitlines()]
zero = [z for z in range(1 << 16) if all(sum((z & m) == m for m in t) % 2 == 0 for t in rel)]


def gmul(a, b):
    p = 0
    for _ in range(8):
        if b & 1:
            p ^= a
        hi, a = a & 0x80, (a << 1) & 0xFF
        if hi:
            a ^= 0x1B
        b >>= 1
    return p


inv = [0] + [next(b for b in range(1, 256) if gmul(a, b) == 1) for a in range(1, 256)]
rot = lambda b, i: ((b << i) | (b >> (8 - i))) & 0xFF
S = [inv[a] ^ rot(inv[a], 1) ^ rot(inv[a], 2) ^ rot(inv[a], 3) ^ rot(inv[a], 4) ^ 0x63 for a in range(256)]

graph = sorted((z & 0xFF, z >> 8) for z in zero)
assert len(rel) == 39 and len(zero) == 256
assert graph == [(a, S[a]) for a in range(256)]
print("39 relations · 256 zero-energy states · {E = 0} = {(x, S(x))} = graph of the AES S-box  ✓")
