#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ristretto255 group operations in pure Python — the certificate's group layer.

Public standard only, in pure Python: the prime field, the Edwards25519
curve and the Ristretto255 group (encode/decode of the draft), anchored to
the OFFICIAL published test vectors (ristretto.group / RFC 7748) —
`autocheck()` verifies them BEFORE any use (verified before first use).

WHO USES THIS LIB: `verifica_reciba.py`, the kit's receipt verifier — one
Python definition of every piece, independent of the service it verifies.

WHAT TRAVELS HERE: this file and its users carry public-standard
cryptography only. The wire field `fold_code` is an opaque byte on the
wire (see the receipt format); nothing about how the server computes it
is part of this kit.

Uso: `import lib_cert_ristretto as rist` (o same-dir).
"""

import hashlib

# ── EL CUERPO FINITO y la curva (constantes publicadas: RFC 7748) ──

P = 2**255 - 19
L = 2**252 + 27742317777372353535851937790883648493  # el orden del subgrupo primo
D = -121665 * pow(121666, P - 2, P) % P               # d de Edwards25519
SQRT_M1 = pow(2, (P - 1) // 4, P)                    # sqrt(−1): p ≡ 5 mod 8


def inv(x):
    return pow(x, P - 2, P)


def sqrt_ratio(u, v):
    """(era_cuadrado, r) con r² = u/v si u/v es cuadrado — la referencia del draft."""
    v3 = v * v * v % P
    v7 = v3 * v3 * v % P
    r = u * v3 * pow(u * v7, (P - 5) // 8, P) % P
    check = v * r * r % P
    if check == u % P:
        return True, r
    if check == (-u) % P:
        return True, r * SQRT_M1 % P
    return False, 0


# ── Edwards25519 en AFÍN (la fórmula del libro — verificada contra los
#    vectores oficiales en el autocheck) ──

IDENTIDAD = (0, 1)


def sumar(p1, p2):
    """La adición afín unificada de Edwards (a = −1)."""
    x1, y1 = p1
    x2, y2 = p2
    xy = x1 * x2 % P * (y1 * y2 % P) % P
    denx = (1 + D * xy) % P
    deny = (1 - D * xy) % P
    x3 = (x1 * y2 + y1 * x2) * inv(denx) % P
    y3 = (y1 * y2 + x1 * x2) * inv(deny) % P
    return (x3, y3)


def escalar(n, pto):
    """n·pto por double-and-add (n ≥ 0)."""
    r = IDENTIDAD
    while n > 0:
        if n & 1:
            r = sumar(r, pto)
        pto = sumar(pto, pto)
        n >>= 1
    return r


def es_negativo(x):
    return x % 2 == 1


def mismos_puntos(p1, p2):
    """La igualdad EN RISTRETTO es por ENCODING (cada elemento es un coset
    de representantes Edwards — el encoding es la proyección canónica)."""
    return ristretto_encode(p1) == ristretto_encode(p2)


# ── EL PUNTO BASE (la constante publicada: y = 4/5, x recuperado par) ──

Y_B = 4 * inv(5) % P


def recuperar_x(y, signo):
    x2 = (y * y - 1) * inv(D * y * y + 1) % P
    x = pow(x2, (P + 3) // 8, P)
    if x * x % P != x2:
        x = x * SQRT_M1 % P
    if x * x % P != x2:
        return None
    if x % 2 != signo:
        x = P - x
    return x


X_B = recuperar_x(Y_B, 0)
BASE = (X_B, Y_B)

# ── Ristretto255: encode/decode (el draft §4.3, ristretto.group/formulas) ──

INVSQRT_A_MENOS_D = sqrt_ratio(1, (-1 - D) % P)[1]


def ristretto_encode(pto):
    """La entrada afín (x, y) se lleva a Z=1, T=xy."""
    X, Y = pto
    Z, T = 1, X * Y % P
    u1 = (Z + Y) * (Z - Y) % P
    u2 = X * Y % P
    _, invsqrt = sqrt_ratio(1, u1 * u2 * u2 % P)
    den1 = invsqrt * u1 % P
    den2 = invsqrt * u2 % P
    z_inv = den1 * den2 * T % P
    ix0 = X * SQRT_M1 % P
    iy0 = Y * SQRT_M1 % P
    encantado = den1 * INVSQRT_A_MENOS_D % P
    rotar = es_negativo(T * z_inv)
    x = iy0 if rotar else X
    y = ix0 if rotar else Y
    den_inv = encantado if rotar else den2
    if es_negativo(x * z_inv):
        y = (-y) % P
    s = den_inv * (Z - y) % P
    if es_negativo(s * z_inv):
        s = (-s) % P
    return s.to_bytes(32, "little")


def ristretto_decode(b32):
    """El decode EXACTO del draft: canonicalidad · s NO negativo ·
    v = ad·u1² − u2² · x = |2s·Dx| (niega SOLO x) · abort si t negativo o y=0."""
    s = int.from_bytes(b32, "little")
    if s >= P:
        return None  # no canónico
    if es_negativo(s):
        return None  # s negativo — los encodings de ristretto son ≥ 0
    ss = s * s % P
    u1 = (1 - ss) % P
    u2 = (1 + ss) % P
    u2_sq = u2 * u2 % P
    v = (-D * u1 * u1 - u2_sq) % P
    ok, invsqrt = sqrt_ratio(1, v * u2_sq % P)
    if not ok:
        return None
    den_x = invsqrt * u2 % P
    den_y = invsqrt * den_x * v % P  # I·D_x·v (el draft — NO u1)
    x = 2 * s * den_x % P
    if es_negativo(x):
        x = (-x) % P  # |2s·Dx| — SOLO x
    y = u1 * den_y % P
    t = x * y % P
    if y == 0 or es_negativo(t):
        return None
    return (x, y)


# ── LOS VECTORES OFICIALES publicados (el ancla externa del grupo) ──

MULTIPLOS_OFICIALES = [
    "0000000000000000000000000000000000000000000000000000000000000000",
    "e2f2ae0a6abc4e71a884a961c500515f58e30b6aa582dd8db6a65945e08d2d76",
    "6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919",
    "94741f5d5d52755ece4f23f044ee27d5d1ea1e2bd196b462166b16152a9d0259",
    "da80862773358b466ffadfe0b3293ab3d9fd53c5ea6c955358f568322daf6a57",
    "e882b131016b52c1d3337080187cf768423efccbb517bb495ab812c4160ff44e",
    "f64746d3c92b13050ed8d80236a7f0007c3b3f962f5ba793d19a601ebb1df403",
    "44f53520926ec81fbd5a387845beb7df85a96a24ece18738bdcfa6a7822a176d",
    "903293d8f2287ebe10e2374dc1a53e0bc887e592699f02d077d5263cdd55601c",
    "02622ace8f7303a31cafc63f8fc48fdc16e1c8c8d234b2f0d6685282a9076031",
    "20706fd788b2720a1ed2a5dad4952b01f413bcf0e7564de8cdc816689e2db95f",
    "bce83f8ba5dd2fa572864c24ba1810f9522bc6004afe95877ac73241cafdab42",
    "e4549ee16b9aa03099ca208c67adafcafa4c3f3e4e5303de6026e3ca8ff84460",
    "aa52e000df2e16f55fb1032fc33bc42742dad6bd5a8fc0be0167436c5948501f",
    "46376b80f409b29dc2b5f6f0c52591990896e5716f41477cd30085ab7f10301e",
    "e0c418f7c8d9c4cdd7395b93ea124f3ad99021bb681dfc3302a9d99a2e53e64e",
]

MALOS_OFICIALES = [
    "00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",  # no canónico
    "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",  # no canónico
    "0100000000000000000000000000000000000000000000000000000000000000",  # negativo
    "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",  # s = −1 → y = 0
    "26948d35ca62e643e26a83177332e6b6afeb9d08e4268b650f1f5bbd8d81d371",  # x² no cuadrado
    "3eb858e78f5a7254d8c9731174a94f76755fd3941c0ac93735c07ba14579630e",  # xy negativo
]


def autocheck():
    """La validación de ESTA implementación contra lo publicado — corre
    ANTES de cualquier medición (el patrón valida-el-instrumento-primero)."""
    fallos = []
    if SQRT_M1 * SQRT_M1 % P != P - 1:
        fallos.append("sqrt(-1) mal derivada")
    pto = IDENTIDAD
    for i, hex_oficial in enumerate(MULTIPLOS_OFICIALES):
        if ristretto_encode(pto) != bytes.fromhex(hex_oficial):
            fallos.append(f"encode({i}·B) != el vector oficial")
        dec = ristretto_decode(bytes.fromhex(hex_oficial))
        if dec is None or not mismos_puntos(dec, pto):
            fallos.append(f"decode del vector oficial {i}·B falla")
        pto = sumar(pto, BASE)
    if Y_B != 46316835694926478169428394003475163141307993866256225615783033603165251855960:
        fallos.append("y_B != 4/5 (la constante del RFC 7748)")
    if not mismos_puntos(escalar(L, BASE), IDENTIDAD):
        fallos.append("l·B != identidad (el orden del subgrupo)")
    for hex_malo in MALOS_OFICIALES:
        if ristretto_decode(bytes.fromhex(hex_malo)) is not None:
            fallos.append(f"el encoding malo oficial NO se rechaza: {hex_malo[:16]}…")
    return fallos


# ── EL WIRE PÚBLICO DEL CERTIFICADO (los tags del formato) ──

TAG_NONCE = b"kmerbio-cert-schnorr-nonce-v1"
TAG_RETO = b"kmerbio-cert-schnorr-challenge-v1"
TAG_HEAD = b"kmerbio-cert-head-v1"
TAG_ID = b"kmerbio-cert-id-v1"
GENESIS_LABEL = b"kmerbio-cert-ledger-genesis-v1"


def escalar_del_digesto(digesto):
    """Wide scalar reduction: the 64-byte little-endian integer, mod l."""
    return int.from_bytes(digesto, "little") % L


def head_genesis():
    import hashlib
    return hashlib.sha256(GENESIS_LABEL).digest()


def head_de(campos):
    """EL HEAD por la fórmula pública — el campo fold_code entra como BYTE OPACO."""
    head_prev, cert_id, seq, payload_sha, firma, kv, ts, fold_code = campos
    h = hashlib.sha256()
    h.update(TAG_HEAD)
    h.update(head_prev)
    h.update(cert_id)
    h.update(seq.to_bytes(8, "little"))
    h.update(payload_sha)
    h.update(firma)
    h.update(kv.to_bytes(4, "little"))
    h.update(ts.to_bytes(8, "little"))
    h.update(bytes([fold_code]))
    return h.digest()


def cert_id_de(version, key_version, ts, payload_sha):
    """cert_id = sha256(TAG_ID ‖ sobre(seq=0)) — el sobre canónico 56B BE."""
    sobre = (
        version.to_bytes(4, "big")
        + key_version.to_bytes(4, "big")
        + ts.to_bytes(8, "big")
        + (0).to_bytes(8, "big")
        + payload_sha
    )
    import hashlib
    return hashlib.sha256(TAG_ID + sobre).digest()


def sobre_canonico(version, key_version, ts, seq, payload_sha):
    return (
        version.to_bytes(4, "big")
        + key_version.to_bytes(4, "big")
        + ts.to_bytes(8, "big")
        + seq.to_bytes(8, "big")
        + payload_sha
    )


def verificar_firma(publica_hex, r_bytes, s_bytes, version, key_version, ts, seq, payload_sha):
    """LA ECUACIÓN estándar: e = H(tag‖R‖PK‖m); s·B == R + e·PK."""
    s_int = int.from_bytes(s_bytes, "little")
    if s_int >= L:
        return False  # s no canónico
    r_pto = ristretto_decode(r_bytes)
    if r_pto is None:
        return False
    pk_bytes = bytes.fromhex(publica_hex)
    p_pto = ristretto_decode(pk_bytes)
    if p_pto is None:
        return False
    m = sobre_canonico(version, key_version, ts, seq, payload_sha)
    reto = hashlib.sha512(TAG_RETO + r_bytes + pk_bytes + m).digest()
    e = escalar_del_digesto(reto)
    return mismos_puntos(escalar(s_int, BASE), sumar(r_pto, escalar(e, p_pto)))


def palabras_de_folds(payload_sha):
    """The set-level arithmetic digests: xor/sum over the 4 little-endian
    u64 words of the payload_sha (plain numbers on the wire — nothing
    else is computed or checked here)."""
    xor = [0] * 4
    suma = [0] * 4
    for w in range(4):
        palabra = int.from_bytes(payload_sha[w * 8:(w + 1) * 8], "little")
        xor[w] = palabra
        suma[w] = palabra
    return xor, suma


def acumular_folds(xor, suma, payload_sha):
    for w in range(4):
        palabra = int.from_bytes(payload_sha[w * 8:(w + 1) * 8], "little")
        xor[w] ^= palabra
        suma[w] = (suma[w] + palabra) % (1 << 64)
