#!/usr/bin/env python3 """LLPRO merge ledger: offline check of an export. Runs without our server. Needs Python 3 and: pip install cryptography python3 ledger_verify.py archive.json [LLPRO_LEDGER_KEY_ID] archive.json is what the ledger_export tool returned in "archive". Pass LLPRO's published ledger key id (the llpro1: id on llpro.ai/locker/what-we-hold) or the check proves only that the archive agrees with itself. Prints PASS or the first failure. This file is the ONE copy of the chain, state and signature rules: the ledger on our side imports it, so the tool and this checker cannot drift apart. It proves LLPRO signed each entry at that point in the chain and that nothing was cut off the end. It does not prove an entry is true (the owner said it).""" import base64 import hashlib import json import sys PREFIX = "llpro1:" ZERO = "0" * 64 def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) def sha(s): return hashlib.sha256(s.encode("utf-8")).hexdigest() def key_id(pub_b64): """The llpro1: id of a public key (base64 of 32 raw bytes).""" raw = base64.b64decode(pub_b64, validate=True) return PREFIX + base64.b32encode(hashlib.sha256(raw).digest()[:16]).decode().lower().rstrip("=") def sig_ok(pub, sig, text): try: from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey Ed25519PublicKey.from_public_bytes(base64.b64decode(pub, validate=True)).verify(base64.b64decode(sig, validate=True), text.encode("utf-8")) return True except Exception: return False def entry_hash(e): return sha(canon({k: v for k, v in e.items() if k not in ("sig", "hash", "signer")})) def entry_message(owner_id, e): """What LLPRO signed for one entry.""" return canon({"owner": sha(owner_id), "n": e["n"], "hash": e["hash"], "prev": e["prev"], "signer": e["signer"]}) def head_message(a): """What LLPRO signed for the whole archive (a cut-off tail no longer matches).""" rows = a["entries"] return canon({"owner": sha(a["owner_id"]), "head": rows[-1]["hash"] if rows else ZERO, "count": len(rows), "exported_at": a["exported_at"], "signer": a["signer"]}) def state(rows): """What the chain says now: functions with their rung, receipts, preferences, kept files. Pure.""" S = {"functions": {}, "receipts": {}, "preferences": {}, "files": {}} for e in rows: b, sh, op = e["body"], e["shelf"], e["op"] if sh == "handover": if op in ("set", "lower"): S["functions"][b["function"]] = {"rung": b["rung"], "since": e["at"]} elif op == "remove": S["functions"].pop(b["function"], None) elif sh == "receipt" and op == "put": S["receipts"][b["receipt_id"]] = {"kind": b["kind"], "hash": b["hash"], "filed": e["at"]} elif sh == "preference": if op == "put": S["preferences"][b["key"]] = b["value"] elif op == "remove": S["preferences"].pop(b["key"], None) elif sh == "keptfile": if op == "put": S["files"][b["label"]] = {"sha256": b["sha256"], "size": b["size"]} elif op == "remove": S["files"].pop(b["label"], None) return S def verify_archive(a, expected_signer=None): """-> (True, '') or (False, reason).""" try: if a.get("type") != "ledger-archive" or not a.get("signer_key"): return False, "not a ledger archive" if a["signer"] != key_id(a["signer_key"]) or (expected_signer and a["signer"] != expected_signer): return False, "signer is not the expected LLPRO key" prev = ZERO for i, e in enumerate(a["entries"], 1): if e["n"] != i or e["prev"] != prev or e["hash"] != entry_hash(e): return False, "chain broken at entry %d" % i if e["signer"] != a["signer"] or not sig_ok(a["signer_key"], e["sig"], entry_message(a["owner_id"], e)): return False, "signature does not match at entry %d" % i prev = e["hash"] if not sig_ok(a["signer_key"], a.get("head_sig") or "", head_message(a)): return False, "signed head does not match the entries (archive cut short or altered)" if a.get("state") != state(a["entries"]): return False, "state does not match the entries" return True, "" except Exception as ex: return False, "unreadable archive: %s" % type(ex).__name__ def verify_deletion(r, expected_signer=None, signer_key=None): """Check a deletion receipt against LLPRO's ledger public key (base64). -> (True, '') or (False, reason).""" try: if r.get("type") != "ledger-deletion" or not signer_key or r.get("signer") != key_id(signer_key) or (expected_signer and r["signer"] != expected_signer): return False, "not a deletion receipt from the expected key" body = {k: v for k, v in r.items() if k not in ("sig", "does_not_prove")} return (True, "") if sig_ok(signer_key, r.get("sig") or "", canon(body)) else (False, "signature does not match") except Exception as ex: return False, "unreadable receipt: %s" % type(ex).__name__ def deletion_is_mine(r, owner_salt, owner_id): """True when a deletion receipt's owner_hash is this owner's (the salt came back only to the owner with the receipt).""" try: return isinstance(owner_salt, str) and isinstance(owner_id, str) and r.get("owner_hash") == sha(owner_salt + ":" + owner_id) except Exception: return False def _no_dup(pairs): d = {} for k, v in pairs: if k in d: raise ValueError("duplicate key %r" % k[:40]) d[k] = v return d def _no_const(x): raise ValueError("number %s is not allowed" % x) def load_strict(path): """Read an archive file: duplicate keys and NaN/Infinity are refused (two readers of one file must see the same thing).""" with open(path, encoding="utf-8") as fh: return json.load(fh, object_pairs_hook=_no_dup, parse_constant=_no_const) def main(argv): if not argv or argv[0] in ("-h", "--help"): print(__doc__) return 2 try: a = load_strict(argv[0]) except (OSError, ValueError, RecursionError, MemoryError) as ex: # RP3_: a clear FAIL line, never a traceback print("FAIL: cannot read %s: %s" % (argv[0], (str(ex) or type(ex).__name__)[:120])) return 1 if isinstance(a, dict) and isinstance(a.get("archive"), dict): a = a["archive"] ok, why = verify_archive(a, argv[1] if len(argv) > 1 else None) print("PASS" if ok else "FAIL: " + why) if ok and len(argv) < 2: print("note: no LLPRO key id given; this shows the archive agrees with itself, not that LLPRO signed it") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))