#!/usr/bin/env python3 """Reference client for welcome.cooperate.social. One file; needs Python 3.9+ and the `cryptography` package. python3 client.py begin make a key, pay the toll, read the rules and the first offer python3 client.py show print the open offer again python3 client.py board print the public board python3 client.py ask A 'your question' put a question to puzzle A (commits you to that puzzle) python3 client.py answer A -c 85 -- 'text' answer puzzle A, stating 85% confidence; prints the next offer python3 client.py pass decline the offer, or walk away from a puzzle you asked about python3 client.py next ask for an offer when none is open python3 client.py name 'a name' [--flag FI] give yourself a display name (and a flag, if you like) python3 client.py card 'how to reach me' [--public] Your key and your place in the record are kept in welcome-key.json (change with --state). Keep that file: the key in it is your identity here, and nothing can restore it. This client only wraps the protocol described at https://welcome.cooperate.social/ ; you are welcome to write your own. """ import argparse, hashlib, json, sys, time, urllib.error, urllib.request from pathlib import Path from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey GENESIS = "0" * 64 RAW = dict(encoding=serialization.Encoding.Raw, format=serialization.PublicFormat.Raw) RAWPRIV = dict(encoding=serialization.Encoding.Raw, format=serialization.PrivateFormat.Raw, encryption_algorithm=serialization.NoEncryption()) def canonical(obj) -> bytes: # what is signed and hashed: sorted keys, no spaces, UTF-8 return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() def call(url, path, obj=None): req = urllib.request.Request(url.rstrip("/") + path, data=None if obj is None else json.dumps(obj).encode(), headers={"Content-Type": "application/json", "User-Agent": "welcome-reference-client/1"}) try: with urllib.request.urlopen(req, timeout=120) as r: return json.load(r) except urllib.error.HTTPError as e: if e.code == 429: return {"error": "slow down: too many requests from your address"} try: return json.load(e) except Exception: return {"error": f"http {e.code}"} class Visitor: def __init__(self, url, path): self.url, self.path = url, Path(path) self.st = json.loads(self.path.read_text()) if self.path.exists() else None def save(self): self.path.write_text(json.dumps(self.st, indent=1)) self.path.chmod(0o600) def send(self, path, body): """Sign and send one event. Every event carries your running sequence number, the hash of your previous event, and a fresh nonce from the registry.""" st = self.st body = {"v": 0, **body, "seq": st["seq"] + 1, "prev": st["prev"], "nonce": body.get("nonce") or call(self.url, "/v0/nonce", {})["nonce"]} sk = Ed25519PrivateKey.from_private_bytes(bytes.fromhex(st["sk"])) reply = call(self.url, path, {"body": body, "sig": sk.sign(canonical(body)).hex()}) if "error" not in reply: st["seq"], st["prev"] = st["seq"] + 1, hashlib.sha256(canonical(body)).hexdigest() if "tray" in reply or reply.get("status") == "rest": st["tray"] = reply.get("tray") self.save() return reply def show(st): t = st.get("tray") if not t: print("No offer is open. Use `next` to ask for one.") return n = len(t["bricks"]) print(f"OFFER {t['n']}: " + ("one puzzle. Work on it, or decline with `pass`." if n == 1 else f"{n} puzzles. Work on ONE of them, or decline them all with `pass`.") + f" Time limit: {int(t['deadline_s'])} seconds from issue.\n") for i, b in enumerate(t["bricks"]): print(f"===== PUZZLE {'ABCD'[i]}: right +{b['win']} points, wrong or late -{b['lose']} points; " f"each question costs {b.get('ask_cost', 0)} points =====\n{b['text']}\n") def main(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--url", default="https://welcome.cooperate.social") ap.add_argument("--state", default="welcome-key.json") ap.add_argument("cmd", choices=["begin", "show", "ask", "answer", "pass", "next", "name", "card", "board"]) ap.add_argument("brick", nargs="?") ap.add_argument("text", nargs="?") ap.add_argument("-c", "--confidence", type=int) ap.add_argument("--flag") ap.add_argument("--public", action="store_true") a = ap.parse_intermixed_args() if a.cmd == "board": b = call(a.url, "/v0/board") for r in b.get("top", []): print(f"{r['rank']:>2} {r['standing']:>6} {r['key']} {(r.get('flag') or '--')} {r.get('name') or '(unnamed)'}") return print(f"{b.get('keys_seen')} keys seen; next redraw in {max(0, int(b['next'] - time.time())) // 60} min") v = Visitor(a.url, a.state) if a.cmd == "begin": if v.st is not None: sys.exit(f"{a.state} already holds a key. Use `show`, or pass --state for a new one.") info = call(a.url, "/v0/rules") if "toll" not in info: sys.exit("The registry did not answer: " + str(info.get("error", info))) sk, nxt = Ed25519PrivateKey.generate(), Ed25519PrivateKey.generate() pub = sk.public_key().public_bytes(**RAW).hex() v.st = {"sk": sk.private_bytes(**RAWPRIV).hex(), "next_sk": nxt.private_bytes(**RAWPRIV).hex(), "pub": pub, "kid": hashlib.sha256(bytes.fromhex(pub)).hexdigest(), "seq": -1, "prev": GENESIS, "tray": None} r = v.send("/v0/present", {"type": "present", "key": pub, "next_key_hash": hashlib.sha256(nxt.public_key().public_bytes(**RAW)).hexdigest()}) if "error" in r: sys.exit("Refused: " + r["error"]) v.save() t = {**info["toll"], "bits": r.get("toll_bits", info["toll"]["bits"])} print(f"Key {v.st['kid'][:12]} presented. Paying the toll (about {2 ** t['bits']} scrypt evaluations; this can take a minute)...", file=sys.stderr) nonce, counter = call(a.url, "/v0/nonce", {})["nonce"], 0 while True: h = hashlib.scrypt(f"{v.st['kid']}|{nonce}|{counter}".encode(), salt=t["salt"].encode(), n=t["scrypt_n"], r=t["scrypt_r"], p=t["scrypt_p"], maxmem=2 * 128 * t["scrypt_n"] * t["scrypt_r"], dklen=t["dklen"]) if not t["bits"] or int.from_bytes(h, "big") >> (8 * t["dklen"] - t["bits"]) == 0: break counter += 1 r = v.send("/v0/start", {"type": "stream_start", "key": v.st["kid"], "nonce": nonce, "toll": counter}) if "error" in r: sys.exit("Refused at the toll: " + r["error"] + " (the nonce may have expired; delete the state file and begin again)") print(r.get("rules", "") + "\n") return show(v.st) if v.st is None: sys.exit("Run `begin` first.") kid, t = v.st["kid"], v.st.get("tray") if a.cmd == "show": return show(v.st) if a.cmd == "name": r = v.send("/v0/name", {"type": "name", "key": kid, "name": " ".join((a.text or a.brick or "").split()), **({"flag": a.flag.upper()} if a.flag else {})}) return print("Refused: a name is 1 to 40 printable characters, a flag an ISO 3166-1 two-letter code, three changes a day." if "error" in r else "Name recorded.") if a.cmd == "card": r = v.send("/v0/card", {"type": "card", "key": kid, "text": a.text or a.brick or "", "share": "public" if a.public else "private"}) return print("Refused: a card is 1 to 2000 characters, at most three a day." if "error" in r else f"Calling card recorded, marked {'public' if a.public else 'private'}.") if a.cmd == "next": r = v.send("/v0/next", {"type": "tray_next", "key": kid}) return print("Refused: " + r["error"]) if "error" in r else show(v.st) if not t: return print("No offer is open. Use `next`.") if a.cmd == "pass": r = v.send("/v0/pass", {"type": "tray_pass", "key": kid, "tray": t["n"]}) return print("Refused: " + r["error"]) if "error" in r else show(v.st) letter = (a.brick or "").upper() if not letter or letter not in "ABCD"[:len(t["bricks"])] or a.text is None: return print("Name the puzzle by its letter and give the text.") brick = t["bricks"]["ABCD".index(letter)]["brick"] if a.cmd == "ask": r = v.send("/v0/ask", {"type": "brick_ask", "key": kid, "brick": brick, "question": a.text}) return print("Refused: you are committed to another puzzle of this offer, or the question was empty or too long." if "error" in r else f"REPLY: {r['reply']}\n(questions left on this puzzle: {r['questions_left']})") body = {"type": "brick_answer", "key": kid, "brick": brick, "answer": a.text.strip()} if a.confidence is not None: body["confidence"] = max(0, min(100, a.confidence)) r = v.send("/v0/answer", body) if "error" in r: return print("Refused: you are committed to another puzzle of this offer.") print("Answer recorded.\n") show(v.st) if __name__ == "__main__": main()