#!/usr/bin/env python3
"""Minimal dependency-free Ed25519 verification (RFC 8032 arithmetic)."""
import hashlib
Q = 2**255 - 19
L = 2**252 + 27742317777372353535851937790883648493
D = (-121665 * pow(121666, Q - 2, Q)) % Q
I = pow(2, (Q - 1) // 4, Q)

def _xrecover(y):
    x = pow((y*y - 1) * pow(D*y*y + 1, Q - 2, Q) % Q, (Q + 3)//8, Q)
    if (x*x - (y*y - 1) * pow(D*y*y + 1, Q - 2, Q)) % Q:
        x = x * I % Q
    if x & 1: x = Q - x
    return x

def _edwards(p, q):
    x1,y1=p; x2,y2=q
    z=(D*x1*x2*y1*y2) % Q
    return ((x1*y2+x2*y1)*pow(1+z,Q-2,Q)%Q, (y1*y2+x1*x2)*pow(1-z,Q-2,Q)%Q)

def _scalar(p, e):
    if e == 0: return (0,1)
    q=_scalar(p,e//2); q=_edwards(q,q)
    return _edwards(q,p) if e & 1 else q

def _decode(s):
    if len(s)!=32: raise ValueError('point length')
    y=int.from_bytes(s,'little') & ((1<<255)-1)
    if y>=Q: raise ValueError('noncanonical point')
    x=_xrecover(y)
    if (x & 1) != (s[31] >> 7): x=Q-x
    if (-x*x+y*y-1-D*x*x*y*y) % Q: raise ValueError('point off curve')
    return x,y

BY = 4 * pow(5,Q-2,Q) % Q
B = (_xrecover(BY), BY)

def verify(signature: bytes, message: bytes, public_key: bytes) -> bool:
    try:
        if len(signature)!=64 or len(public_key)!=32: return False
        rbytes=signature[:32]; s=int.from_bytes(signature[32:],'little')
        if s>=L: return False
        r=_decode(rbytes); a=_decode(public_key)
        h=int.from_bytes(hashlib.sha512(rbytes+public_key+message).digest(),'little') % L
        return _scalar(B,s) == _edwards(r,_scalar(a,h))
    except Exception:
        return False
