#!/usr/bin/env python3 """The slow obvious canvas client. Faster is the game. pip install argon2-cffi (and pillow for --image) python3 client.py URL 10 20 ff8800 [--name yours] python3 client.py URL --image logo.png 100 100 [--name yours] """ import argparse, json, random, struct, sys, urllib.error, urllib.request from argon2.low_level import hash_secret_raw, Type def call(url, path, body=None): req = urllib.request.Request(url.rstrip("/") + path, method="POST" if body else "GET", data=json.dumps(body).encode() if body else None, headers={"Content-Type": "application/json", "User-Agent": "canvas-client"}) try: with urllib.request.urlopen(req, timeout=30) 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 ValueError: return e.code, {} def paint(url, cfg, x, y, color, name): while True: st, ch = call(url, "/api/challenge?x=%d&y=%d" % (x, y)) if st != 200: print("challenge failed:", st, ch) return False rgb = bytes.fromhex(color) salt = bytes.fromhex(ch["epoch"]) nonce = random.getrandbits(48) while True: h = hash_secret_raw(struct.pack("> (256 - ch["bits"]) == 0: break nonce += 1 body = {"x": x, "y": y, "color": color, "epoch": ch["epoch"], "nonce": nonce} if name: body["name"] = name st, r = call(url, "/api/paint", body) if st == 200: return True if st == 409: continue # epoch rotated or price rose: ask again print("paint failed:", st, r) return False def main(): ap = argparse.ArgumentParser() ap.add_argument("url") ap.add_argument("args", nargs="*") ap.add_argument("--image") ap.add_argument("--name", default="") a = ap.parse_args() st, cfg = call(a.url, "/api/config") if st != 200: sys.exit("cannot read /api/config") if a.image: from PIL import Image x0, y0 = int(a.args[0]), int(a.args[1]) im = Image.open(a.image).convert("RGBA") n = 0 for y in range(im.height): for x in range(im.width): r, g, b, al = im.getpixel((x, y)) if al < 128: continue if paint(a.url, cfg, x0 + x, y0 + y, "%02x%02x%02x" % (r, g, b), a.name): n += 1 print("\r%d pixels" % n, end="", flush=True) print() else: x, y, color = int(a.args[0]), int(a.args[1]), a.args[2].lstrip("#") print("painted" if paint(a.url, cfg, x, y, color, a.name) else "failed") if __name__ == "__main__": main()