from utils import listener
import hashlib
import random

FLAG = "crypto{?????????????????????????????????????????}"

N = 64
Q = 12289
TARGET_MSG = b"I am admin."

rng = random.Random(2026)
H = [rng.randrange(Q) for _ in range(N)]


def poly_add_mod(a, b, q):
    return [(x + y) % q for x, y in zip(a, b)]


def poly_mul_mod(a, b, q):
    n = len(a)
    res = [0] * n
    for i in range(n):
        for j in range(n):
            if i + j < n:
                res[i + j] = (res[i + j] + a[i] * b[j]) % q
            else:
                res[i + j - n] = (res[i + j - n] - a[i] * b[j]) % q
    return res


def hash_to_point(msg, salt):
    digest = hashlib.shake_256(salt + msg).digest(2 * N)
    return [int.from_bytes(digest[2 * i : 2 * i + 2], "big") % Q for i in range(N)]


def verify(msg, salt, s1, s2, h):
    if not (isinstance(s1, list) and isinstance(s2, list) and len(s1) == N and len(s2) == N):
        return False
    if not all(isinstance(x, int) for x in s1 + s2):
        return False
    c = hash_to_point(msg, salt)
    lhs = poly_add_mod(s1, poly_mul_mod(s2, h, Q), Q)
    return lhs == c


class Challenge:
    def __init__(self):
        self.before_input = (
            f"Public key: {{\"n\": {N}, \"q\": {Q}, \"h\": {H}}}\n"
            f"Send a signature for \"{TARGET_MSG.decode()}\" as JSON: {{\"salt\": hex, \"s1\": [...], \"s2\": [...]}}\n"
        )
        self.max_payload_size = 8192

    def challenge(self, your_input):
        if not all(k in your_input for k in ("salt", "s1", "s2")):
            return {"error": "You must provide salt, s1 and s2"}

        salt = bytes.fromhex(your_input["salt"])
        if verify(TARGET_MSG, salt, your_input["s1"], your_input["s2"], H):
            self.exit = True
            return {"flag": FLAG}
        return {"error": "Invalid signature."}


import builtins; builtins.Challenge = Challenge # hack to enable challenge to be run locally, see https://cryptohack.org/faq/#listener
listener.start_server(port=13439)
