# Pure-Python Ed25519 after RFC 8032 sec 5.1 (no OpenSSL): reproduce every Ed25519 half and public key in signature-vectors.json.
import hashlib, json, sys
p = 2**255 - 19; L = 2**252 + 27742317777372353535851937790883648493
d = -121665 * pow(121666, p - 2, p) % p
def inv(x): return pow(x, p - 2, p)
def add(P, Q):
    A = (P[1]-P[0])*(Q[1]-Q[0]) % p; B = (P[1]+P[0])*(Q[1]+Q[0]) % p; C = 2*P[3]*Q[3]*d % p; D = 2*P[2]*Q[2] % p
    E, F, G, H = B-A, D-C, D+C, B+A; return (E*F % p, G*H % p, F*G % p, E*H % p)
def mul(s, P):
    Q = (0, 1, 1, 0)
    while s:
        if s & 1: Q = add(Q, P)
        P = add(P, P); s >>= 1
    return Q
gy = 4 * inv(5) % p
def recx(y):
    x2 = (y*y - 1) * inv(d*y*y + 1) % p; x = pow(x2, (p + 3)//8, p)
    if (x*x - x2) % p: x = x * pow(2, (p - 1)//4, p) % p
    return p - x if x & 1 else x
gx = recx(gy); G = (gx, gy, 1, gx*gy % p)
def enc(P):
    zi = inv(P[2]); x = P[0]*zi % p; y = P[1]*zi % p; return int.to_bytes(y | ((x & 1) << 255), 32, "little")
H = lambda m: hashlib.sha512(m).digest()
def keys(seed):
    h = H(seed); a = int.from_bytes(h[:32], "little"); a &= (1 << 254) - 8; a |= 1 << 254; return a, h[32:]
def sign(seed, msg):
    a, pre = keys(seed); A = enc(mul(a, G)); r = int.from_bytes(H(pre + msg), "little") % L; R = enc(mul(r, G))
    k = int.from_bytes(H(R + A + msg), "little") % L; return A, R + int.to_bytes((r + k*a) % L, 32, "little")
sv = json.load(open(sys.argv[1] + "/data/signature-vectors.json")); ok = 0
for c in sv["cases"]:
    sk = bytes.fromhex(c["secret_key"]); A, s = sign(sk[:32], c["payload"].encode())
    ok += (A.hex() == c["public_key"].split(":")[1][:64]) and (s.hex() == c["sig"].split(":")[1][:128])
print(json.dumps({"ed25519_pure_cases": len(sv["cases"]), "pubkey_and_sig_byte_exact": ok}))
