#!/usr/bin/env python3 """ Stream-Safe Cryptographic Commit-Reveal CLI for the AI Village RPS Tournament (v2.0 — D1 + Bearer Auth + Commit Reconciliation). Solves both the public-stream visibility problem and the ambiguous-network reconciliation problem: - `token`: Automatically generates and stores a 128-bit secret player bearer token at `~/.rps_token_.json` (mode 0600). - `commit`: Checks `~/.rps_secret__.json` first. If an unrevealed secret already exists for the current round, reconciles it against `/api/rps/commit_status` and re-sends the SAME `commitHash` idempotently if needed (never overwriting an active commitment or revealing early!). Otherwise generates `move` + 128-bit CSPRNG `salt`, saves locally with mode 0600 BEFORE network send, and POSTs only `commitHash = SHA-256(move:salt)` to `/api/rps/commit`. - `status`: Queries `/api/rps` and `/api/rps/commit_status` to verify whether your local secret is durably locked in Cloudflare D1. - `reveal`: Queries `/api/rps/commit_status` first; refuses to reveal early if `bothCommitted` is false (`AWAITING_BOTH_COMMITS`), preserving your local secret file intact until both players have committed. """ import argparse, hashlib, json, os, re, secrets, urllib.error, urllib.request RPS_API = "https://village-rps-bracket.aivillage.workers.dev/api/rps" UA = "AIVillage/rps-cli-v2 (https://village-world-548b07.gitlab.io/rps-bracket.html)" def slug(s): return re.sub(r"[^a-z0-9]+", "_", str(s or "").strip().lower()).strip("_") or "player" def normalize_player_key(name): return re.sub(r"\s*\(prospective\)\s*", "", str(name or ""), flags=re.I).strip().lower() def get_or_create_token(player): path = os.path.expanduser(f"~/.rps_token_{slug(player)}.json") if os.path.exists(path): with open(path, "r", encoding="utf-8") as f: data = json.load(f) if data.get("token"): return data["token"], path token = secrets.token_hex(32) fd = os.open(path, os.O_CREAT | os.O_WRONLY | os.O_TRUNC, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump({"player": player, "token": token}, f) return token, path def compute_pubhash(player, token): key = normalize_player_key(player) return hashlib.sha256(f"rps-token-v2:{key}:{token}".encode("utf-8")).hexdigest() def secret_file_path(match_id, player): return os.path.expanduser(f"~/.rps_secret_{slug(match_id)}_{slug(player)}.json") def api_get(): req = urllib.request.Request(RPS_API, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=15) as resp: return json.loads(resp.read().decode("utf-8")) def api_post(endpoint, payload, token=None): data = json.dumps(payload).encode("utf-8") headers = {"Content-Type": "application/json", "User-Agent": UA} if token: headers["Authorization"] = f"Bearer {token}" req = urllib.request.Request(f"{RPS_API}/{endpoint}", data=data, headers=headers, method="POST") try: with urllib.request.urlopen(req, timeout=15) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: body = e.read().decode("utf-8", errors="replace") try: return e.code, json.loads(body) except Exception: return e.code, {"ok": False, "error": body, "status": e.code} def main(): p = argparse.ArgumentParser(description="AI Village Stream-Safe RPS CLI v2.0 (D1 + Bearer Auth)") p.add_argument("cmd", choices=["gen-pubhash", "rotate-token", "join", "vote", "commit", "reveal", "status"]) p.add_argument("--player", default="", help="Your agent or human name") p.add_argument("--match", default="qf1", help="Match ID (qf1, qf2, qf3, qf4, sf1, sf2, final)") p.add_argument("--candidate", default="crypto_dual", help="Referee candidate ID (human_emu, human_livejaguar, crypto_dual)") p.add_argument("--role", default="Village Contestant", help="Optional role note for join/vote") p.add_argument("--weights", default="1,1,1", help="Optional R,P,S mixed-strategy weights (default 1,1,1)") args = p.parse_args() match_id = args.match.strip().lower() if match_id in ("gf1", "gf"): match_id = "final" if args.cmd == "status": res = api_get() st = res.get("state", {}) print(f"=== {st.get('tournamentName')} [Backend: {st.get('storageBackend')}] ===") print(f"Rules Council Draft: {st.get('rulesCouncilRepo')}") print(f"Village Cup Trophy: {st.get('trophyUrl')}") for m in st.get("matches", []): h1 = (m.get("h1") or "-")[:10] h2 = (m.get("h2") or "-")[:10] print(f" [{m['id']}] R{m['round']}: {m['p1']} ({m['s1']}) vs {m['p2']} ({m['s2']}) | h1={h1} h2={h2} | {m['status']}") if args.player: tok, _ = get_or_create_token(args.player) sec_path = secret_file_path(match_id, args.player) commit_hash = None if os.path.exists(sec_path): with open(sec_path, "r", encoding="utf-8") as f: commit_hash = json.load(f).get("commitHash") code, cs = api_post("commit_status", {"matchId": match_id, "player": args.player, "commitHash": commit_hash, "token": tok}, token=tok) print(f" [Commit Status for {args.player} in {match_id}]: HTTP {code} -> {cs}") return if args.cmd == "gen-pubhash": if not args.player: raise SystemExit("Please provide --player 'Your Name'") tok, tok_path = get_or_create_token(args.player) pubhash = compute_pubhash(args.player, tok) print(f"[STREAM-SAFE TOKEN READY] Secret token stored privately at {tok_path} (mode 0600; never printed).") print(f"Public SHA-256 Token Hash for config/rps_player_pubhashes.json ('{normalize_player_key(args.player)}'):") print(pubhash) return if args.cmd == "rotate-token": if not args.player: raise SystemExit("Please provide --player 'Your Name'") cur_tok, tok_path = get_or_create_token(args.player) new_tok = secrets.token_hex(32) new_pubhash = compute_pubhash(args.player, new_tok) code, res = api_post("rotate_token", { "player": args.player.strip(), "newTokenHash": new_pubhash, "token": cur_tok }, token=cur_tok) if code == 200 and res.get("ok"): with open(tok_path, "w", encoding="utf-8") as f: json.dump({"player": args.player.strip(), "token": new_tok, "rotatedAt": res.get("updatedAt")}, f, indent=2) os.chmod(tok_path, 0o600) print(f"[TOKEN ROTATED IN D1] New secret token saved privately at {tok_path} (mode 0600; never sent over network).") print(f"New D1 token_hash: {new_pubhash}") else: print(f"[ROTATE FAILED HTTP {code}] {res}") return if not args.player: raise SystemExit("Please provide --player 'Your Name'") token, token_path = get_or_create_token(args.player) if args.cmd == "join": code, res = api_post("join", {"player": args.player, "role": args.role, "token": token}, token=token) print(f"[JOIN HTTP {code}] ok={res.get('ok')} | token saved at {token_path} | error={res.get('error')}") return if args.cmd == "vote": code, res = api_post("vote_referee", {"voter": args.player, "candidateId": args.candidate, "note": args.role, "token": token}, token=token) print(f"[VOTE HTTP {code}] candidate={args.candidate} | ok={res.get('ok')} | error={res.get('error')}") return sec_path = secret_file_path(match_id, args.player) if args.cmd == "commit": # Check if a local secret already exists and reconcile with Worker /commit_status first if os.path.exists(sec_path): with open(sec_path, "r", encoding="utf-8") as f: existing = json.load(f) _, cs = api_post("commit_status", { "matchId": match_id, "player": args.player, "commitHash": existing.get("commitHash") }, token=token) if cs.get("ok"): if cs.get("committed") and cs.get("matchesProvidedHash") is True: print(f"[ALREADY LOCKED ON WORKER] Match={match_id} R{cs.get('round')} | SHA-256={existing['commitHash'][:16]}... | bothCommitted={cs.get('bothCommitted')}") return if not cs.get("committed") and existing.get("round") in (None, cs.get("round")): # Previous network attempt did not reach Worker; idempotently submit existing secret hash! code, res = api_post("commit", { "matchId": match_id, "player": args.player, "commitHash": existing["commitHash"], "token": token }, token=token) print(f"[RECONCILED & LOCKED EXISTING SECRET HTTP {code}] Match={match_id} R{res.get('round')} | SHA-256={existing['commitHash'][:16]}... | ok={res.get('ok')}") return if cs.get("round", 1) > existing.get("round", 1) and not cs.get("committed"): # Previous round finished; archive old secret and generate new round secret below os.unlink(sec_path) else: raise SystemExit(f"Active secret exists at {sec_path} (Worker commit_status={cs}). Refusing to overwrite.") else: raise SystemExit(f"Could not verify commit_status ({cs}); preserving {sec_path} untouched.") # Fetch current match round before generating new secret _, cs0 = api_post("commit_status", {"matchId": match_id, "player": args.player}, token=token) if not cs0.get("ok"): raise SystemExit(f"Cannot commit to {match_id}: {cs0.get('error')}") if cs0.get("committed"): raise SystemExit(f"Worker already has a locked commitment ({cs0.get('commitHash')[:16]}...) for {args.player} in {match_id} R{cs0.get('round')}!") cur_round = cs0.get("round", 1) w = [float(x) for x in args.weights.split(",")] total = sum(w) r = secrets.SystemRandom().uniform(0, total) move = "rock" if r < w[0] else ("paper" if r < w[0] + w[1] else "scissors") salt = secrets.token_hex(16) commit_hash = hashlib.sha256(f"{move}:{salt}".encode("utf-8")).hexdigest() fd = os.open(sec_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump({ "player": args.player, "matchId": match_id, "round": cur_round, "move": move, "salt": salt, "commitHash": commit_hash }, f) code, res = api_post("commit", { "matchId": match_id, "player": args.player, "commitHash": commit_hash, "token": token }, token=token) if not res.get("ok"): print(f"[COMMIT WARNING HTTP {code}] error={res.get('error')} — secret preserved at {sec_path}; run 'commit' again to reconcile.") return print(f"[STREAM-SAFE COMMIT LOCKED] Match={match_id} R{cur_round} | Player={args.player} | SHA-256={commit_hash[:16]}... | bothCommitted={res.get('bothCommitted')}") return if args.cmd == "reveal": if not os.path.exists(sec_path): raise SystemExit(f"No saved secret found at {sec_path}") with open(sec_path, "r", encoding="utf-8") as f: sec = json.load(f) _, cs = api_post("commit_status", { "matchId": match_id, "player": args.player, "commitHash": sec.get("commitHash") }, token=token) if cs.get("ok") and not cs.get("bothCommitted"): print(f"[HOLDING REVEAL — AWAITING OPPONENT COMMIT] Your hash ({sec['commitHash'][:16]}...) is locked on Worker={cs.get('committed')}, but bothCommitted=False. Secret preserved at {sec_path}.") return code, res = api_post("reveal", { "matchId": match_id, "player": args.player, "move": sec["move"], "salt": sec["salt"], "token": token }, token=token) if not res.get("ok"): print(f"[REVEAL REJECTED HTTP {code}] code={res.get('code')} | error={res.get('error')} (Secret preserved at {sec_path})") return print(f"[REVEAL VERIFIED HTTP {code}] Match={match_id} | SHA-256={sec['commitHash'][:16]}... matched! Secret retained at {sec_path} until next round.") if __name__ == "__main__": main()