// Stealth payments on Ethereum (ERC-5564, scheme 1) with viem and @noble/curves.
import { secp256k1 } from '@noble/curves/secp256k1';
import { bytesToHex, hexToBytes, keccak256, parseAbi, type Account, type Chain, type Hex, type PublicClient, type Transport, type WalletClient } from 'viem';
import { publicKeyToAddress } from 'viem/accounts';

const ANNOUNCER = '0x55649E01B5Df198D18D95b5cc5051630cfD45564'; // same address on every chain
const abi = parseAbi([
  'function announce(uint256 schemeId, address stealthAddress, bytes ephemeralPubKey, bytes metadata)',
  'event Announcement(uint256 indexed schemeId, address indexed stealthAddress, address indexed caller, bytes ephemeralPubKey, bytes metadata)',
]);
const N = secp256k1.CURVE.n;
const randomKey = () => bytesToHex(secp256k1.utils.randomPrivateKey());
const pubOf = (k: Hex) => bytesToHex(secp256k1.getPublicKey(hexToBytes(k), true)); // compressed, 33 bytes
// keccak256 of the shared point. Its first byte is the view tag.
const secret = (priv: Hex, pub: Hex) => keccak256(secp256k1.getSharedSecret(hexToBytes(priv), hexToBytes(pub), true));
// The one-time address: spending public key + secret * G.
const stealthOf = (spendPub: Hex, h: Hex) => publicKeyToAddress(bytesToHex(secp256k1.ProjectivePoint.fromHex(spendPub.slice(2))
  .add(secp256k1.ProjectivePoint.BASE.multiply(BigInt(h) % N)).toRawBytes(false)));

// 1. Receiver: two keys. Share the meta-address once; keep both private keys.
export function newKeys() {
  const spend = randomKey(), view = randomKey();
  return { spend, view, meta: `st:eth:0x${pubOf(spend).slice(2)}${pubOf(view).slice(2)}` };
}

// 2. Sender: derive a fresh address, announce it, then pay it.
export async function pay(wallet: WalletClient<Transport, Chain, Account>, meta: string, value: bigint) {
  const m = meta.split(':').pop()!.slice(2);
  const spendPub = `0x${m.slice(0, 66)}` as Hex, viewPub = `0x${m.slice(66)}` as Hex;
  const eph = randomKey();
  const h = secret(eph, viewPub);
  const to = stealthOf(spendPub, h);
  // Metadata: view tag, 0xeeeeeeee, the ETH placeholder token 0xEeee...EeeE, amount (57 bytes).
  const metadata = `${h.slice(0, 4)}${'ee'.repeat(24)}${value.toString(16).padStart(64, '0')}` as Hex;
  await wallet.writeContract({ address: ANNOUNCER, abi, functionName: 'announce', args: [1n, to, pubOf(eph), metadata] });
  const hash = await wallet.sendTransaction({ to, value });
  return { to, hash };
}

// 3. Receiver: scan announcements. The view tag skips 255 of 256 strangers' payments early.
export async function scan(client: PublicClient, keys: { spend: Hex; view: Hex }, fromBlock = 0n) {
  const logs = await client.getContractEvents({ address: ANNOUNCER, abi, eventName: 'Announcement', args: { schemeId: 1n }, fromBlock });
  const found: { address: Hex; privateKey: Hex }[] = [];
  for (const { args: a } of logs) {
    if (!a.ephemeralPubKey || !a.metadata || !a.stealthAddress) continue;
    let h: Hex;
    try { h = secret(keys.view, a.ephemeralPubKey); } catch { continue; } // anyone can announce garbage
    if (h.slice(0, 4) !== a.metadata.slice(0, 4).toLowerCase()) continue; // view tag: not ours
    if (stealthOf(pubOf(keys.spend), h) !== a.stealthAddress) continue; // full check
    // 4. Only the receiver can spend: p_stealth = p_spend + secret (mod n).
    const p = (BigInt(keys.spend) + BigInt(h)) % N;
    found.push({ address: a.stealthAddress, privateKey: `0x${p.toString(16).padStart(64, '0')}` });
  }
  return found;
}
