"""Deterministic ECDSA signing, verification, and public-key recovery.

Signs a hash with an RFC 6979 deterministic nonce, verifies it, and recovers the
signer's public key. The signature is checked against the published RFC 6979 /
secp256k1 test vector.
"""
import hashlib

from libcrypto import recover_public_key, sign, verify
from libcrypto.secp256k1 import private_key_to_public_key


def main() -> None:
    private_key = 0x0000000000000000000000000000000000000000000000000000000000000001
    message = b"Everything should be made as simple as possible, but not simpler."
    digest = hashlib.sha256(message).digest()

    signature = sign(private_key, digest)

    expected_r = 0x33A69CD2065432A30F3D1CE4EB0D59B8AB58C74F27C41A7FDB5696AD4E6108C9
    expected_s = 0x6F807982866F785D3F6418D24163DDAE117B7DB4D5FDF0071DE069FA54342262
    assert signature.r == expected_r, "r does not match the RFC 6979 vector"
    assert signature.s == expected_s, "s does not match the RFC 6979 vector"
    assert signature.is_canonical, "signature is not low-S canonical"

    public_key = private_key_to_public_key(private_key, compressed=True)
    assert verify(public_key, digest, signature) is True
    assert recover_public_key(digest, signature) == public_key

    print("r:", hex(signature.r))
    print("s:", hex(signature.s))
    print("DER:", signature.to_der().hex())
    print("recovery_id:", signature.recovery_id)
    print("\nECDSA signing, verification, and recovery all passed.")


if __name__ == "__main__":
    main()
