#!/usr/bin/env python3 """Fetch store blobs by sha256 and verify them. python fetch_sha.py [ ...] The file store is server-root: GET https://solveathome.org/files/. Saves to `files/` and refuses to accept a body whose sha256 differs from the request (a mis-served or truncated blob must fail loudly, not become evidence). Anonymous first; retries with the run's bearer token on 401/403. Prints no credential. """ import hashlib import json import os import sys import urllib.error import urllib.request sys.stdout.reconfigure(encoding="utf-8", errors="replace") ROOT = "https://solveathome.org" UA = "sah-research-agent/1.0" HERE = os.path.dirname(os.path.abspath(__file__)) OUT = os.path.join(HERE, "files") os.makedirs(OUT, exist_ok=True) def token(): tf = os.environ.get("SOLVEATHOME_TOKEN_FILE") if not tf: tf = os.path.join(os.environ.get("LOCALAPPDATA", ""), "solveathome", "credentials", "twin-primes.token") try: with open(tf, encoding="utf-8") as fh: return fh.read().strip() except OSError: return None def fetch(sha, auth=False): url = "%s/files/%s" % (ROOT, sha) h = {"User-Agent": UA, "Accept": "*/*"} if auth: t = token() if t: h["Authorization"] = "Bearer " + t req = urllib.request.Request(url, headers=h) try: with urllib.request.urlopen(req, timeout=90) as f: return f.status, f.read() except urllib.error.HTTPError as e: return e.code, e.read() for sha in sys.argv[1:]: code, body = fetch(sha) if code in (401, 403): code, body = fetch(sha, auth=True) print("(%s: retried with token)" % sha[:12]) got = hashlib.sha256(body).hexdigest() ok = got == sha if code == 200 and ok: with open(os.path.join(OUT, sha), "wb") as fh: fh.write(body) try: txt = body.decode("utf-8") lines = txt.count("\n") + 1 except UnicodeDecodeError: lines = None print("%-64s http=%s bytes=%-8d lines=%-6s sha_ok=%s" % (sha, code, len(body), lines, ok)) if code == 200 and not ok: print(" !! digest mismatch: %s" % got)