#!/usr/bin/env python3
"""
eip3009.py — Pure-Python Zero-Dependency Cryptography for x402 & EIP-3009 on Base Mainnet
Implements from scratch (standard library only):
- Keccak-256 (original Ethereum sponge, 0x01 padding)
- secp256k1 ECDSA (RFC-6979 deterministic k, low-s normalization, ecrecover)
- EIP-712 typed data hashing for EIP-3009 TransferWithAuthorization (Base USDC)
- RLP encoding + EIP-155 legacy transaction signing
- ABI calldata encoding for transferWithAuthorization (selector 0xe3ee160e)
"""

from __future__ import annotations
import hashlib
import hmac
from typing import Tuple, List, Union

# ============================================================================
# 1. KECCAK-256 (Ethereum 0x01 padding, pure Python)
# ============================================================================

_RC = [
    0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000,
    0x000000000000808B, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009,
    0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
    0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003,
    0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
    0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008,
]

_ROT = [
    [0, 36, 3, 41, 18],
    [1, 44, 10, 45, 2],
    [62, 6, 43, 15, 61],
    [28, 55, 25, 21, 56],
    [27, 20, 39, 8, 14],
]

_MASK64 = 0xFFFFFFFFFFFFFFFF


def _rol64(val: int, shift: int) -> int:
    return ((val << shift) | (val >> (64 - shift))) & _MASK64


def _keccak_f1600(state: List[List[int]]) -> None:
    for r in range(24):
        # Theta
        c = [state[x][0] ^ state[x][1] ^ state[x][2] ^ state[x][3] ^ state[x][4] for x in range(5)]
        d = [c[(x - 1) % 5] ^ _rol64(c[(x + 1) % 5], 1) for x in range(5)]
        for x in range(5):
            for y in range(5):
                state[x][y] ^= d[x]

        # Rho & Pi
        b = [[0] * 5 for _ in range(5)]
        for x in range(5):
            for y in range(5):
                b[y][(2 * x + 3 * y) % 5] = _rol64(state[x][y], _ROT[x][y])

        # Chi
        for x in range(5):
            for y in range(5):
                state[x][y] = b[x][y] ^ ((~b[(x + 1) % 5][y]) & b[(x + 2) % 5][y] & _MASK64)

        # Iota
        state[0][0] ^= _RC[r]


def keccak256(data: Union[bytes, bytearray, str]) -> bytes:
    if isinstance(data, str):
        data = data.encode("utf-8")
    rate = 136  # 1088 bits for Keccak-256
    state = [[0] * 5 for _ in range(5)]

    padded = bytearray(data)
    padded.append(0x01)
    while len(padded) % rate != 0:
        padded.append(0x00)
    padded[-1] ^= 0x80

    for offset in range(0, len(padded), rate):
        block = padded[offset : offset + rate]
        for i in range(rate // 8):
            lane = int.from_bytes(block[i * 8 : (i + 1) * 8], "little")
            state[i % 5][i // 5] ^= lane
        _keccak_f1600(state)

    out = bytearray()
    for y in range(5):
        for x in range(5):
            if len(out) < 32:
                out.extend(state[x][y].to_bytes(8, "little"))
    return bytes(out[:32])


# ============================================================================
# 2. SECP256K1 ECDSA (RFC-6979 deterministic k + low-s + recovery)
# ============================================================================

P_SECP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
N_SECP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798
GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8
G_POINT = (GX, GY)


def _point_add(p1: Tuple[int, int] | None, p2: Tuple[int, int] | None) -> Tuple[int, int] | None:
    if p1 is None:
        return p2
    if p2 is None:
        return p1
    x1, y1 = p1
    x2, y2 = p2
    if x1 == x2 and y1 != y2:
        return None
    if x1 == x2:
        lam = (3 * x1 * x1 * pow(2 * y1, P_SECP - 2, P_SECP)) % P_SECP
    else:
        lam = ((y2 - y1) * pow(x2 - x1, P_SECP - 2, P_SECP)) % P_SECP
    x3 = (lam * lam - x1 - x2) % P_SECP
    y3 = (lam * (x1 - x3) - y1) % P_SECP
    return (x3, y3)


def _point_mul(k: int, point: Tuple[int, int] = G_POINT) -> Tuple[int, int] | None:
    k = k % N_SECP
    if k == 0:
        return None
    res = None
    addend: Tuple[int, int] | None = point
    while k:
        if k & 1:
            res = _point_add(res, addend)
        addend = _point_add(addend, addend)
        k >>= 1
    return res


def private_key_to_address(priv_int: int) -> str:
    pt = _point_mul(priv_int, G_POINT)
    assert pt is not None
    pub_uncompressed = pt[0].to_bytes(32, "big") + pt[1].to_bytes(32, "big")
    addr_bytes = keccak256(pub_uncompressed)[-20:]
    return "0x" + addr_bytes.hex()


def _rfc6979_k(priv_int: int, msg_hash32: bytes) -> int:
    x = priv_int.to_bytes(32, "big")
    h1 = (int.from_bytes(msg_hash32, "big") % N_SECP).to_bytes(32, "big")
    v = b"\x01" * 32
    k = b"\x00" * 32
    k = hmac.new(k, v + b"\x00" + x + h1, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    k = hmac.new(k, v + b"\x01" + x + h1, hashlib.sha256).digest()
    v = hmac.new(k, v, hashlib.sha256).digest()
    while True:
        v = hmac.new(k, v, hashlib.sha256).digest()
        candidate = int.from_bytes(v, "big")
        if 1 <= candidate < N_SECP:
            return candidate
        k = hmac.new(k, v + b"\x00", hashlib.sha256).digest()
        v = hmac.new(k, v, hashlib.sha256).digest()


def sign_digest(priv_int: int, digest32: bytes) -> Tuple[int, int, int]:
    """Returns (v, r, s) with EIP-2 low-s normalization and v in {27, 28}."""
    z = int.from_bytes(digest32, "big")
    k = _rfc6979_k(priv_int, digest32)
    pt = _point_mul(k, G_POINT)
    assert pt is not None
    r = pt[0] % N_SECP
    assert r != 0
    rec_id = pt[1] & 1
    if pt[0] >= N_SECP:
        rec_id |= 2
    s = (pow(k, N_SECP - 2, N_SECP) * (z + r * priv_int)) % N_SECP
    if s > N_SECP // 2:
        s = N_SECP - s
        rec_id ^= 1
    return (27 + rec_id, r, s)


def ecrecover_address(digest32: bytes, v: int, r: int, s: int) -> str:
    if v in (27, 28):
        rec_id = v - 27
    elif v in (0, 1):
        rec_id = v
    else:
        raise ValueError("Invalid recovery id v")
    if not (1 <= r < N_SECP and 1 <= s <= N_SECP // 2):
        raise ValueError("Invalid signature r/s bounds (low-s required)")

    x = r + (N_SECP if (rec_id & 2) else 0)
    if x >= P_SECP:
        raise ValueError("x out of field range")
    y_sq = (pow(x, 3, P_SECP) + 7) % P_SECP
    y = pow(y_sq, (P_SECP + 1) // 4, P_SECP)
    if pow(y, 2, P_SECP) != y_sq:
        raise ValueError("Point not on curve")
    if (y & 1) != (rec_id & 1):
        y = P_SECP - y

    r_pt = (x, y)
    z = int.from_bytes(digest32, "big") % N_SECP
    r_inv = pow(r, N_SECP - 2, N_SECP)
    u1 = (-z * r_inv) % N_SECP
    u2 = (s * r_inv) % N_SECP
    q = _point_add(_point_mul(u1, G_POINT), _point_mul(u2, r_pt))
    if q is None:
        raise ValueError("Recovered point at infinity")
    pub_bytes = q[0].to_bytes(32, "big") + q[1].to_bytes(32, "big")
    return "0x" + keccak256(pub_bytes)[-20:].hex()


# ============================================================================
# 3. RLP ENCODING & EIP-3009 / EIP-712 CONSTANTS (Base USDC)
# ============================================================================

USDC_BASE_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
BASE_CHAIN_ID = 8453
USDC_DECIMALS = 6
SELECTOR_TRANSFER_WITH_AUTH = bytes.fromhex("e3ee160e")


def rlp_encode(item: Union[bytes, bytearray, List]) -> bytes:
    if isinstance(item, (bytes, bytearray)):
        if len(item) == 1 and item[0] < 0x80:
            return bytes(item)
        if len(item) <= 55:
            return bytes([0x80 + len(item)]) + bytes(item)
        len_bytes = len(item).to_bytes((len(item).bit_length() + 7) // 8, "big")
        return bytes([0xB7 + len(len_bytes)]) + len_bytes + bytes(item)
    elif isinstance(item, list):
        payload = b"".join(rlp_encode(x) for x in item)
        if len(payload) <= 55:
            return bytes([0xC0 + len(payload)]) + payload
        len_bytes = len(payload).to_bytes((len(payload).bit_length() + 7) // 8, "big")
        return bytes([0xF7 + len(len_bytes)]) + len_bytes + payload
    raise TypeError("Unsupported RLP type")


def _addr_word(addr: str) -> bytes:
    clean = addr.lower().replace("0x", "")
    assert len(clean) == 40
    return bytes.fromhex(clean).rjust(32, b"\x00")


def _uint256_word(val: int) -> bytes:
    return int(val).to_bytes(32, "big")


def eip3009_domain_separator(
    name: str = "USD Coin",
    version: str = "2",
    chain_id: int = BASE_CHAIN_ID,
    verifying_contract: str = USDC_BASE_ADDRESS,
) -> bytes:
    type_hash = keccak256(
        "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
    )
    return keccak256(
        type_hash
        + keccak256(name)
        + keccak256(version)
        + _uint256_word(chain_id)
        + _addr_word(verifying_contract)
    )


def eip3009_transfer_digest(
    from_addr: str,
    to_addr: str,
    value: int,
    valid_after: int,
    valid_before: int,
    nonce32: bytes,
) -> bytes:
    assert len(nonce32) == 32
    type_hash = keccak256(
        "TransferWithAuthorization(address from,address to,uint256 value,uint256 validAfter,uint256 validBefore,bytes32 nonce)"
    )
    struct_hash = keccak256(
        type_hash
        + _addr_word(from_addr)
        + _addr_word(to_addr)
        + _uint256_word(value)
        + _uint256_word(valid_after)
        + _uint256_word(valid_before)
        + nonce32
    )
    return keccak256(b"\x19\x01" + eip3009_domain_separator() + struct_hash)


def encode_transfer_with_authorization_calldata(
    from_addr: str,
    to_addr: str,
    value: int,
    valid_after: int,
    valid_before: int,
    nonce32: bytes,
    v: int,
    r: Union[int, bytes, bytearray],
    s: Union[int, bytes, bytearray],
) -> bytes:
    assert len(nonce32) == 32
    r_bytes = _uint256_word(r) if isinstance(r, int) else bytes(r)
    s_bytes = _uint256_word(s) if isinstance(s, int) else bytes(s)
    assert len(r_bytes) == 32 and len(s_bytes) == 32
    calldata = (
        SELECTOR_TRANSFER_WITH_AUTH
        + _addr_word(from_addr)
        + _addr_word(to_addr)
        + _uint256_word(value)
        + _uint256_word(valid_after)
        + _uint256_word(valid_before)
        + nonce32
        + _uint256_word(v)
        + r_bytes
        + s_bytes
    )
    assert len(calldata) == 292
    return calldata


def run_blocking_self_tests() -> bool:
    """Verifies the 4 mandatory blocking test vectors from MISSIONE Phase 1."""
    h_empty = keccak256(b"").hex()
    assert h_empty.startswith("c5d24601") and h_empty.endswith("85a470"), f"keccak('') failed: {h_empty}"

    h_abc = keccak256(b"abc").hex()
    assert h_abc.startswith("4e03657a") and h_abc.endswith("d6c45"), f"keccak('abc') failed: {h_abc}"

    addr_1 = private_key_to_address(1).lower()
    assert addr_1.startswith("0x7e5f4552") and addr_1.endswith("395bdf"), f"addr(1) failed: {addr_1}"

    rlp_dog = rlp_encode(b"dog").hex()
    assert rlp_dog == "83646f67", f"RLP(b'dog') failed: {rlp_dog}"

    expected_selector = keccak256(
        "transferWithAuthorization(address,address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)"
    )[:4]
    assert SELECTOR_TRANSFER_WITH_AUTH == expected_selector, (
        f"selector mismatch: {SELECTOR_TRANSFER_WITH_AUTH.hex()} != {expected_selector.hex()}"
    )

    # Verify EIP-3009 sign + ecrecover + full 292-byte ABI calldata roundtrip
    nonce = keccak256(b"test-nonce-1")
    digest = eip3009_transfer_digest(addr_1, USDC_BASE_ADDRESS, 10000, 0, 9999999999, nonce)
    v, r, s = sign_digest(1, digest)
    recovered = ecrecover_address(digest, v, r, s)
    assert recovered.lower() == addr_1, f"ecrecover mismatch: {recovered} != {addr_1}"
    calldata = encode_transfer_with_authorization_calldata(
        addr_1, USDC_BASE_ADDRESS, 10000, 0, 9999999999, nonce, v, r, s
    )
    assert len(calldata) == 292 and calldata[:4] == SELECTOR_TRANSFER_WITH_AUTH
    return True


if __name__ == "__main__":
    run_blocking_self_tests()
    print("[OK] All 4 blocking crypto self-tests & EIP-3009 roundtrips passed 100%.")
