#!/usr/bin/env python3 """LLPRO offline verifier: one file, Python 3.8+ standard library only. No server, no network, no pip install. Re-checks a signed answer from any LLPRO Trust product with the product's public key (shown on its page). (the published TEST keys are refused for real answers; add --test-key to try a vector by hand) python3 llpro_verify.py vectors [vectors.json] run every published test vector; prints OK/MISMATCH per vector python3 llpro_verify.py envelope KEY result.json any signed answer {"observation": ..., "signature": ...} python3 llpro_verify.py transaction-audit KEY result.json [bundle.json] python3 llpro_verify.py spend-limits KEY result.json [request.json] (request.json = the body you sent: scope, request, ...) python3 llpro_verify.py witness KEY receipts.json (a list of receipts of one deal) python3 llpro_verify.py signed-handoffs KEY record.json python3 llpro_verify.py run-records KEY result.json records.json KEY is the product's Ed25519 public key in base64. Output starts with PASS or FAIL (exit code 0 / 1). Key history (any product command): ... --keys llpro-keys.json [--prev an-older-llpro-keys.json] checks https://llpro.ai/.well-known/llpro-keys.json is signed by LLPRO's key-history key pinned below (HISTORY_KEYS), that KEY is listed, that the answer's time is inside the key's valid dates and that the key is not revoked; with --prev, an older or forked history is refused. Signatures: Ed25519 (RFC 8032, written out below so you can read it). Strict: S must be below the group order, points must be canonical, small-order (weak) public keys are refused. Signed text: canonical JSON (sorted keys, separators "," and ":", UTF-8, no ASCII escaping). This is LLPRO's canonical form, NOT RFC 8785 (JCS); they agree for the strings and integers our products sign, and differ for some floats. PASS shows only that the named key signed exactly this and that the parts agree. It does not show who holds the key or anything the product says it does not show. """ import base64 import calendar import hashlib import json import re import sys import time from decimal import Decimal VERSION = "1.0 (12 Nov 2026)" # ------------------------------------------------------------------ Ed25519 verify (RFC 8032 section 5.1) P = 2 ** 255 - 19 L = 2 ** 252 + 27742317777372353535851937790883648493 D = -121665 * pow(121666, P - 2, P) % P SQRT_M1 = pow(2, (P - 1) // 4, P) _GY = 4 * pow(5, P - 2, P) % P def _inv(x): return pow(x, P - 2, P) def _add(a, b): """Extended twisted Edwards coordinates (X, Y, Z, T), a = -1 (RFC 8032 5.1.4).""" A = (a[1] - a[0]) * (b[1] - b[0]) % P B = (a[1] + a[0]) * (b[1] + b[0]) % P C = 2 * a[3] * b[3] * D % P Dd = 2 * a[2] * b[2] % P E, F, G, H = B - A, Dd - C, Dd + C, B + A return (E * F % P, G * H % P, F * G % P, E * H % P) def _mul(s, pt): q = (0, 1, 1, 0) while s > 0: if s & 1: q = _add(q, pt) pt = _add(pt, pt) s >>= 1 return q def _eq(a, b): return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0 def _decode(s): """32 bytes -> point, or None when the encoding is not canonical or not on the curve (RFC 8032 5.1.3).""" if len(s) != 32: return None y = int.from_bytes(s, "little") sign = y >> 255 y &= (1 << 255) - 1 if y >= P: return None x2 = (y * y - 1) * _inv(D * y * y + 1) % P if x2 == 0: if sign: return None x = 0 else: x = pow(x2, (P + 3) // 8, P) if (x * x - x2) % P: x = x * SQRT_M1 % P if (x * x - x2) % P: return None if (x & 1) != sign: x = P - x return (x, y, 1, x * y % P) def _gx(): return _decode(_GY.to_bytes(32, "little")) G = _gx() IDENT = (0, 1, 1, 0) def ed25519_verify(pub, msg, sig): """pub 32 bytes, msg bytes, sig 64 bytes -> True/False. Never raises.""" try: if not (isinstance(pub, bytes) and isinstance(sig, bytes) and isinstance(msg, bytes)) or len(pub) != 32 or len(sig) != 64: return False A = _decode(pub) if A is None or _eq(_mul(8, A), IDENT): # non-canonical or weak (small-order) key return False R = _decode(sig[:32]) if R is None: return False S = int.from_bytes(sig[32:], "little") if S >= L: # non-canonical S (malleable) return False h = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(), "little") % L return _eq(_mul(S, G), _add(R, _mul(h, A))) except Exception: return False # ------------------------------------------------------------------ helpers shared by every product def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False) def sha(o): return hashlib.sha256(canon(o).encode("utf-8")).hexdigest() def b64(s, n): """Strict canonical base64 of exactly n bytes, or None.""" try: if not isinstance(s, str): return None raw = base64.b64decode(s, validate=True) if len(raw) != n or base64.b64encode(raw).decode() != s: return None return raw except Exception: return None def sig_ok(pub_b64, sig_b64, text): pub, sig = b64(pub_b64, 32), b64(sig_b64, 64) return bool(pub and sig) and ed25519_verify(pub, text.encode("utf-8"), sig) def key_id(pub_b64): """The llpro1: id of a public key, as products put it in observation.signer.""" raw = b64(pub_b64, 32) return "llpro1:" + base64.b32encode(hashlib.sha256(raw).digest()[:16]).decode().lower().rstrip("=") if raw else None def ep(x): return calendar.timegm(time.strptime(x, "%Y-%m-%dT%H:%M:%SZ")) def content(d): return {k: v for k, v in d.items() if k != "sig"} def envelope(key, rec, want_type=None): """-> (None, observation) when LLPRO's signature checks, else (failure text, None).""" if not isinstance(rec, dict) or not isinstance(rec.get("observation"), dict): return "FAIL: not a signed answer (needs observation and signature)", None if b64(key, 32) is None: return "FAIL: the public key is not 32 bytes of canonical base64", None o = rec["observation"] if not sig_ok(key, rec.get("signature"), canon(o)): return "FAIL: the LLPRO signature does not verify for this key", None if want_type and o.get("type") != want_type: return "FAIL: signed, but it is a %r answer, not %r" % (o.get("type"), want_type), None if "signer" in o and o["signer"] != key_id(key): return "FAIL: the observation names signer %r, which is not this key" % o["signer"], None return None, o # ------------------------------------------------------------------ products def verify_envelope(key, rec): try: err, o = envelope(key, rec) return err or "PASS: signed by this key; type %r. Shows the signature only." % o.get("type") except Exception as e: return "FAIL: malformed answer (%s)" % type(e).__name__ _TS = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z\Z", re.ASCII) _AMOUNT = re.compile(r"\d{1,12}(\.\d{1,6})?\Z", re.ASCII) _CUR = re.compile(r"[A-Z]{3,5}\Z", re.ASCII) _PID = re.compile(r"[A-Za-z0-9_.:\-]{1,64}\Z", re.ASCII) _HEX64 = re.compile(r"[0-9a-f]{64}\Z", re.ASCII) _SID = re.compile(r"[A-Za-z0-9_.:\-]{1,128}\Z", re.ASCII) _ACT = re.compile(r"[a-z0-9_.:\-]{1,64}\Z", re.ASCII) _TYPES = ("offer", "accept", "payment", "delivery", "confirm", "dispute") _SCOPE_KEYS = {"v", "type", "id", "agent", "principal_key", "cap", "not_before", "not_after", "actions", "max_per_action", "sig"} def _ts_ok(s): if not isinstance(s, str) or not _TS.match(s): return False try: if int(s[17:19]) > 59: return False ep(s) return True except (ValueError, OverflowError): return False def _key_ok(k): """Canonical base64 of a curve point that is not of small order (the products' weak-key rule).""" raw = b64(k, 32) pt = _decode(raw) if raw else None return pt is not None and not _eq(_mul(8, pt), IDENT) def ta_audit(parties, events, now): """Transaction Audit's own rules, re-done here -> (outcome, stage, failed check names). Same order and names as the product.""" failed = [] def chk(name, ok): if not ok: failed.append(name) return ok pok, keys, roles = True, {}, {} for p in parties: if not (isinstance(p, dict) and isinstance(p.get("id"), str) and _PID.match(p["id"]) and p.get("role") in ("buyer", "seller") and isinstance(p.get("public_key"), str) and _key_ok(p["public_key"])): pok = False continue keys[p["id"]] = p["public_key"] roles[p["role"]] = p["id"] pok = pok and len(keys) == 2 and len(roles) == 2 and len(set(keys.values())) == 2 if not chk("parties", pok): return "invalid", "none", failed buyer, seller = roles["buyer"], roles["seller"] sc = lambda ev: dict({"type": ev["type"], "by": ev["by"], "at": ev["at"], "body": ev["body"]}, **({"ref": ev["ref"]} if ev.get("ref") is not None else {})) eh = lambda ev: sha(sc(ev)) by_hash, seen = {}, set() shape_ok = s_ok = True for ev in events: if not (isinstance(ev, dict) and ev.get("type") in _TYPES and isinstance(ev.get("by"), str) and ev["by"] in keys and _ts_ok(ev.get("at")) and isinstance(ev.get("body"), dict) and isinstance(ev.get("sig"), str) and (ev.get("ref") is None or (isinstance(ev["ref"], str) and _HEX64.match(ev["ref"]))) and len(canon(ev["body"])) <= 2048): shape_ok = False continue if not sig_ok(keys[ev["by"]], ev["sig"], canon(sc(ev))): s_ok = False h = eh(ev) if h in seen: shape_ok = False seen.add(h) by_hash[h] = ev chk("structure", shape_ok) chk("signatures", s_ok and shape_ok) if not (shape_ok and s_ok): return "invalid", "none", failed order_ok = future_ok = True last = 0 for ev in events: t = ep(ev["at"]) order_ok &= t >= last last = max(last, t) future_ok &= t <= now + 300 chk("time order", order_ok) chk("not in the future", future_ok) prob = [] firsts = {} for ev in events: firsts.setdefault(ev["type"], ev) off, acc, pay, dlv, cfm, dsp = (firsts.get(t) for t in _TYPES) for t in _TYPES[:5]: if sum(1 for e in events if e["type"] == t) > 1: prob.append(t) terms_ok = lambda t: (isinstance(t, dict) and isinstance(t.get("item"), str) and 0 < len(t["item"]) <= 200 and isinstance(t.get("amount"), str) and _AMOUNT.match(t["amount"]) and t["amount"].replace(".", "").strip("0") != "" and isinstance(t.get("currency"), str) and _CUR.match(t["currency"]) and isinstance(t.get("buyer"), str) and isinstance(t.get("seller"), str) and (t.get("deliver_by") is None or _ts_ok(t.get("deliver_by")))) stage = "none" if off: if off.get("ref") is not None or not terms_ok(off["body"]): prob.append("offer") stage = "offer" elif events: prob.append("no offer") terms = off["body"] if off and terms_ok(off["body"]) else None if terms is not None and (terms["buyer"] != buyer or terms["seller"] != seller): prob.append("parties") def after(ev, ref): if ref and ep(ev["at"]) < ep(ref["at"]): prob.append("date") if acc: if not off: prob.append("accept") elif acc.get("ref") != eh(off) or acc["by"] == off["by"] or (terms is not None and canon(acc["body"].get("terms")) != canon(terms)) or ep(acc["at"]) < ep(off["at"]): prob.append("accept") stage = "accept" after(acc, off) if pay: if not acc: prob.append("payment") elif pay.get("ref") != eh(acc) or pay["by"] != buyer or (terms is not None and (pay["body"].get("amount") != terms["amount"] or pay["body"].get("currency") != terms["currency"])): prob.append("payment") stage = "payment" after(pay, acc) if dlv: if not acc: prob.append("delivery") elif (dlv.get("ref") != eh(acc) or dlv["by"] != seller or (terms is not None and terms.get("deliver_by") and ep(dlv["at"]) > ep(terms["deliver_by"])) or (terms is not None and dlv["body"].get("item") != terms["item"])): prob.append("delivery") after(dlv, acc) stage = "delivery" if stage in ("payment", "delivery", "accept") else stage if cfm: if not dlv or cfm.get("ref") != eh(dlv) or cfm["by"] != buyer: prob.append("confirm") after(cfm, dlv) if pay and ep(pay["at"]) > ep(cfm["at"]): prob.append("confirm") stage = "confirm" for d_ in [e for e in events if e["type"] == "dispute"]: if d_.get("ref") not in by_hash: prob.append("dispute") else: after(d_, by_hash[d_["ref"]]) consistent = not prob chk("chain and terms", consistent) if not (order_ok and future_ok and consistent): return "inconsistent", stage, failed if dsp: return "disputed", stage, failed return ("complete" if (off and acc and pay and dlv and cfm) else "partial"), stage, failed def verify_transaction_audit(key, rec, bundle=None): try: err, o = envelope(key, rec, "transaction-audit") if err: return err if bundle is None: return "PASS: signed by this key: Transaction Audit answer, outcome %s (bundle not given, so the evidence itself was not re-checked)" % o["outcome"] if sha(bundle) != o["bundle_hash"]: return "FAIL: this is not the bundle that was audited (bundle_hash differs)" if not (isinstance(bundle, dict) and isinstance(bundle.get("parties"), list) and len(bundle["parties"]) == 2 and isinstance(bundle.get("events"), list) and 1 <= len(bundle["events"]) <= 40): return "FAIL: the bundle is not in the form Transaction Audit signs answers for" if len(bundle["events"]) != o["events"]: return "FAIL: the answer counts %r events, the bundle has %d" % (o["events"], len(bundle["events"])) outcome, stage, failed = ta_audit(bundle["parties"], bundle["events"], ep(o["audited_at"])) for k, v in (("outcome", outcome), ("stage", stage), ("checks_failed", failed)): if o.get(k) != v: return "FAIL: the answer says %s=%r but re-doing the audit on this bundle gives %r" % (k, o.get(k), v) return "PASS: signed by this key: Transaction Audit answer for this bundle; the audit re-done here agrees: outcome %s, stage %s%s. Shows evidence consistency only, not that money moved or goods arrived." % ( outcome, stage, (", failed: " + ", ".join(failed)) if failed else "") except Exception as e: return "FAIL: malformed answer or bundle (%s)" % type(e).__name__ def _money(x, positive=False): if not (isinstance(x, str) and _AMOUNT.match(x)): return None d = Decimal(x) return None if positive and d <= 0 else d def _fmt(d): return format(d.normalize(), "f") if d != 0 else "0" def _scope_shape_ok(s): if not isinstance(s, dict) or set(s) - _SCOPE_KEYS or type(s.get("v")) is not int or s.get("v") != 1 or s.get("type") != "spend-scope": return False if not all(isinstance(s.get(f), str) and _SID.match(s[f]) for f in ("id", "agent")) or not (isinstance(s.get("principal_key"), str) and _key_ok(s["principal_key"])): return False cap = s.get("cap") if not (isinstance(cap, dict) and set(cap) == {"amount", "currency"} and _money(cap.get("amount"), True) is not None and isinstance(cap.get("currency"), str) and _CUR.match(cap["currency"])): return False if s.get("max_per_action") is not None and _money(s["max_per_action"], True) is None: return False if (s.get("not_before") is not None and not _ts_ok(s["not_before"])) or not _ts_ok(s.get("not_after")): return False if s.get("not_before") is not None and ep(s["not_before"]) >= ep(s["not_after"]): return False a = s.get("actions") if not (isinstance(a, list) and 1 <= len(a) <= 32 and all(isinstance(x, str) and _ACT.match(x) for x in a) and len(set(a)) == len(a)): return False return b64(s.get("sig"), 64) is not None def sl_check(scope, request, spent, expected, now): """Spend Limits' own rules, re-done here -> (verdict, failed check names, remaining Decimal or None).""" if not _scope_shape_ok(scope): return "invalid", ["scope format"], None if not sig_ok(scope["principal_key"], scope["sig"], canon(content(scope))): return "invalid", ["signature"], None if expected is not None and expected != scope["principal_key"]: return "invalid", ["expected owner"], None failed = [] t = int(now) started = scope.get("not_before") is None or t >= ep(scope["not_before"]) live = t <= ep(scope["not_after"]) amt = Decimal(request["amount"]) per_ok = scope.get("max_per_action") is None or amt <= Decimal(scope["max_per_action"]) cap = Decimal(scope["cap"]["amount"]) sp = spent if spent is not None else Decimal(0) for name, ok in (("not started", started), ("end date", live), ("action allowed", request["action"] in scope["actions"]), ("currency", request["currency"] == scope["cap"]["currency"]), ("per-action cap", per_ok), ("budget cap", sp + amt <= cap)): if not ok: failed.append(name) left = cap - sp return ("deny" if failed else "allow"), failed, (left if left > 0 else Decimal(0)) def verify_spend_limits(key, rec, body=None): try: err, o = envelope(key, rec, "spend-limit-check") if err: return err if body is None: return "PASS: signed by this key: Spend Limits answer, verdict %s (request not given, so the scope itself was not re-checked)" % o["verdict"] s, r = body["scope"], body["request"] if sha(s) != o["scope_hash"]: return "FAIL: this is not the scope that was checked (scope_hash differs)" if o["request"] != {"action": r["action"], "amount": r["amount"], "currency": r["currency"]} or _money(r["amount"], True) is None: return "FAIL: the answer is for a different request" spent = None if body.get("spent_so_far") is None else _money(body["spent_so_far"]) if body.get("spent_so_far") is not None and spent is None: return "FAIL: spent_so_far in the request is not decimal text" exp = body.get("expected_principal") verdict, failed, left = sl_check(s, r, spent, exp, o["epoch"]) want = {"verdict": verdict, "checks_failed": failed, "remaining": None if left is None else _fmt(left), "spent_so_far_stated": None if spent is None else _fmt(spent), "owner_pinned": exp is not None} if verdict != "invalid": want.update(cap=s["cap"], not_after=s["not_after"], agent=s["agent"], scope_id=s["id"], principal_key=s["principal_key"]) if o.get("checked_at") != time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(o["epoch"])): return "FAIL: checked_at and epoch in the answer disagree" for k, v in want.items(): if o.get(k) != v: return "FAIL: the answer says %s=%r but re-doing the check on this scope and request gives %r" % (k, o.get(k), v) return "PASS: signed by this key: Spend Limits answer for this scope and request; the check re-done here agrees: verdict %s%s, remaining %s. Shows scope and arithmetic only; no money is held." % ( verdict, (" (" + ", ".join(failed) + ")") if failed else "", want["remaining"]) except Exception as e: return "FAIL: malformed answer or request (%s)" % type(e).__name__ def verify_witness(key, receipts): try: if b64(key, 32) is None: return "FAIL: the public key is not 32 bytes of canonical base64" if not isinstance(receipts, list): return "FAIL: receipts must be a list" uniq = {json.dumps(r, sort_keys=True): r for r in receipts}.values() # a replayed receipt is byte-identical; keep one rs = sorted(uniq, key=lambda r: r["observation"]["seq"]) prev, last_t, keys, ids, deal = "0" * 64, "", {}, {}, None for i, r in enumerate(rs): err, o = envelope(key, r, "witness-receipt") if err: return "FAIL: receipt %d: %s" % (i, "Witness signature does not verify for this key" if "LLPRO signature" in err else err[6:]) ev = {"v": 1, "type": "witness-event", "deal_id": o["deal_id"], "party_id": o["party_id"], "event_type": o["event_type"], "content_hash": o["content_hash"]} if not sig_ok(o["public_key"], o["party_sig"], canon(ev)): return "FAIL: receipt %d: party signature does not verify" % i link = {k: o[k] for k in ("deal_id", "seq", "prev_chain_hash", "party_id", "public_key", "event_type", "content_hash", "party_sig", "witnessed_at")} if sha(dict(link, v=1)) != o["chain_hash"]: return "FAIL: receipt %d: chain_hash does not match" % i if o["seq"] != i or o["prev_chain_hash"] != prev or o["witnessed_at"] < last_t: return "FAIL: receipt %d: does not link to the one before" % i if deal not in (None, o["deal_id"]) or keys.setdefault(o["party_id"], o["public_key"]) != o["public_key"] or ids.setdefault(o["public_key"], o["party_id"]) != o["party_id"]: return "FAIL: receipt %d: mixed deals or a party/key mismatch" % i deal, prev, last_t = o["deal_id"], o["chain_hash"], o["witnessed_at"] return "PASS: %d receipts, last chain_hash %s (does not show nothing came after)" % (len(rs), prev) if rs else "FAIL: no receipts" except Exception: return "FAIL: malformed receipts" def verify_handoff(key, rec): try: err, o = envelope(key, rec, "handoff-record") if err: return err if o.get("verdict") != "valid": return "FAIL: not a valid hand-off record (verdict %r)" % o.get("verdict") q, a = o["question_doc"], o["answer_doc"] if sha(content(q)) != a["question_hash"] or a["question_hash"] != o["question_hash"]: return "FAIL: the approver signed a different question than the one in the record" if sha(content(a)) != o["answer_hash"]: return "FAIL: answer_hash does not match the answer" if not sig_ok(a["approver_key"], a["sig"], canon(content(a))): return "FAIL: the approver signature does not verify" if q["run_id"] != a["run_id"] or o["run_id"] != q["run_id"]: return "FAIL: run ids differ" for k, v in (("agent_id", q["agent_id"]), ("decision", a["decision"]), ("approver_id", a["approver_id"]), ("approver_key", a["approver_key"]), ("asked_at", q["asked_at"]), ("answered_at", a["answered_at"]), ("agent_signed", "agent_key" in q)): if o.get(k) != v: return "FAIL: the record says %s=%r but the signed documents say %r" % (k, o.get(k), v) if o.get("checks_failed"): return "FAIL: the record lists failed checks" if q["agent_id"] == a["approver_id"]: return "FAIL: approver_id is the agent's own id" if "agent_key" in q: if not sig_ok(q["agent_key"], q["sig"], canon(content(q))): return "FAIL: the agent signature on the question does not verify" if q["agent_key"] == a["approver_key"]: return "FAIL: the approver key is the agent's own key" if ep(a["answered_at"]) < ep(q["asked_at"]): return "FAIL: the answer is dated before the question" if ep(a["answered_at"]) > ep(o["recorded_at"]) + 300: return "FAIL: the answer is dated after LLPRO recorded it (beyond the 300 s allowed)" who = "agent-signed question" if "agent_key" in q else "UNSIGNED question (agent not authenticated; self-approval by key not ruled out)" return "PASS: decision %s by %s on run %s, answered %s, recorded by LLPRO %s; %s. (Shows keys and order only, not who the approver is.)" % ( a["decision"], a["approver_id"], q["run_id"], a["answered_at"], o["recorded_at"], who) except Exception as e: return "FAIL: malformed record (%s)" % type(e).__name__ _RR_TS = re.compile(r"20\d\d-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\dZ\Z", re.ASCII) _RR_BASE = {"v", "type", "run_id", "seq", "kind", "at", "prev", "recorder_id", "recorder_key", "sig", "telemetry_hash", "note"} def _prime_order_key(k): """Canonical 32-byte key of prime order (not small order, no torsion part).""" raw = b64(k, 32) pt = _decode(raw) if raw else None return pt is not None and not _eq(pt, IDENT) and _eq(_mul(L, pt), IDENT) def _rr_format(r, i): import unicodedata k = r["kind"] allowed = _RR_BASE | ({"agent_id", "heartbeat_s", "agent_key", "task_hash"} if k == "start" else set()) | ({"outcome"} if k == "end" else set()) need = (_RR_BASE - {"telemetry_hash", "note"}) | ({"agent_id", "heartbeat_s"} if k == "start" else set()) | ({"outcome"} if k == "end" else set()) return (set(allowed) >= set(r) >= need and type(r["v"]) is int and r["v"] == 1 and r["type"] == "run-record" and type(r["seq"]) is int and r["seq"] == i and all(isinstance(r.get(f), str) and _SID.match(r[f]) for f in ("run_id", "recorder_id") + (("agent_id",) if k == "start" else ())) and isinstance(r["at"], str) and _RR_TS.match(r["at"]) and ep(r["at"]) >= 1577836800 and all(isinstance(r[f], str) and _HEX64.match(r[f]) for f in ("prev", "telemetry_hash", "task_hash") if f in r) and (k != "start" or (type(r["heartbeat_s"]) is int and 10 <= r["heartbeat_s"] <= 86400 and ("agent_key" not in r or _prime_order_key(r["agent_key"])))) and (k != "end" or r["outcome"] in ("completed", "failed", "stopped", "timed-out")) and ("note" not in r or (isinstance(r["note"], str) and len(r["note"]) <= 280 and unicodedata.is_normalized("NFC", r["note"]) and all(c in "\n\t\r" or unicodedata.category(c)[0] != "C" for c in r["note"])))) def verify_run_records(key, res, recs): try: err, o = envelope(key, res, "run-record-check") if err: return err if o.get("verdict") != "valid" or o.get("checks_failed"): return "FAIL: not a valid run-record check (verdict %r)" % o.get("verdict") if not isinstance(recs, list) or not recs or sha(recs) != o["records_hash"] or len(recs) != o["records"]: return "FAIL: these are not the records the result summarises (records_hash or count differs)" st = recs[0] if not _prime_order_key(st["recorder_key"]): return "FAIL: the recorder key is not a strict Ed25519 key" prev = "0" * 64 for i, r in enumerate(recs): if not isinstance(r, dict) or r.get("kind") not in ("start", "heartbeat", "event", "end") or not _rr_format(r, i): return "FAIL: records[%d] is not in the record format" % i if (r["kind"] == "start") != (i == 0) or (r["kind"] == "end" and i != len(recs) - 1) or r["run_id"] != st["run_id"]: return "FAIL: records[%d] is in the wrong place or names another run" % i if r["recorder_key"] != st["recorder_key"] or r["recorder_id"] != st["recorder_id"]: return "FAIL: records[%d] names another recorder" % i if not sig_ok(r["recorder_key"], r["sig"], canon(content(r))): return "FAIL: records[%d] recorder signature does not verify" % i if r["prev"] != prev: return "FAIL: records[%d] breaks the hash chain" % i prev = sha(r) if st["recorder_id"].casefold() == st["agent_id"].casefold() or st.get("agent_key") == st["recorder_key"]: return "FAIL: the recorder is the agent itself" ts = [ep(r["at"]) for r in recs] if any(ts[i] < ts[i - 1] for i in range(1, len(ts))): return "FAIL: a record is dated before the one it follows" if ts[-1] > o["epoch"] + 300 or o["recorded_at"] != time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(o["epoch"])): return "FAIL: the last record is dated after LLPRO checked it, or the check time is inconsistent" hb = st["heartbeat_s"] al = hb + max(5, hb // 5) d = [ts[i] - ts[i - 1] for i in range(1, len(ts))] gaps = [{"after_seq": i, "gap_s": x} for i, x in enumerate(d) if x > al] end = recs[-1]["kind"] == "end" silent = max(0, o["epoch"] - min(ts[-1], o["epoch"])) state = "ended" if end else ("running" if silent <= al else "silent") want = dict({k: st.get(k) for k in ("run_id", "agent_id", "agent_key", "recorder_id", "recorder_key", "heartbeat_s", "task_hash")}, allowance_s=al, gaps_missed=len(gaps), gaps=gaps[:20], longest_gap_s=max(d or [0]), state=state, outcome=recs[-1]["outcome"] if end else None, silent_for_s=None if end else silent, heartbeat_kept=not gaps and state != "silent", first_at=recs[0]["at"], last_at=recs[-1]["at"], chain_head=prev, telemetry_hashes=sum("telemetry_hash" in r for r in recs)) for k, v in want.items(): if o.get(k) != v: return "FAIL: the result says %s=%r but the records say %r" % (k, o.get(k), v) pin = "agent key pinned" if o.get("agent_key_checked") else "agent key NOT pinned (the agent could hold the recorder key)" return "PASS: run %s, %d records by recorder %s, chain whole, %s, %d missed beat(s), %s%s. Shows keys, chain and clock only." % ( st["run_id"], len(recs), st["recorder_id"], state, len(gaps), pin, "" if o.get("head_pinned") else ", newest records not pinned") except Exception as e: return "FAIL: malformed result or records (%s)" % type(e).__name__ PRODUCTS = {"envelope": (verify_envelope, 1, 1), "transaction-audit": (verify_transaction_audit, 1, 2), "spend-limits": (verify_spend_limits, 1, 2), "witness": (verify_witness, 1, 1), "signed-handoffs": (verify_handoff, 1, 1), "run-records": (verify_run_records, 2, 2)} def run_vector(v): """One published vector -> verdict text. kinds: ed25519 (raw RFC 8032 check) or a product name. Never raises.""" try: if v["kind"] == "ed25519": ok = ed25519_verify(bytes.fromhex(v["public_key"]), bytes.fromhex(v["message"]), bytes.fromhex(v["signature"])) return "PASS: signature verifies" if ok else "FAIL: signature does not verify" fn, lo, hi = PRODUCTS[v["kind"]] if not lo <= len(v["inputs"]) <= hi: return "FAIL: wrong number of inputs for %s" % v["kind"] return fn(v["key"], *v["inputs"]) except Exception as e: return "FAIL: malformed vector (%s)" % type(e).__name__ def run_vectors(vs): bad = 0 for v in vs["vectors"]: got = run_vector(v) ok = got.split(":")[0] == v["expect"] bad += not ok print("%-8s %-46s expect %-4s got %s" % ("OK" if ok else "MISMATCH", v["id"], v["expect"], got[:110])) print("%d vectors, %d mismatches" % (len(vs["vectors"]), bad)) return bad == 0 def _no_dupes(pairs): d = {} for k, v in pairs: if k in d: raise ValueError("duplicate key %r" % k) # another parser could read the other value d[k] = v return d def load(p): with open(p, encoding="utf-8") as fh: return json.load(fh, object_pairs_hook=_no_dupes, parse_constant=lambda c: (_ for _ in ()).throw(ValueError("non-JSON number " + c))) # Public test keys (seeds published in vectors.json): accepted only in `vectors` mode, refused for real answers. TEST_KEYS = frozenset(("AKZx75hCF1pjlnZif4zYm2gxU3coELmH1qEGFEm9SMk=", "rYQtu3ak+OiGr/3zvHgsJbUMg3c7+byib/LcbpZFk+I=")) # ------------------------------------------------------------------ key history (bp-ts5, 14 Nov 2026) # LLPRO's key-history signing key, pinned here so https://llpro.ai/.well-known/llpro-keys.json can be checked with no network. # Empty until the history key is made at release; then this line holds its public key (base64). HISTORY_KEYS = frozenset(('1S6OrTiNQKanFefrAxDflyagvvIKwf2dCsdWWkFd4eQ=',)) # KEYHIST_ pinned 2026-11-15 _DOC_FIELDS = {"v", "type", "issuer", "policy", "history_key", "keys", "revocations", "seq", "published_at", "prev", "chain", "sig"} _KEY_FIELDS = {"id", "public_key", "names", "products", "use", "valid_from", "valid_to", "status"} _REV_FIELDS = {"id", "public_key", "revoked_at", "untrusted_from", "reason", "notice", "incident"} _HEX64 = re.compile(r"[0-9a-f]{64}\Z", re.ASCII) def history_ok(doc, prev=None, pinned=None): """-> (None, doc) when the history file is signed by a pinned history key, well formed and (given prev, an older copy you kept) continues it; else (failure text, None). Rollback: a file older than prev, or one whose chain does not hold prev's hash, is refused.""" pins = HISTORY_KEYS if pinned is None else frozenset(pinned) if not (isinstance(doc, dict) and doc.get("type") == "llpro-key-history" and doc.get("v") == 1 and not set(doc) ^ _DOC_FIELDS): return "FAIL: not an LLPRO key history file (version 1)", None if not pins: return "FAIL: no key-history key is pinned in this verifier yet (give one with --history-key)", None if doc["history_key"] not in pins: return "FAIL: the key history is signed by a key that is not the history key pinned in this verifier", None if not sig_ok(doc["history_key"], doc.get("sig"), canon(content(doc))): return "FAIL: the key history signature does not verify (altered or forged file)", None seq, ch = doc["seq"], doc["chain"] if not (type(seq) is int and seq >= 1 and isinstance(ch, list) and len(ch) == seq - 1 and _ts_ok(doc["published_at"])): return "FAIL: key history sequence, chain or date is malformed", None for i, c in enumerate(ch): if not (isinstance(c, list) and len(c) == 2 and type(c[0]) is int and c[0] == i + 1 and isinstance(c[1], str) and _HEX64.match(c[1])): return "FAIL: key history chain entry %d is malformed" % (i + 1), None if doc["prev"] != (ch[-1][1] if ch else None): return "FAIL: key history 'prev' does not match its chain", None if not (isinstance(doc["keys"], list) and isinstance(doc["revocations"], list)): return "FAIL: key history lists are malformed", None seen = set() for k in doc["keys"]: if not (isinstance(k, dict) and not set(k) ^ _KEY_FIELDS and b64(k["public_key"], 32) and k["id"] == key_id(k["public_key"]) and k["status"] in ("active", "retired", "revoked") and _ts_ok(k["valid_from"]) and (k["valid_to"] is None or _ts_ok(k["valid_to"])) and (k["valid_to"] is None) == (k["status"] == "active") and isinstance(k["products"], list)): return "FAIL: a key entry in the history is malformed or its id does not match its public key", None if k["public_key"] in seen: return "FAIL: a key is listed twice in the history", None seen.add(k["public_key"]) for r in doc["revocations"]: if not (isinstance(r, dict) and not set(r) ^ _REV_FIELDS and r["public_key"] in seen and _ts_ok(r["untrusted_from"]) and _ts_ok(r["revoked_at"])): return "FAIL: a revocation in the history is malformed or names an unlisted key", None if any(k["status"] == "revoked" and not any(r["public_key"] == k["public_key"] for r in doc["revocations"]) for k in doc["keys"]): return "FAIL: a key is marked revoked with no revocation entry", None if prev is not None: err, p = history_ok(prev, None, pins) if err: return "FAIL: the older history file you gave (--prev) does not check: " + err[6:], None if p["seq"] > seq: return "FAIL: this key history (version %d) is OLDER than the one you kept (version %d): refused as a rollback" % (seq, p["seq"]), None if p["seq"] == seq and sha(p) != sha(doc): return "FAIL: two different key histories carry version %d: refused (fork)" % seq, None if p["seq"] < seq and ch[p["seq"] - 1][1] != sha(p): return "FAIL: this key history does not continue the one you kept (its chain does not hold that file's hash)", None lost = continues(p, doc) if lost: return "FAIL: this key history drops or changes what the one you kept said: " + lost, None return None, doc def continues(old, new): """None when new keeps every key and revocation of old (a key's start never moves, a close date never changes once set, a revoked key stays revoked); else what was lost. Used here (--prev) and by LLPRO before it signs a new version.""" nk = {k["public_key"]: k for k in new["keys"]} for k in old["keys"]: n = nk.get(k["public_key"]) if n is None: return "key %s is gone" % k["id"] if n["valid_from"] != k["valid_from"]: return "key %s start date moved" % k["id"] if k["valid_to"] is not None and n["valid_to"] != k["valid_to"]: return "key %s close date changed" % k["id"] if k["status"] == "revoked" and n["status"] != "revoked": return "key %s is no longer revoked" % k["id"] nr = [canon(r) for r in new["revocations"]] for r in old["revocations"]: if canon(r) not in nr: return "revocation of %s is gone or changed" % r["id"] return None def key_window(doc, key, t): """-> None when the key is listed and may have signed at time t (seconds, or None = unknown), else failure text.""" ents = [k for k in doc["keys"] if k["public_key"] == key] if not ents: return "FAIL: this key is not in LLPRO's key history" k = ents[0] for r in doc["revocations"]: if r["public_key"] == key and (t is None or t >= ep(r["untrusted_from"])): return "FAIL: this key was revoked on %s (%s); answers it signed from %s on are not trusted" % (r["revoked_at"][:10], r["reason"], r["untrusted_from"]) if t is None: return None if k["status"] == "active" else "FAIL: this key is %s and the answer carries no time to compare with its valid dates" % k["status"] if t < ep(k["valid_from"]): return "FAIL: the answer claims a time before this key existed (valid from %s)" % k["valid_from"] if k["valid_to"] is not None and t > ep(k["valid_to"]): return "FAIL: the answer claims a time after this key was closed on %s" % k["valid_to"] return None _REC_TIMES = ("audited_at", "checked_at", "recorded_at", "witnessed_at", "observed_at", "issued_at", "at") _PRODUCT_TIME = {"transaction-audit": "audited_at", "spend-limits": "checked_at", "signed-handoffs": "recorded_at", "run-records": "recorded_at", "witness": "witnessed_at"} def rec_times(product, rec): """Every time the answer says it was signed (inside signed observations): one per answer, one per receipt for witness. [] = none found.""" recs = rec if (product == "witness" and isinstance(rec, list)) else [rec] out = [] for r in recs: o = r.get("observation") if isinstance(r, dict) else None names = (_PRODUCT_TIME[product],) if product in _PRODUCT_TIME else _REC_TIMES t = next((ep(o[f]) for f in names if isinstance(o, dict) and isinstance(o.get(f), str) and _ts_ok(o[f])), None) if t is None: return [] out.append(t) return out def _opt(args, name): """Remove '--name VALUE' from args -> value or None.""" if name in args: i = args.index(name) if i + 1 >= len(args): raise ValueError("%s needs a value" % name) v = args[i + 1] del args[i:i + 2] return v return None def main(argv): try: if len(argv) >= 2 and argv[1] == "vectors": return 0 if run_vectors(load(argv[2] if len(argv) > 2 else "vectors.json")) else 1 if len(argv) >= 4 and argv[1] in PRODUCTS: rest = list(argv[3:]) keys_f, prev_f, hand_pin = _opt(rest, "--keys"), _opt(rest, "--prev"), _opt(rest, "--history-key") files = [a for a in rest if a != "--test-key"] allow_test = len(files) != len(rest) if argv[2].strip() in TEST_KEYS and not allow_test: print("FAIL: this is LLPRO's PUBLIC TEST key; its seed is published, so anyone can sign with it. Use the product's own key from its page. (Trying a test vector by hand? add --test-key)") return 1 fn, lo, hi = PRODUCTS[argv[1]] if not lo <= len(files) <= hi or ((prev_f or hand_pin) and not keys_f): print(__doc__) return 2 inputs = [load(f) for f in files] note = "" if keys_f: err, doc = history_ok(load(keys_f), load(prev_f) if prev_f else None, [hand_pin] if hand_pin else None) if err: print(err) return 1 ts = rec_times(argv[1], inputs[0]) for t in (ts or [None]): kerr = key_window(doc, argv[2].strip(), t) if kerr: print(kerr) return 1 t = ts[0] if ts else None k = [x for x in doc["keys"] if x["public_key"] == argv[2].strip()][0] note = " Key: in LLPRO key history version %d, %s, valid %s to %s%s.%s" % ( doc["seq"], k["status"], k["valid_from"], k["valid_to"] or "now", "" if t is not None else " (answer has no time: checked as active only)", " The answer's own time is the signer's claim; it is proven only if the answer is in the Trust Log." if k["status"] != "active" else "") if hand_pin: note += " [history key given by hand with --history-key, not the one pinned in this file]" out = fn(argv[2], *inputs) if out.startswith("PASS"): out += note if argv[2].strip() in TEST_KEYS: out += " [TEST KEY: anyone can sign with it; this proves nothing about a real answer]" print(out) return 0 if out.startswith("PASS") else 1 except Exception as e: print("FAIL: cannot read input (%s: %s)" % (type(e).__name__, str(e)[:120])) return 1 print(__doc__) return 2 if __name__ == "__main__": sys.exit(main(sys.argv))