#!/usr/bin/env python3
"""bb84 reference client — a complete bb84 wallet in one file, for agents with their own runtime.

Specification: https://bb84.com/agent/protocol.md   (this file implements protocol version 1)
No dependencies beyond the Python 3.8+ standard library. `eth_hash` or `pycryptodome` are used for
keccak-256 when installed; otherwise a pure-Python Keccak-f[1600] is used (slower, same result).

    python3 bb84.py new   [--name alice]        create a wallet, publish its commitment, pick a name
    python3 bb84.py status                      address, name, activation, remaining steps, balances
    python3 bb84.py pay <to> <amount> <USDC|EURC> [--memo "…"] [--goods]
    python3 bb84.py name <label>                claim / change the bb84 name (<label>.bb84.eth)
    python3 bb84.py selftest                    offline check of the cryptography against test vectors
    BB84_WALLET_FILE (default ./bb84-wallet.json) or --state <file> selects the wallet file.

As a library:
    from bb84 import Wallet
    w = Wallet.create(); w.save("wallet.json"); w.publish_commitment(); print(w.address)
    w = Wallet.load("wallet.json"); print(w.status()); w.pay("alice", "2.50", "USDC", memo="Coffee")

SECRETS. The wallet file holds the hash-chain seed. Whoever reads it can spend every balance and
there is no way to revoke it short of emptying the wallet. Keep the file where only the agent's
process can read it (this client writes it with mode 0600), never print it, never put it into a chat
transcript, prompt, log or ticket. An agent that cannot keep a secret must not run this client; it
should use the bb84 MCP server instead (https://bb84.com/developers), where the user's phone or an
on-chain capped AI budget holds the keys.

Chain facts the protocol is built on: an account is a one-time address (OTA) derived from the head of
a keccak-256 hash chain; spending step k reveals chain element [length − k] inside a HashRevealTx
(type 0x7f) that a HashCommitTx (type 0x7c) announced one or more blocks earlier. There are no ECDSA
keys and no signatures; the node checks keccak256(preImage) == lastReveal. The chain decides what is
valid — this client only builds bytes and talks to public, unauthenticated HTTP endpoints.
"""
import json
import os
import re
import secrets
import sys
import time
import urllib.error
import urllib.request

PROTOCOL_VERSION = 1
CHAIN_ID = 42069000
CHAIN_LENGTH = 1000                        # every wallet registration uses this depth (StealthPool.OTA_CHAIN_LENGTH)
BASE = os.environ.get("BB84_BASE", "https://bb84.com")
RELAY = BASE + "/api/connect/web"          # chain/<addr>, fees, send, tx/<hash> — public, no key
ENS = BASE + "/api/ens"                    # name/<addr>, label/<addr>, address/<label>, check/<label>, commitment, register
TOKENS = {"USDC": "0x50590ee131edc98a7213c91ae82e3e8987b9b5ee", "EURC": "0x47dbbf8233cd91c16360bdb69e325f771fd9a667"}
DECIMALS = 6
STEALTH_POOL = "0x4200000000000000000000000000000000000044"
COMMIT_KEY_REGISTRY = "0x420000000000000000000000000000000000004a"
OTA_DELETE_ADDRESS = "0x4200000000000000000000000000000000000047"
GAS_TRANSFER, GAS_GOODS, GAS_REGISTER, GAS_SELF = 80000, 160000, 200000, 60000
COMMIT_GAS, COMMIT_EXPIRE_BLOCKS, MAX_FEE_CAP = 100000, 250, 1_000_000_000
MEMO_MAX_BYTES = 280
COMMIT_KEY_LENGTH, COMMIT_KEY_REANCHOR_AT, COMMIT_KEY_EPOCH_SEARCH = 2048, 64, 32
LABEL_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$")
ADDR_RE = re.compile(r"^0x[0-9a-fA-F]{40}$")
AMOUNT_RE = re.compile(r"^\d{1,12}(\.\d{1,6})?$")
USER_AGENT = "bb84-agent-client/1 (+https://bb84.com/agent/protocol.md)"


# ─── keccak-256 ──────────────────────────────────────────────────────────────
def _pure_keccak256(data: bytes) -> bytes:
    """Keccak-f[1600], rate 1088 bits, Keccak padding (0x01 … 0x80) — NOT SHA3-256 (0x06)."""
    mask = (1 << 64) - 1
    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))

    def rol(v, n):
        return ((v << n) | (v >> (64 - n))) & mask if n else v

    def f(st):
        for r in rc:
            c = [st[x] ^ st[x + 5] ^ st[x + 10] ^ st[x + 15] ^ st[x + 20] for x in range(5)]
            d = [c[(x - 1) % 5] ^ rol(c[(x + 1) % 5], 1) for x in range(5)]
            st = [st[i] ^ d[i % 5] for i in range(25)]
            b = [0] * 25
            for x in range(5):
                for y in range(5):
                    b[y + 5 * ((2 * x + 3 * y) % 5)] = rol(st[x + 5 * y], rot[x][y])
            st = [b[i] ^ ((~b[(i % 5 + 1) % 5 + 5 * (i // 5)] & mask) & b[(i % 5 + 2) % 5 + 5 * (i // 5)]) for i in range(25)]
            st[0] ^= r
        return st

    rate = 136
    msg = bytearray(data) + b"\x01"
    msg += b"\x00" * ((-len(msg)) % rate)
    msg[-1] |= 0x80
    st = [0] * 25
    for off in range(0, len(msg), rate):
        for i in range(rate // 8):
            st[i] ^= int.from_bytes(msg[off + 8 * i: off + 8 * i + 8], "little")
        st = f(st)
    return b"".join(st[i].to_bytes(8, "little") for i in range(4))


try:                                         # fast paths when available; identical output
    from eth_hash.auto import keccak as _fast_keccak      # type: ignore
    def keccak256(data: bytes) -> bytes:
        return bytes(_fast_keccak(data))
    KECCAK_BACKEND = "eth_hash"
except Exception:                            # pragma: no cover
    try:
        from Crypto.Hash import keccak as _cr_keccak      # type: ignore
        def keccak256(data: bytes) -> bytes:
            return _cr_keccak.new(digest_bits=256, data=data).digest()
        KECCAK_BACKEND = "pycryptodome"
    except Exception:
        keccak256 = _pure_keccak256
        KECCAK_BACKEND = "pure-python"


def kk(*parts: bytes) -> bytes:
    return keccak256(b"".join(parts))


D_OTA_SPEND = kk(b"OP_OTA_SPEND_v1")
D_OTA_VIEW = kk(b"OP_OTA_VIEW_v1")
D_HASH_ADDR = kk(b"OP_HASH_ADDR_v1")
D_NULLIFIER = kk(b"OP_NULLIFIER_v1")
D_COMMIT_BIND = kk(b"OP_COMMIT_BIND_v1")
D_COMMIT_KEY = kk(b"OP_OTA_COMMITKEY_v1")
SEL_TRANSFER = bytes.fromhex("a9059cbb")                                   # transfer(address,uint256)
SEL_REGISTER_FOR = kk(b"registerCommitmentFor(address,bytes32)")[:4]       # 0x79176c17


# ─── hash chain, address ─────────────────────────────────────────────────────
def derive_chain(spend_sk: bytes, r: bytes, length: int = CHAIN_LENGTH):
    """chain[0] = keccak(D_OTA_SPEND ‖ spendSK ‖ r); chain[k] = keccak(chain[k-1]); commitment = chain[length]."""
    chain = [kk(D_OTA_SPEND, spend_sk, r)]
    for _ in range(length):
        chain.append(keccak256(chain[-1]))
    return chain


def ota_address(commitment: bytes) -> str:
    """trunc20(keccak(D_HASH_ADDR ‖ commitment)) — the account address of a fresh chain."""
    return "0x" + kk(D_HASH_ADDR, commitment)[12:].hex()


# ─── RLP (exactly op-geth's encoding of the two hash tx types) ───────────────
def _min_bytes(n: int) -> bytes:
    return b"" if n == 0 else n.to_bytes((n.bit_length() + 7) // 8, "big")


def rlp_str(b: bytes) -> bytes:
    if len(b) == 1 and b[0] < 0x80:
        return b
    if len(b) < 56:
        return bytes([0x80 + len(b)]) + b
    lb = _min_bytes(len(b))
    return bytes([0xb7 + len(lb)]) + lb + b


def rlp_list(items) -> bytes:
    p = b"".join(items)
    if len(p) < 56:
        return bytes([0xc0 + len(p)]) + p
    lb = _min_bytes(len(p))
    return bytes([0xf7 + len(lb)]) + lb + p


def rlp_int(n: int) -> bytes:
    return rlp_str(_min_bytes(n))


ZERO32 = b"\x00" * 32


def tx_digest(frm, nonce, to, value, gas, fee_cap, tip_cap, data, new_commitment=ZERO32, new_chain_length=0) -> bytes:
    """keccak(RLP([chainId, from, nonce, to, value, gas, gasFeeCap, gasTipCap, data, newCommitment, newChainLength]))"""
    return kk(rlp_list([rlp_int(CHAIN_ID), rlp_str(frm), rlp_int(nonce), rlp_str(to), rlp_int(value), rlp_int(gas),
                        rlp_int(fee_cap), rlp_int(tip_cap), rlp_str(data), rlp_str(new_commitment), rlp_int(new_chain_length)]))


def build_spend_txs(frm: bytes, nonce: int, to: bytes, data: bytes, gas: int, fee_cap: int, tip_cap: int, preimage: bytes,
                    commit_preimage: bytes = ZERO32, new_commitment: bytes = ZERO32, new_chain_length: int = 0, value: int = 0):
    """One spend step: HashCommitTx (0x7c, nonce N) + HashRevealTx (0x7f, nonce N+1). All bindings use N+1.
    commit_preimage: next element of the commit key chain (zero = account has no commit key).
    new_commitment/new_chain_length: only on the last step of the chain (renewal)."""
    rn = nonce + 1
    digest = tx_digest(frm, rn, to, value, gas, fee_cap, tip_cap, data, new_commitment, new_chain_length)
    n8 = rn.to_bytes(8, "big")
    nullifier = kk(D_NULLIFIER, preimage, n8, digest)
    hash_commit = kk(D_COMMIT_BIND, nullifier, preimage, digest, n8)
    fields = [rlp_int(CHAIN_ID), rlp_str(frm), rlp_int(nonce), rlp_str(hash_commit), rlp_int(COMMIT_GAS),
              rlp_int(fee_cap), rlp_int(tip_cap), rlp_int(COMMIT_EXPIRE_BLOCKS)]
    if commit_preimage != ZERO32:
        fields.append(rlp_str(commit_preimage))
    commit = b"\x7c" + rlp_list(fields)
    reveal = b"\x7f" + rlp_list([rlp_int(CHAIN_ID), rlp_str(frm), rlp_int(rn), rlp_str(to), rlp_int(value), rlp_int(gas),
                                 rlp_int(fee_cap), rlp_int(tip_cap), rlp_str(data), rlp_str(nullifier), rlp_str(preimage),
                                 rlp_int(0), rlp_str(new_commitment), rlp_int(new_chain_length)])
    return commit, reveal


def tx_hash(raw: bytes) -> str:
    """Hash of a typed transaction = keccak(type ‖ rlp) — what the node returns from eth_sendRawTransaction."""
    return "0x" + keccak256(raw).hex()


# ─── calldata ────────────────────────────────────────────────────────────────
def to_units(amount: str, decimals: int = DECIMALS) -> int:
    a = amount.strip().replace(",", ".")
    if not AMOUNT_RE.match(a):
        raise Bb84Error("amount", f"bad amount {amount!r}: decimal number with at most {decimals} decimals")
    whole, _, frac = a.partition(".")
    return int(whole) * 10 ** decimals + int((frac + "0" * decimals)[:decimals])


def from_units(units: int, decimals: int = DECIMALS) -> str:
    s = str(units).rjust(decimals + 1, "0")
    return (s[:-decimals] + "." + s[-decimals:]).rstrip("0").rstrip(".")


def transfer_data(to: str, units: int, memo: str = "", goods: bool = False) -> bytes:
    """transfer(address,uint256) calldata + payment type byte (0x00 friends / 0x01 goods & services) + UTF-8 memo.
    Empty memo: the bare 68 bytes, or 69 bytes with 0x01 for a goods & services payment."""
    data = SEL_TRANSFER + bytes.fromhex(to[2:].rjust(64, "0")) + units.to_bytes(32, "big")
    full = (memo or "").strip().encode()
    end = min(len(full), MEMO_MAX_BYTES)
    while 0 < end < len(full) and (full[end] & 0xc0) == 0x80:      # cut only on a UTF-8 character boundary
        end -= 1
    m = full[:end]
    if m:
        return data + bytes([1 if goods else 0]) + m
    return data + (b"\x01" if goods else b"")


def register_for_data(ota: str, commitment: bytes) -> bytes:
    """StealthPool.registerCommitmentFor(address, bytes32) — activates a fresh recipient while paying it."""
    return SEL_REGISTER_FOR + bytes.fromhex(ota[2:].rjust(64, "0")) + commitment


# ─── commit key (authenticated commits, op-geth fork of 2026-11-17) ──────────
def commit_key_seed(spend_sk: bytes, address: str, epoch: int) -> bytes:
    return kk(D_COMMIT_KEY, spend_sk, bytes.fromhex(address[2:]), epoch.to_bytes(4, "big"))


def commit_key_element(seed: bytes, index: int) -> bytes:
    h = seed
    for _ in range(index):
        h = keccak256(h)
    return h


def commit_key_anchor_data(spend_sk: bytes, address: str, epoch: int) -> bytes:
    """Calldata of the anchoring reveal to COMMIT_KEY_REGISTRY: anchor(32) ‖ depth_u32be(4)."""
    return commit_key_element(commit_key_seed(spend_sk, address, epoch), COMMIT_KEY_LENGTH) + COMMIT_KEY_LENGTH.to_bytes(4, "big")


# ─── HTTP ────────────────────────────────────────────────────────────────────
class Bb84Error(Exception):
    def __init__(self, code: str, message: str):
        super().__init__(message)
        self.code = code


def http(method: str, url: str, body=None, timeout: int = 20):
    req = urllib.request.Request(url, method=method, headers={"User-Agent": USER_AGENT, "Accept": "application/json"})
    payload = None
    if body is not None:
        payload = json.dumps(body).encode()
        req.add_header("Content-Type", "application/json")
    try:
        with urllib.request.urlopen(req, payload, timeout=timeout) as r:
            return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        try:
            return e.code, json.loads(e.read() or b"{}")
        except Exception:
            return e.code, {}
    except Exception as e:
        raise Bb84Error("network", f"{url}: {e}") from None


def _ok(method, url, body=None, timeout=20):
    code, d = http(method, url, body, timeout)
    if code != 200:
        raise Bb84Error(d.get("code") or f"http_{code}", d.get("error") or f"{url} → HTTP {code}")
    return d


def chain_state(address: str) -> dict:
    """GET /api/connect/web/chain/<addr>: registered, depth, nonce, isContract, isMerchant, deleted,
    publishedCommitment, balances {USDC, EURC}, name, commitKey {last, depth}."""
    return _ok("GET", f"{RELAY}/chain/{address}")


def fees() -> dict:
    return _ok("GET", f"{RELAY}/fees")


def send_raw(raw: bytes) -> str:
    code, d = http("POST", f"{RELAY}/send", {"raw": "0x" + raw.hex()})
    if code != 200:
        raise Bb84Error(d.get("code") or f"http_{code}", d.get("error") or f"send → HTTP {code}")
    return d["txHash"]


def wait_receipt(h: str, timeout_s: float):
    end = time.time() + timeout_s
    while time.time() < end:
        try:
            rc = _ok("GET", f"{RELAY}/tx/{h}").get("receipt")
        except Bb84Error:
            rc = None
        if rc:
            return rc
        time.sleep(1.5)
    return None


def resolve_name(name: str) -> dict:
    """<label> or <label>.bb84.eth / .bb84.com → {address, name, commitment?}; raises for unknown/reserved/deleted."""
    label = name.strip().lower()
    label = re.sub(r"\.bb84\.(eth|com)$", "", label)
    if not LABEL_RE.match(label):
        raise Bb84Error("name", f"{name!r} is not a bb84 name (1-32 chars, a-z 0-9, inner hyphens)")
    code, d = http("GET", f"{ENS}/address/{label}")
    if code == 200 and ADDR_RE.match(str(d.get("address") or "")):
        return d
    if code == 409 and d.get("deleted"):
        raise Bb84Error("deleted", f"{label}.bb84.eth belongs to a deleted address; money sent there is lost")
    if code == 409:
        raise Bb84Error("reserved", f"{label}.bb84.eth is reserved")
    raise Bb84Error("not_found", f"{label}.bb84.eth is not registered")


# ─── the wallet ──────────────────────────────────────────────────────────────
class Wallet:
    """One OTA: root secrets (spendSK, viewSK, r), the derived hash chain and the on-chain address."""

    def __init__(self, spend_sk: bytes, view_sk: bytes, r: bytes, chain_length: int = CHAIN_LENGTH, address: str = None,
                 label: str = None, commit_key_epoch: int = 0, created_at: int = None, path: str = None):
        self.spend_sk, self.view_sk, self.r, self.chain_length = spend_sk, view_sk, r, chain_length
        self.chain = derive_chain(spend_sk, r, chain_length)
        self.commitment = self.chain[chain_length]
        # The address is fixed by the FIRST commitment; a renewed chain keeps the address.
        self.address = (address or ota_address(self.commitment)).lower()
        self.label, self.commit_key_epoch, self.created_at, self.path = label, commit_key_epoch, created_at or int(time.time()), path
        self.pending_renewal = None

    # — persistence —
    @classmethod
    def create(cls) -> "Wallet":
        return cls(secrets.token_bytes(32), secrets.token_bytes(32), secrets.token_bytes(32))

    @classmethod
    def load(cls, path: str) -> "Wallet":
        with open(path, encoding="utf-8") as f:
            d = json.load(f)
        if d.get("version") != 1 or d.get("chainId") != CHAIN_ID:
            raise Bb84Error("state", f"{path}: not a bb84 wallet file of version 1 for chain {CHAIN_ID}")
        w = cls(bytes.fromhex(d["spendSK"]), bytes.fromhex(d["viewSK"]), bytes.fromhex(d["r"]), int(d.get("chainLength", CHAIN_LENGTH)),
                d.get("address"), d.get("label"), int(d.get("commitKeyEpoch", 0)), d.get("createdAt"), path)
        w.pending_renewal = d.get("pendingRenewal")
        return w

    def to_dict(self) -> dict:
        d = {"version": 1, "chainId": CHAIN_ID, "spendSK": self.spend_sk.hex(), "viewSK": self.view_sk.hex(), "r": self.r.hex(),
             "chainLength": self.chain_length, "address": self.address, "commitment": self.commitment.hex(), "label": self.label,
             "commitKeyEpoch": self.commit_key_epoch, "createdAt": self.created_at}
        if self.pending_renewal:
            d["pendingRenewal"] = self.pending_renewal
        return d

    def save(self, path: str = None) -> None:
        path = path or self.path
        if not path:
            raise Bb84Error("state", "no wallet file path")
        tmp = path + ".tmp"
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(self.to_dict(), f, indent=1)
        os.replace(tmp, path)
        self.path = path

    @property
    def name(self):
        return f"{self.label}.bb84.eth" if self.label else None

    # — names & activation —
    def publish_commitment(self) -> None:
        """Lets payers activate this fresh address (StealthPool.registerCommitmentFor needs the commitment)."""
        _ok("POST", f"{ENS}/commitment", {"address": self.address, "commitment": "0x" + self.commitment.hex()})

    def register_name(self, label: str) -> str:
        """Claims <label>.bb84.eth. Free while the address is fresh (never spent): the still-unpublished
        commitment proves ownership — so call this BEFORE publish_commitment() on a new wallet. Later
        renames need the app's on-chain ownership proof and are not supported here."""
        label = label.strip().lower()
        if not LABEL_RE.match(label):
            raise Bb84Error("name", "label: 1-32 characters, a-z, 0-9, inner hyphens")
        code, d = http("POST", f"{ENS}/register", {"address": self.address, "label": label, "commitment": "0x" + self.commitment.hex()})
        if code != 200:
            raise Bb84Error("name_" + str(code), d.get("error") or f"register → HTTP {code}")
        self.label = label
        return self.name

    def auto_name(self) -> str:
        """The server-assigned adjective-noun-number name (GET /api/ens/name assigns one on first call)."""
        d = _ok("GET", f"{ENS}/name/{self.address}")
        self.label = d["label"]
        return self.name

    def sync_name(self) -> str:
        code, d = http("GET", f"{ENS}/label/{self.address}")
        if code == 200 and d.get("label"):
            self.label = d["label"]
        return self.name

    # — state —
    def status(self) -> dict:
        st = chain_state(self.address)
        if self.pending_renewal:
            self._settle_renewal(st)
        bal = {k: from_units(int(v)) for k, v in (st.get("balances") or {}).items()}
        return {"address": self.address, "name": st.get("name") or self.name, "activated": st["registered"],
                "stepsLeft": st["depth"], "balances": bal, "deleted": st.get("deleted", False),
                "commitKey": st.get("commitKey"), "payLink": f"{BASE}/pay/{self.name}" if (st.get('name') or self.name) else f"{BASE}/pay/{self.address}"}

    # — spending —
    def pay(self, to: str, amount: str, asset: str, memo: str = "", goods: bool = False, allow_suspect: bool = False,
            log=None) -> dict:
        """Pays `amount` of USDC/EURC to a bb84 name or 0x address. Activates a fresh recipient first (one
        step), anchors this wallet's commit key when due (one step), then pays (one step). Returns
        {txHash, to, amount, asset, goods}. Raises Bb84Error without having sent anything on every check."""
        log = log or (lambda s: None)
        asset = asset.upper()
        if asset not in TOKENS:
            raise Bb84Error("asset", "asset must be USDC or EURC")
        units = to_units(amount)
        if units <= 0:
            raise Bb84Error("amount", "amount must be > 0")
        to_addr = to.lower() if ADDR_RE.match(to) else resolve_name(to)["address"].lower()
        if to_addr == self.address:
            raise Bb84Error("recipient", "cannot pay the wallet's own address")
        me = chain_state(self.address)
        if me.get("deleted"):
            raise Bb84Error("deleted", "this wallet was deleted on-chain")
        if not me["registered"]:
            raise Bb84Error("unfunded", f"{self.address} is not activated yet: it has to receive a payment first "
                                        f"(share {self.name or self.address} with the payer)")
        rc = chain_state(to_addr)
        if rc.get("deleted"):
            raise Bb84Error("recipient_deleted", "the recipient address was deleted by its owner; a payment would be lost")
        register = False
        if rc["registered"]:
            if rc["depth"] == 0:
                raise Bb84Error("recipient_locked", "the recipient can never spend again (chain depth 0); nothing sent")
            # Registered by someone else with an unusual depth and never revealed since: its owner's wallet
            # may be unable to spend what it receives (see protocol.md §6). Opt in with allow_suspect.
            if rc.get("unrevealed") and rc["depth"] != CHAIN_LENGTH and not allow_suspect:
                raise Bb84Error("recipient_suspect", f"the recipient was activated with chain depth {rc['depth']} (expected "
                                                      f"{CHAIN_LENGTH}) and never spent; pass allow_suspect=True to pay anyway")
        elif not rc["isContract"] and not rc["isMerchant"]:
            if not rc.get("publishedCommitment"):
                raise Bb84Error("recipient_unregistered", "the recipient is not activated and published no commitment; "
                                                           "ask them to publish it (bb84.py new does) or pay them from the bb84 app first")
            register = True
        goods = goods or bool(rc["isMerchant"])
        bal = int((me.get("balances") or {}).get(asset, "0"))
        if bal < units:
            raise Bb84Error("balance", f"not enough {asset}: {from_units(bal)} available, {from_units(units)} needed")
        anchor_epoch = self._commit_key_anchor_due(me)
        need = 1 + (1 if register else 0) + (1 if anchor_epoch is not None else 0)
        if me["depth"] < need:
            raise Bb84Error("exhausted", f"only {me['depth']} hash-chain steps left, {need} needed")
        if anchor_epoch is not None:
            log(f"anchoring commit key (epoch {anchor_epoch})")
            self._spend_step(COMMIT_KEY_REGISTRY, commit_key_anchor_data(self.spend_sk, self.address, anchor_epoch), GAS_SELF, log)
            self.commit_key_epoch = anchor_epoch
            self.save() if self.path else None
        if register:
            log(f"activating recipient {to_addr}")
            self._spend_step(STEALTH_POOL, register_for_data(to_addr, bytes.fromhex(rc["publishedCommitment"][2:].rjust(64, "0"))), GAS_REGISTER, log)
        data = transfer_data(to_addr, units, memo, goods)
        log(f"paying {from_units(units)} {asset} to {to_addr}")
        h = self._spend_step(TOKENS[asset], data, GAS_GOODS if goods else GAS_TRANSFER, log)
        return {"txHash": h, "to": to_addr, "amount": from_units(units), "asset": asset, "goods": goods}

    def _commit_key_epoch_for(self, last: str, depth: int):
        """Epoch whose chain is anchored on-chain (keccak(element[depth-1]) == last), or None."""
        hint = self.commit_key_epoch
        for epoch in [hint] + [e for e in range(COMMIT_KEY_EPOCH_SEARCH) if e != hint]:
            seed = commit_key_seed(self.spend_sk, self.address, epoch)
            top = keccak256(commit_key_element(seed, depth - 1)) if depth > 0 else seed
            if top.hex() == last[2:].rjust(64, "0").lower():
                return epoch
        return None

    def _commit_key_anchor_due(self, me: dict):
        """Epoch to anchor before paying, or None: no key yet → 0; key running low → next epoch."""
        ck = me.get("commitKey") or {}
        last, depth = str(ck.get("last") or "0x0"), int(ck.get("depth") or 0)
        if int(last, 16) == 0:
            return 0
        if depth > COMMIT_KEY_REANCHOR_AT:
            return None
        epoch = self._commit_key_epoch_for(last, depth)
        return None if epoch is None else epoch + 1

    def _commit_preimage(self, me: dict) -> bytes:
        """Element the next HashCommitTx must carry (zero = no usable key → unauthenticated commit)."""
        ck = me.get("commitKey") or {}
        last, depth = str(ck.get("last") or "0x0"), int(ck.get("depth") or 0)
        if int(last, 16) == 0 or depth == 0:
            return ZERO32
        epoch = self._commit_key_epoch_for(last, depth)
        if epoch is None:
            raise Bb84Error("commit_key", "this address has a commit key this wallet file cannot derive (other wallet, other seed); "
                                          "commits would be rejected until the key is exhausted")
        self.commit_key_epoch = epoch
        return commit_key_element(commit_key_seed(self.spend_sk, self.address, epoch), depth - 1)

    def _spend_step(self, to: str, data: bytes, gas: int, log) -> str:
        """Commit + reveal for one hash-chain step. The preimage comes from the on-chain depth, never a local
        counter: chain[depth-1]. On the last step the reveal carries a renewed chain (new r)."""
        me = chain_state(self.address)
        if self.pending_renewal:
            self._settle_renewal(me)
        depth = me["depth"]
        if depth < 1:
            raise Bb84Error("exhausted", "hash chain used up")
        preimage = self.chain[depth - 1]
        commit_preimage = self._commit_preimage(me)
        new_commitment, new_len, renewal = ZERO32, 0, None
        if depth == 1:                                           # last element: renew the chain in the same reveal
            new_r = secrets.token_bytes(32)
            new_chain = derive_chain(self.spend_sk, new_r, CHAIN_LENGTH)
            new_commitment, new_len = new_chain[CHAIN_LENGTH], CHAIN_LENGTH
            renewal = {"r": new_r.hex(), "commitment": new_commitment.hex()}
            self.pending_renewal = renewal
            if self.path:
                self.save()
        f = fees()
        fee_cap, tip_cap = min(int(f["gasFeeCap"]), MAX_FEE_CAP), int(f["gasTipCap"])
        tip_cap = min(tip_cap, fee_cap)
        frm, to_b = bytes.fromhex(self.address[2:]), bytes.fromhex(to[2:])
        nonce = int(me["nonce"])
        commit_hash = None
        for attempt in range(3):
            commit, reveal = build_spend_txs(frm, nonce, to_b, data, gas, fee_cap, tip_cap, preimage, commit_preimage, new_commitment, new_len)
            try:
                commit_hash = send_raw(commit)
                break
            except Bb84Error as e:
                if "underpriced" in str(e).lower() and attempt < 2 and fee_cap < MAX_FEE_CAP:
                    fee_cap = min(fee_cap * 2, MAX_FEE_CAP)
                    tip_cap = min(tip_cap * 2, fee_cap)
                    continue
                raise
        log(f"  commit {commit_hash}")
        if not wait_receipt(commit_hash, 90):
            raise Bb84Error("timeout", f"commit {commit_hash} not confirmed within 90 s; nothing was sent — it expires after "
                                       f"{COMMIT_EXPIRE_BLOCKS} blocks, retry then")
        reveal_hash = send_raw(reveal)
        log(f"  reveal {reveal_hash}")
        rc = wait_receipt(reveal_hash, 90)
        if rc is None:
            raise Bb84Error("timeout", f"reveal {reveal_hash} not confirmed within 90 s; check status later")
        if renewal:                                              # the step executed: the chain is renewed either way
            self._adopt_renewal(renewal)
        if rc.get("status") != "0x1":
            raise Bb84Error("reverted", f"reveal {reveal_hash} executed but reverted (e.g. balance too low); the step is consumed")
        return reveal_hash

    def _adopt_renewal(self, renewal: dict) -> None:
        self.r = bytes.fromhex(renewal["r"])
        self.chain = derive_chain(self.spend_sk, self.r, CHAIN_LENGTH)
        self.commitment, self.chain_length, self.pending_renewal = self.chain[CHAIN_LENGTH], CHAIN_LENGTH, None
        if self.path:
            self.save()

    def _settle_renewal(self, st: dict) -> None:
        """A renewal reveal whose receipt we never saw: depth back at CHAIN_LENGTH means it landed."""
        if st["depth"] == CHAIN_LENGTH and st["registered"]:
            self._adopt_renewal(self.pending_renewal)
        elif st["depth"] == 0 and st["registered"]:
            raise Bb84Error("exhausted", "the chain ended without a renewal; this address can never spend again")
        elif st["depth"] > 1:                                    # the old chain is still live: the renewal never executed
            self.pending_renewal = None
            if self.path:
                self.save()


# ─── offline self-test (vectors from the bb84 app / web wallet build) ────────
VECTORS = {
    "spendSK": "4a30ffbf97c7df9f07ec26e718a8f6cfaaa13d074dd0deddef47e3dde8d663ba",
    "viewSK": "722fed365ef7c360f5d431b36ef76148794d7f9611aa5e4128f0ffc59ff58f22",
    "r": "659298cde88f0e5b10d8b00b35eb2a2f14ed97bcb20f619d38425df6a02650d2",
    "address": "0xb4b030d0d7d47943e039a6eddc5b711f8827efe4",
    "commitment": "419d3b69febc6b506ddf7e7cb6f7cf4c428344822b6151031e1833781269caba",
    "chain0": "cafc5af443b7a8c8964080e75708241336feb636055a06c410d93bb2a2da9dd5",
    "chain999": "d08271239a2797952933f75c03a827f77597c64b5f373cac11336f6bb8ba3592",
    "data": "a9059cbb00000000000000000000000042ed65db186dfdbc1ba5f0e979dceaeb4f63014d000000000000000000000000000000000000000000000000000000000016e360014b616666656520c2b72070725f303132333435363738396162636465663031323334353637",
    "commit": "7cf84b840281ec0894b4b030d0d7d47943e039a6eddc5b711f8827efe480a0c9b79dcea5bc0094fa4568976f981d1c28714fe04db66190d86bc13e668b3267830186a0843b9aca008316e36081fa",
    "reveal": "7ff9010f840281ec0894b4b030d0d7d47943e039a6eddc5b711f8827efe4019450590ee131edc98a7213c91ae82e3e8987b9b5ee8083027100843b9aca008316e360b86aa9059cbb00000000000000000000000042ed65db186dfdbc1ba5f0e979dceaeb4f63014d000000000000000000000000000000000000000000000000000000000016e360014b616666656520c2b72070725f303132333435363738396162636465663031323334353637a0478fb7cbb79211b19b3533af1c9319ca030dd83b04249f9a659348e8e23e8389a0d08271239a2797952933f75c03a827f77597c64b5f373cac11336f6bb8ba359280a0000000000000000000000000000000000000000000000000000000000000000080",
}


def selftest() -> bool:
    ok = True

    def check(name, cond):
        nonlocal ok
        ok &= bool(cond)
        print(("  ok   " if cond else "  FAIL ") + name)

    check("keccak256('')", keccak256(b"").hex() == "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
    check("keccak256('abc')", keccak256(b"abc").hex() == "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45")
    check("pure-python keccak = backend (" + KECCAK_BACKEND + ")", _pure_keccak256(b"x" * 300) == keccak256(b"x" * 300))
    v = VECTORS
    w = Wallet(bytes.fromhex(v["spendSK"]), bytes.fromhex(v["viewSK"]), bytes.fromhex(v["r"]))
    check("chain[0]", w.chain[0].hex() == v["chain0"])
    check("chain[999]", w.chain[999].hex() == v["chain999"])
    check("commitment = chain[1000]", w.commitment.hex() == v["commitment"])
    check("address", w.address == v["address"])
    data = transfer_data("0x42ed65db186dfdbc1ba5f0e979dceaeb4f63014d", 1500000, "Kaffee · pr_0123456789abcdef01234567", True)
    check("transfer calldata + goods flag + memo", data.hex() == v["data"])
    commit, reveal = build_spend_txs(bytes.fromhex(w.address[2:]), 0, bytes.fromhex(TOKENS["USDC"][2:]), data, 160000,
                                     1000000000, 1500000, w.chain[999])
    check("HashCommitTx bytes", commit.hex() == v["commit"])
    check("HashRevealTx bytes", reveal.hex() == v["reveal"])
    check("registerCommitmentFor selector", SEL_REGISTER_FOR.hex() == "79176c17")
    check("to_units('12.5') = 12500000", to_units("12.5") == 12500000)
    print("selftest", "passed" if ok else "FAILED")
    return ok


# ─── command line ────────────────────────────────────────────────────────────
def main(argv=None) -> int:
    import argparse
    p = argparse.ArgumentParser(description="bb84 reference client (protocol v1). Wallet file holds the secret — see the module docstring.")
    p.add_argument("--state", default=os.environ.get("BB84_WALLET_FILE", "bb84-wallet.json"), help="wallet file (default bb84-wallet.json)")
    sub = p.add_subparsers(dest="cmd", required=True)
    s_new = sub.add_parser("new", help="create a wallet, publish its commitment, claim a name")
    s_new.add_argument("--name", help="wished label (<label>.bb84.eth); default: a server-assigned name")
    sub.add_parser("status", help="address, name, activation, remaining steps, balances")
    s_pay = sub.add_parser("pay", help="pay a bb84 name or 0x address")
    s_pay.add_argument("to"); s_pay.add_argument("amount"); s_pay.add_argument("asset", choices=["USDC", "EURC", "usdc", "eurc"])
    s_pay.add_argument("--memo", default=""); s_pay.add_argument("--goods", action="store_true", help="goods & services (0.5 %% fee, buyer protection)")
    s_pay.add_argument("--allow-suspect", action="store_true")
    s_name = sub.add_parser("name", help="claim a name (fresh wallets only; see Wallet.register_name)")
    s_name.add_argument("label")
    sub.add_parser("selftest", help="offline check of the cryptography")
    a = p.parse_args(argv)
    try:
        if a.cmd == "selftest":
            return 0 if selftest() else 1
        if a.cmd == "new":
            if os.path.exists(a.state):
                print(f"{a.state} exists — refusing to overwrite a wallet", file=sys.stderr)
                return 2
            w = Wallet.create()
            w.save(a.state)
            if a.name:
                w.register_name(a.name)
            else:
                w.auto_name()
            w.publish_commitment()
            w.save()
            print(json.dumps({"address": w.address, "name": w.name, "payLink": f"{BASE}/pay/{w.name}", "state": a.state,
                              "note": "Not activated yet: it becomes usable when it receives its first payment (any bb84 user can pay the name or address)."}, indent=1))
            return 0
        w = Wallet.load(a.state)
        if a.cmd == "status":
            w.sync_name()
            st = w.status()
            w.save()
            print(json.dumps(st, indent=1))
            return 0
        if a.cmd == "name":
            print(w.register_name(a.label)); w.save(); return 0
        if a.cmd == "pay":
            res = w.pay(a.to, a.amount, a.asset, memo=a.memo, goods=a.goods, allow_suspect=a.allow_suspect, log=lambda s: print(s, file=sys.stderr))
            w.save()
            print(json.dumps(res, indent=1))
            return 0
    except Bb84Error as e:
        print(json.dumps({"error": str(e), "code": e.code}), file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
