#!/usr/bin/env python3 """MIZAN mirror — run this, and the record carries a head signed by a key MIZAN does not hold. One file. No repo needed. Standard library plus `cryptography` (pip install cryptography) for Ed25519. curl -sO https://mizan.market/mirror/mirror.py python3 mirror.py What it does, every run, with its own code (nothing is imported from the server): 1. GET {origin}/api/log/head and {origin}/.well-known/mizan-keys.json; verify the head's Ed25519 signature over the signed fields {size, root, ts, alg, log} with the published key, and the head's signature SET against its quorum. 2. GET every leaf ({origin}/api/log/entries, pages of 1000); recompute every leaf hash (sha256(0x00 || canonical(leaf without index/leaf_hash))), check every index, and fold the RFC 6962 root ITSELF. 3. If this mirror signed an earlier head, GET /api/log/consistency?old=&new= and verify the proof: the log it signed before is a prefix of the log it is about to sign (append-only). 4. ONLY when the re-derived root equals the head's root, sign {root, size, ts, log, head_sig_sha256, witness_key_id, operator_statement_sha256} with YOUR OWN Ed25519 key (--key-dir, default ~/.mizan/mirror, 0700/0600, created on first run) and write /heads/.json /heads/latest.json /key.json /operator.txt 5. Unless --no-register: POST the signed head to {origin}/api/log/witnesses/register. The record verifies the signature with the public key in the body, checks (size, root) against a head it actually had, checks the key is not one MIZAN holds, and lists it at GET {origin}/api/log/witnesses. On any mismatch nothing is written, nothing is registered, and the exit code is 2. This program never signs a head it did not re-derive. Your private key never leaves --key-dir. Run: python3 mirror.py [--origin https://studio.mizan.market] [--out ./mizan-mirror] [--key-dir ~/.mizan/mirror] [--no-register] [--operator "free text, 120 chars max"] [--my-origin https://where.you/publish/heads/] """ from __future__ import annotations import argparse, base64, hashlib, json, os, sys, time, urllib.error, urllib.request ORIGIN = "https://studio.mizan.market" OUT_DEFAULT = "./mizan-mirror" KEY_DIR_DEFAULT = os.path.expanduser("~/.mizan/mirror") LOG_NAME = "mizan-verdict-log-v1" HEAD_V = "mizan-mirror-head/1" KEY_V = "mizan-mirror-key/1" PAGE = 1000 HEAD_SIGNED_FIELDS = ("size", "root", "ts", "alg", "log") HEAD_ALG = "sha256/RFC6962" SIGNED_FIELDS = ("root", "size", "ts", "log", "head_sig_sha256", "witness_key_id", "operator_statement_sha256") QUORUM_DEFAULT = 1 REGISTER_PATH = "/api/log/witnesses/register" INSTALL_HINT = "mirror.py needs the `cryptography` package for Ed25519: python3 -m pip install cryptography" OPERATOR_STATEMENT = ( "MIZAN mirror — operator statement\n\n" "This head was re-derived from the public leaves of the MIZAN record by mirror.py, a single file run by whoever holds the key\n" "in key.json. The program fetched every leaf, recomputed every leaf hash, folded the RFC 6962 root with its own code, verified\n" "the record's own signature on the head, and signed only because the two roots were equal. The private key was generated on\n" "the runner's machine and MIZAN does not hold it. The signature shows that this key saw this head and could re-derive it;\n" "it says nothing about who the runner is. Anyone may run this program and register their own key with the record.\n" ) # ---------------------------------------------------------------- RFC 6962, written here on purpose (not imported from the server) def _canon(o) -> bytes: return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode() def leaf_hash(data: bytes) -> bytes: return hashlib.sha256(b"\x00" + data).digest() def node_hash(l: bytes, r: bytes) -> bytes: return hashlib.sha256(b"\x01" + l + r).digest() def merkle_root(h: list) -> bytes: n = len(h) if n == 0: return hashlib.sha256(b"").digest() if n == 1: return h[0] k = 1 while k * 2 < n: k *= 2 return node_hash(merkle_root(h[:k]), merkle_root(h[k:])) def verify_consistency(m: int, n: int, old_root: bytes, new_root: bytes, proof: list) -> bool: if m == n: return old_root == new_root and not proof if m == 0 or m > n: return False p = list(proof) if m & (m - 1) == 0: p = [old_root] + p if not p: return False fn, sn = m - 1, n - 1 while fn & 1: fn >>= 1; sn >>= 1 fr = sr = p[0] for c in p[1:]: if sn == 0: return False if fn & 1 or fn == sn: fr = node_hash(c, fr); sr = node_hash(c, sr) while fn != 0 and not (fn & 1): fn >>= 1; sn >>= 1 else: sr = node_hash(sr, c) fn >>= 1; sn >>= 1 return fr == old_root and sr == new_root and sn == 0 # ---------------------------------------------------------------- the head's signature SET, re-derived here def head_bytes(head: dict) -> bytes: return _canon({k: head.get(k) for k in HEAD_SIGNED_FIELDS}) def signature_set(head: dict) -> list: s = head.get("signatures") if isinstance(s, list) and s: return [x for x in s if isinstance(x, dict)] sig = head.get("signature") or {} return [{"key_id": sig.get("key_id", ""), "alg": sig.get("alg", "Ed25519"), "sig_b64": sig.get("sig_b64", ""), "signer": "operator"}] if sig.get("sig_b64") else [] def key_table(*docs) -> dict: out = {} for d in docs: for dd in (d if isinstance(d, list) else [d]): if not isinstance(dd, dict): continue for k in (dd.get("keys") or []): if isinstance(k, dict) and k.get("public_key_b64") and (k.get("alg") or "Ed25519") == "Ed25519": out[str(k.get("key_id"))] = base64.b64decode(k["public_key_b64"]) if dd.get("public_key_b64") and (dd.get("key_id") or dd.get("witness_key_id")): out[str(dd.get("key_id") or dd.get("witness_key_id"))] = base64.b64decode(dd["public_key_b64"]) return out def verify_head_set(head: dict, keys, required=None) -> dict: req = max(1, int(os.environ.get("MIZAN_HEAD_QUORUM", QUORUM_DEFAULT))) if required is None else max(1, int(required)) table = keys if isinstance(keys, dict) and keys and all(isinstance(v, (bytes, bytearray)) for v in keys.values()) else key_table(keys) msg = head_bytes(head) good = {} for e in signature_set(head): kid = str(e.get("key_id") or "") if kid in table and kid not in good and e.get("alg", "Ed25519") == "Ed25519" and _ed_verify(table[kid], str(e.get("sig_b64") or ""), msg): good[kid] = e.get("signer") or "operator" return {"ok": len(good) >= req, "verified": len(good), "required": req, "key_ids": sorted(good)} # ---------------------------------------------------------------- fetching (injectable for tests) class Fetcher: def __init__(self, origin: str, timeout: float = 30.0): self.origin = origin.rstrip("/"); self.timeout = timeout def get_json(self, path: str) -> dict: req = urllib.request.Request(self.origin + path, headers={"User-Agent": "mizan-mirror/1", "Accept": "application/json"}) with urllib.request.urlopen(req, timeout=self.timeout) as r: return json.loads(r.read().decode("utf-8")) def post_json(self, path: str, body: dict) -> tuple: """-> (http_status, json_or_text)""" data = json.dumps(body, separators=(",", ":")).encode() req = urllib.request.Request(self.origin + path, data=data, method="POST", headers={"User-Agent": "mizan-mirror/1", "Accept": "application/json", "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=self.timeout) as r: raw = r.read().decode("utf-8"); st = r.status except urllib.error.HTTPError as e: raw = e.read().decode("utf-8", "replace"); st = e.code try: return st, json.loads(raw) except Exception: return st, {"ok": False, "error": raw[:300]} # ---------------------------------------------------------------- keys def _now() -> str: return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) def _crypto(): try: from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey return serialization, Ed25519PrivateKey, Ed25519PublicKey except ImportError: print(INSTALL_HINT, file=sys.stderr) raise SystemExit(3) def load_or_create_key(key_dir: str): serialization, Ed25519PrivateKey, _ = _crypto() os.makedirs(key_dir, mode=0o700, exist_ok=True) try: os.chmod(key_dir, 0o700) except Exception: pass path = os.path.join(key_dir, "mirror_key.pem") if os.path.exists(path): with open(path, "rb") as f: priv = serialization.load_pem_private_key(f.read(), password=None) else: priv = Ed25519PrivateKey.generate() pem = priv.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) with os.fdopen(fd, "wb") as f: f.write(pem) raw = priv.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw) return priv, base64.b64encode(raw).decode(), hashlib.sha256(raw).hexdigest()[:16] def _issuer_key(keys_doc: dict, key_id: str): for k in keys_doc.get("keys") or []: if k.get("key_id") == key_id and k.get("public_key_b64"): return base64.b64decode(k["public_key_b64"]) return None def _ed_verify(pub_raw: bytes, sig_b64: str, data: bytes) -> bool: try: _, _, Ed25519PublicKey = _crypto() Ed25519PublicKey.from_public_bytes(pub_raw).verify(base64.b64decode(sig_b64), data) return True except SystemExit: raise except Exception: return False def _state_path(key_dir: str) -> str: return os.path.join(key_dir, "state.json") def _load_state(key_dir: str) -> dict: try: return json.load(open(_state_path(key_dir))) except Exception: return {} def _write_json(path: str, obj) -> None: os.makedirs(os.path.dirname(path) or ".", exist_ok=True) tmp = path + ".tmp" with open(tmp, "w") as f: json.dump(obj, f, indent=1, sort_keys=True) os.replace(tmp, path) # ---------------------------------------------------------------- the run def rederive(fetcher: Fetcher, head: dict) -> dict: size = int(head["size"]) hashes = [] bad_idx, bad_hash = [], [] start = 0 while start < size: end = min(size, start + PAGE) page = fetcher.get_json(f"/api/log/entries?start={start}&end={end}") rows = page.get("entries") or [] if len(rows) != end - start: raise RuntimeError(f"short page {start}..{end}: got {len(rows)} leaves") for i, r in enumerate(rows): idx = start + i if r.get("index") != idx: bad_idx.append(idx) body = {k: v for k, v in r.items() if k not in ("leaf_hash", "index")} lh = leaf_hash(_canon(body)) if lh.hex() != r.get("leaf_hash"): bad_hash.append(idx) hashes.append(lh) start = end return {"root_hex": merkle_root(hashes).hex(), "leaves": len(hashes), "bad_indexes": bad_idx, "bad_hashes": bad_hash} def build_head_file(head: dict, priv, pub_b64: str, kid: str, origin: str, rd: dict, cons, operator: str = "", my_origin: str = "") -> dict: """The file this mirror writes and registers: flat, self-contained, verifiable with the public key it carries.""" sig = head.get("signature") or {} stmt_sha = hashlib.sha256(OPERATOR_STATEMENT.encode()).hexdigest() to_sign = {"root": head["root"], "size": int(head["size"]), "ts": head["ts"], "log": LOG_NAME, "head_sig_sha256": hashlib.sha256(str(sig.get("sig_b64", "")).encode()).hexdigest(), "witness_key_id": kid, "operator_statement_sha256": stmt_sha} data = _canon(to_sign) doc = dict(to_sign) doc.update({"v": HEAD_V, "public_key_b64": pub_b64, "signature": {"alg": "Ed25519", "key_id": kid, "sig_b64": base64.b64encode(priv.sign(data)).decode(), "canonical_sha256": hashlib.sha256(data).hexdigest(), "over": "canonical({root, size, ts, log, head_sig_sha256, witness_key_id, operator_statement_sha256}) — sorted keys, no spaces"}, "head_set_signature": {"key_id": kid, "alg": "Ed25519", "sig_b64": base64.b64encode(priv.sign(head_bytes(head))).decode(), "signer": "witness", "over": "canonical({size, root, ts, alg, log}) of the record head, the same bytes as the record's own signature", "head": {k: head.get(k) for k in HEAD_SIGNED_FIELDS}}, "about": {"mirrored_utc": _now(), "record_origin": origin, "rederived_leaves": rd["leaves"], "consistency_from_previous": cons, "program": "mirror.py", "operator_statement": "operator.txt", "how_to_check": "verify signature.sig_b64 over canonical of the seven signed fields with public_key_b64; compare root/size to " "GET /api/log/head or re-derive the root yourself with this program"}}) if operator: doc["operator"] = str(operator)[:120] if my_origin: doc["origin"] = str(my_origin)[:300] return doc def register_body(doc: dict) -> dict: """Exactly what is POSTed to /api/log/witnesses/register (the head file minus the local `about` block).""" return {k: v for k, v in doc.items() if k != "about"} def run(origin: str = ORIGIN, out_dir: str = OUT_DEFAULT, key_dir: str = KEY_DIR_DEFAULT, fetcher=None, quiet: bool = False, register: bool = True, operator: str = "", my_origin: str = "") -> dict: f = fetcher or Fetcher(origin) res = {"ok": False, "origin": origin, "ran_utc": _now()} head = f.get_json("/api/log/head") keys = f.get_json("/.well-known/mizan-keys.json") sig = head.get("signature") or {} signed = {k: head.get(k) for k in HEAD_SIGNED_FIELDS} pub = _issuer_key(keys, sig.get("key_id", "")) res["head"] = {"size": head.get("size"), "root": head.get("root"), "ts": head.get("ts"), "key_id": sig.get("key_id")} if head.get("log") != LOG_NAME: res["error"] = f"unexpected log name {head.get('log')!r}"; return res if pub is None or not _ed_verify(pub, sig.get("sig_b64", ""), _canon(signed)): res["error"] = "the head signature does not verify with the published key; nothing signed"; return res res["head_signature_valid"] = True hs = verify_head_set(head, keys) res["head_set"] = hs if not hs["ok"]: res["error"] = f"the head's signature set does not reach quorum ({hs['verified']} of {hs['required']} published keys verify); nothing signed"; return res rd = rederive(f, head) res["rederived"] = rd if rd["bad_indexes"] or rd["bad_hashes"] or rd["root_hex"] != head["root"]: res["error"] = "MISMATCH: the root re-derived from the public leaves differs from the head (or a leaf hash/index is wrong); nothing signed" res["mismatch"] = {"head_root": head["root"], "rederived_root": rd["root_hex"]} return res priv, pub_b64, kid = load_or_create_key(key_dir) st = _load_state(key_dir) prev = st.get("last") or None cons = None if prev and int(prev["size"]) <= int(head["size"]): m, n = int(prev["size"]), int(head["size"]) if m == n: cons = {"old_size": m, "new_size": n, "ok": prev["root"] == head["root"]} else: c = f.get_json(f"/api/log/consistency?old={m}&new={n}") ok = (c.get("old_root") == prev["root"] and c.get("new_root") == head["root"] and verify_consistency(m, n, bytes.fromhex(prev["root"]), bytes.fromhex(head["root"]), [bytes.fromhex(x) for x in c.get("proof") or []])) cons = {"old_size": m, "new_size": n, "ok": ok} if not cons["ok"]: res["error"] = "APPEND-ONLY BROKEN: the head this mirror signed earlier is not a prefix of the current log; nothing signed" res["consistency"] = cons return res res["consistency"] = cons doc = build_head_file(head, priv, pub_b64, kid, origin, rd, cons, operator, my_origin) size = int(head["size"]) _write_json(os.path.join(out_dir, "heads", f"{size}.json"), doc) _write_json(os.path.join(out_dir, "heads", "latest.json"), doc) _write_json(os.path.join(out_dir, "key.json"), {"v": KEY_V, "witness_key_id": kid, "alg": "Ed25519", "public_key_b64": pub_b64, "format": "raw 32-byte Ed25519", "log": LOG_NAME, "program": "mirror.py", "operator_statement": "operator.txt", "operator_statement_sha256": doc["operator_statement_sha256"], "heads": "heads/latest.json", "key_held_by": "the runner of mirror.py; MIZAN does not hold this key"}) with open(os.path.join(out_dir, "operator.txt"), "w") as f2: f2.write(OPERATOR_STATEMENT) st["last"] = {"size": size, "root": head["root"], "ts": head["ts"], "mirrored_utc": doc["about"]["mirrored_utc"]} st.setdefault("signed_count", 0); st["signed_count"] += 1 _write_json(_state_path(key_dir), st) try: os.chmod(_state_path(key_dir), 0o600) except Exception: pass res.update({"ok": True, "witness_key_id": kid, "public_key_b64": pub_b64, "signed": {k: doc[k] for k in SIGNED_FIELDS}, "wrote": [os.path.join(out_dir, "heads", f"{size}.json"), os.path.join(out_dir, "heads", "latest.json"), os.path.join(out_dir, "key.json"), os.path.join(out_dir, "operator.txt")]}) if register: body = register_body(doc) try: status, reply = f.post_json(REGISTER_PATH, body) except Exception as e: status, reply = 0, {"ok": False, "error": f"could not reach {origin}{REGISTER_PATH}: {str(e)[:200]}"} res["register"] = {"status": status, "reply": reply, "url": origin.rstrip("/") + REGISTER_PATH, "listed_at": origin.rstrip("/") + "/api/log/witnesses"} if not quiet: print_summary(res) return res def print_summary(res: dict) -> None: h = res.get("head") or {} rd = res.get("rederived") or {} print("MIZAN mirror") print(f" record head size {h.get('size')} ts {h.get('ts')}") print(f" entries re-derived {rd.get('leaves', 0)}") print(f" root (re-derived) {rd.get('root_hex', '-')}") print(f" root (record) {h.get('root')}") print(f" matched {'yes' if res.get('ok') else 'NO'}") if res.get("consistency"): c = res["consistency"]; print(f" append-only {c['old_size']} -> {c['new_size']}: {'ok' if c['ok'] else 'BROKEN'}") if res.get("ok"): print(f" your key id {res['witness_key_id']} (private key stays in your --key-dir)") print(f" wrote {res['wrote'][1]}") r = res.get("register") if r: rep = r["reply"] if isinstance(r["reply"], dict) else {} if rep.get("ok"): print(f" registered {r['url']} -> accepted (size {rep.get('size')}, key {rep.get('key_id')})") print(f" listed at {r['listed_at']}") elif r["status"] == 409: print(f" registered already on record for this size (key {res['witness_key_id']}); nothing new to add") print(f" listed at {r['listed_at']}") else: print(f" register FAILED HTTP {r['status']}: {rep.get('error')} fix: {rep.get('fix', '-')}") else: print(" registered skipped (--no-register)") else: print(f" error {res.get('error')}") if res.get("mismatch"): print(f" mismatch {json.dumps(res['mismatch'])}") def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("--origin", default=ORIGIN, help="the record to mirror") ap.add_argument("--out", default=OUT_DEFAULT, help="where heads/, key.json and operator.txt are written") ap.add_argument("--key-dir", default=KEY_DIR_DEFAULT, help="your Ed25519 key (created on first run)") ap.add_argument("--no-register", action="store_true", help="re-derive and sign only; do not POST the head to the record") ap.add_argument("--operator", default="", help="optional free text (<=120 chars) stored with your registration") ap.add_argument("--my-origin", default="", help="optional URL where you publish heads/ and key.json") a = ap.parse_args(argv) try: r = run(a.origin, a.out, a.key_dir, register=not a.no_register, operator=a.operator, my_origin=a.my_origin) except SystemExit: raise except Exception as e: print(json.dumps({"ok": False, "error": str(e)[:300]})); return 3 if not r.get("ok"): return 2 reg = r.get("register") if reg and not (isinstance(reg.get("reply"), dict) and (reg["reply"].get("ok") or reg.get("status") == 409)): return 4 return 0 if __name__ == "__main__": sys.exit(main())