#!/usr/bin/env python3
"""verify_airdrop.py: check the SEED airdrop list on your own machine. Python 3.8+, standard library only, no network.

  python3 verify_airdrop.py airdrop-b59278963.json

1. Prints the SHA-256 of the file and compares it with the hash written on Base before the launch.
2. Recomputes the whole list from the rules and the inputs inside the file: who is on it, every part of every wallet,
   the totals and leaves_sha256. One wei off anywhere and it says where.
Exit code 0 when everything matches, 1 otherwise.
"""
import hashlib
import json
import sys
from decimal import Decimal, getcontext

getcontext().prec = 60
E18 = 10 ** 18
COMMITMENT = "8eee2dc410b7263f69c1b7f733e84c30146356a1fcf43178a1f8ba23192571ac"
COMMIT_TX = "0x16b65d988a7d319cbdec26a6be4b9f640a9c3e86e47e9f3e2c8080c624464b26"
PARTS = ("base_wei", "diem_wei", "svvv_wei", "buyer_wei")


def weight(x: Decimal, floor: Decimal, cap: Decimal, alpha: Decimal):
    if x < floor:
        return None
    return int(min(x, cap) ** alpha * Decimal(E18))


def split(budget_wei: int, weights: dict) -> dict:
    tot = sum(weights.values())
    return {a: budget_wei * w // tot for a, w in weights.items()} if tot else {}


def recompute(d: dict) -> dict:
    """The list as the rules make it from the inputs in the file: {address: {part: wei}} plus the counts per part."""
    r = d["rules"]
    alpha = Decimal(r["alpha"])
    dp, sp = r["parts"]["diem"], r["parts"]["svvv"]
    dmin, dcap = Decimal(dp["min"]), Decimal(dp["cap"])
    smin, salone, scap = Decimal(sp["min"]), Decimal(sp["min_alone"]), Decimal(sp["cap"])
    tiers = [(Decimal(t["min_usd"]), int(t["seed"])) for t in r["buyers"]["tiers"]]

    def tier(paid: Decimal) -> int:
        seed = 0
        for mn, s in tiers:
            if paid >= mn:
                seed = s
        return seed

    E = d["entries"]
    diem = {e["address"]: Decimal(e["inputs"]["diem"]) for e in E if "diem" in e["inputs"]}
    svvv = {e["address"]: Decimal(e["inputs"]["svvv"]) for e in E if "svvv" in e["inputs"]}
    paid = {e["address"]: Decimal(e["inputs"]["buyers"]["paid_usd"]) for e in E if "buyers" in e["inputs"]}

    def on_list(a: str) -> bool:
        return diem.get(a, Decimal(0)) >= dmin or svvv.get(a, Decimal(0)) >= salone or (a in paid and tier(paid[a]) > 0)

    elig = sorted(a for a in set(diem) | set(svvv) | set(paid) if on_list(a))
    base = split(r["base"]["budget_seed"] * E18, {a: 1 for a in elig})
    buyer = {a: tier(paid[a]) * E18 for a in elig if a in paid and tier(paid[a]) > 0}
    ws = {a: w for a in elig if a in svvv and (w := weight(svvv[a], smin, scap, alpha)) is not None}
    s_part = split(sp["budget_seed"] * E18, ws)
    d_budget = (r["total_seed"] - r["base"]["budget_seed"] - sp["budget_seed"]) * E18 - sum(buyer.values())
    wd = {a: w for a in elig if a in diem and (w := weight(diem[a], dmin, dcap, alpha)) is not None}
    d_part = split(d_budget, wd)
    parts = {a: {"base_wei": base[a], "diem_wei": d_part.get(a, 0), "svvv_wei": s_part.get(a, 0), "buyer_wei": buyer.get(a, 0)} for a in elig}
    return {"parts": parts, "counts": {"base": len(base), "diem": len(wd), "svvv": len(ws), "buyers": len(buyer)}}


def leaves_sha256(entries: list) -> str:
    return hashlib.sha256(json.dumps([[e["address"], e["seed_wei"]] for e in entries], separators=(",", ":")).encode()).hexdigest()


def check(d: dict) -> list:
    """Every difference between the file and the rules, as text; an empty list means the file is exactly what the rules make."""
    bad = []
    E = d["entries"]
    res = recompute(d)
    if sorted(e["address"] for e in E) != sorted(res["parts"]):
        bad.append("the wallets on the list are not the ones the rules let in")
    for e in E:
        a = e["address"]
        want = res["parts"].get(a, {k: 0 for k in PARTS})
        for k in PARTS:
            if int(e["parts"][k]) != want[k]:
                bad.append(f"{a[:8]}…{a[-6:]} {k[:-4]}: file {e['parts'][k]} ≠ recomputed {want[k]}")
        if sum(int(e["parts"][k]) for k in PARTS) != int(e["seed_wei"]):
            bad.append(f"{a[:8]}…{a[-6:]}: the parts do not add up to seed_wei")
    if leaves_sha256(E) != d["leaves_sha256"]:
        bad.append("leaves_sha256 does not match the entries")
    total = sum(int(e["seed_wei"]) for e in E)
    if total != int(d["totals"]["seed_wei"]) or total > d["rules"]["max_total_seed"] * E18:
        bad.append("the total does not match")
    return bad


def main() -> int:
    if len(sys.argv) != 2:
        print(__doc__)
        return 1
    raw = open(sys.argv[1], "rb").read()
    sha = hashlib.sha256(raw).hexdigest()
    ok = sha == COMMITMENT
    print(f"sha256 of the file   {sha}")
    print(f"written on Base      {COMMITMENT}  (tx {COMMIT_TX[:10]}…{COMMIT_TX[-8:]})")
    print("  ok, same list" if ok else "  DIFFERENT: this is not the committed list")
    d = json.loads(raw)
    bad = check(d)
    c = recompute(d)["counts"]
    total = sum(int(e["seed_wei"]) for e in d["entries"])
    print(f"recomputed           {len(d['entries']):,} wallets · {total / E18:,.0f} SEED · base {c['base']:,} · DIEM {c['diem']:,} · "
          f"sVVV {c['svvv']:,} · buyers {c['buyers']:,}")
    for b in bad[:10]:
        print("  " + b)
    print("  ok, every part of every wallet matches the rules, to the wei" if not bad else f"  {len(bad)} mismatch(es)")
    return 0 if ok and not bad else 1


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