From 868a759636b7b7d999a111fd6240088cc8b7e62e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:10:16 +0000 Subject: [PATCH 1/2] feat(verify): bind an OTS proof to the ledger before claiming external time mirror-stack-verify checked an OTS proof's Bitcoin block without checking which file the proof stamped, so any valid proof passed, and it left ledger precedence UNVERIFIED by design. With --manifest it now checks proof -> manifest (file sha256 from ots info), manifest -> ledger prefix (locate_ledger) and proof -> Bitcoin, and only then reports the pinned lines and the preregistrations among them as existing before the block. verify() now uses the earliest attestation and pairs each merkle root with its own block; a real multi-calendar proof listed block 959655 before 959599. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Aq8kkjKAMDjSSK54hcWnuc --- CHANGELOG.md | 12 +++ README.md | 10 ++- docs/ANCHORING.md | 20 ++++- mirror_stack_mcp/ots_anchor.py | 134 ++++++++++++++++++++++++++++++--- mirror_stack_mcp/verify.py | 68 +++++++++++++---- tests/test_ots_binding.py | 117 ++++++++++++++++++++++++++++ 6 files changed, 331 insertions(+), 30 deletions(-) create mode 100644 tests/test_ots_binding.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ce94a7f..608cab7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,18 @@ ## [Unreleased] +- `mirror-stack-verify --ots PROOF --manifest MANIFEST` binds an OTS proof to the ledger + being verified: the proof must stamp that manifest (file sha256 from `ots info`), and the + manifest must pin a prefix of the ledger (`locate_ledger`). Only then are the pinned lines, + and the preregistrations among them, reported as existing before the Bitcoin block + (`[EXTERNAL_TIME]`). Before, the CLI checked a proof's block without checking which file + it stamped, so any valid proof passed. New library function `ots_anchor.bind()`. +- `ots_anchor.verify()` now uses the EARLIEST Bitcoin attestation in a proof and pairs each + merkle root with its own block. It used the first one printed, which in a real + multi-calendar proof was 56 blocks later than the earliest. Also reports + `attested_blocks` and `proof_file_sha256`. +- Replace deprecated `datetime.utcnow()` / `utcfromtimestamp()` (same output format). + - OTS anchoring: optional publishable manifest (format 2). `stamp()` / `build_manifest()` accept `id_map_path`; the manifest then carries no paths and names each ledger only by a salted id `sha256(salt || basename)`, with a per-ledger random salt kept in a private map diff --git a/README.md b/README.md index 7730afa..2ac8edc 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,14 @@ Reinstall the package and reconnect the client after an upgrade; do not rewrite fixtures do not certify integrity. Legacy 16-hex seals are accepted with a warning. `stack_verify_all` labels checks `HASH_RECOMPUTED`, `LOCAL_SNAPSHOT`, or `HEAD_WITNESS`. None certifies content truth, author identity, independent reproduction or external time. -The outsider CLI checks an optional OTS proof separately; ledger-to-proof binding is -not checked, so it does not claim this ledger's external-clock precedence. +The outsider CLI reports external time only for a bound proof: +`mirror-stack-verify LEDGER --ots MANIFEST.json.ots --manifest MANIFEST.json` checks that +the proof stamps that manifest (sha256), that the manifest pins a prefix of this ledger, +and that the proof's earliest Bitcoin block matches a public explorer. Only then does it +print `[EXTERNAL_TIME]` for the pinned lines (and which preregistrations they hold); lines +appended after the stamp are listed as not covered. Without `--manifest` it checks the +proof separately and leaves this ledger's external-clock precedence unverified. The +explorer is a trusted third party here; a local Bitcoin node with `ots verify` removes it. The compute/publish gate verifies ledger integrity before reading the decision facts. Publish requires a reasoned retraction, or an explicit result bound to the original seal: diff --git a/docs/ANCHORING.md b/docs/ANCHORING.md index 8c6d585..049f3e1 100644 --- a/docs/ANCHORING.md +++ b/docs/ANCHORING.md @@ -111,9 +111,23 @@ The packaged implementation is [`mirror_stack_mcp/ots_anchor.py`](../mirror_stack_mcp/ots_anchor.py). Machine-local cron scripts are deployment-specific and are not shipped in the conventions directory. -The outsider `mirror-stack-verify` CLI recomputes ledger hashes but checks a supplied -OTS proof separately. It does not currently verify ledger-to-proof binding, so its -output correctly leaves this ledger's external-clock precedence unverified. +The outsider `mirror-stack-verify` CLI recomputes ledger hashes. Given both the proof and +the manifest it stamps, it also binds them to the ledger (`ots_anchor.bind`): + +```bash +mirror-stack-verify claims.jsonl --ots anchors/manifest_X.json.ots --manifest anchors/manifest_X.json +``` + +1. proof -> manifest: the file digest in `ots info` must equal sha256(manifest). Otherwise + any valid proof for any file would "verify". +2. manifest -> ledger: a manifest row must pin the first `bytes` bytes of this ledger + (format 1 and 2; later appends are fine, a rewrite of the pinned part is not). +3. proof -> Bitcoin: the EARLIEST attested block's merkle root must match a public explorer. + A proof stamped on several calendars carries several blocks, not listed in order. + +Only when all three hold is `[EXTERNAL_TIME]` printed for the pinned lines; later lines are +reported as not covered. With `--ots` alone the proof is checked separately and the +ledger's external-clock precedence stays unverified. ## Notes diff --git a/mirror_stack_mcp/ots_anchor.py b/mirror_stack_mcp/ots_anchor.py index d16555b..50ab8ff 100644 --- a/mirror_stack_mcp/ots_anchor.py +++ b/mirror_stack_mcp/ots_anchor.py @@ -28,6 +28,33 @@ DEFAULT_EXPLORER = os.environ.get("OTS_EXPLORER", "https://blockstream.info/api") _BLOCK_RE = re.compile(r"BitcoinBlockHeaderAttestation\((\d+)\)") _ROOT_RE = re.compile(r"Bitcoin block merkle root ([0-9a-fA-F]{64})") +_FILE_RE = re.compile(r"File sha256 hash: ([0-9a-fA-F]{64})") + + +def _attestations(info: str) -> list[tuple[int, str | None]]: + """Every Bitcoin attestation in ``ots info`` output as (height, merkle_root). + + A proof stamped on several calendars carries one attestation per calendar, often in + different blocks. ``ots info`` prints each merkle root as a comment line right AFTER + its ``verify BitcoinBlockHeaderAttestation(h)`` line; the root is computed by applying + the proof's operations to the file digest, so it is not a value the proof merely asserts. + """ + out: list[list] = [] + for line in info.splitlines(): + m = _BLOCK_RE.search(line) + if m: + out.append([int(m.group(1)), None]) + continue + m = _ROOT_RE.search(line) + if m and out and out[-1][1] is None: + out[-1][1] = m.group(1).lower() + return [(h, r) for h, r in out] + + +def _proof_digest(info: str) -> str | None: + """The sha256 of the file the proof is about, as ``ots info`` reports it.""" + m = _FILE_RE.search(info) + return m.group(1).lower() if m else None def _sha256(p) -> str: @@ -110,11 +137,11 @@ def build_manifest(ledger_paths: list[str], out_dir: str, *, else: name = os.path.basename(f) rows.append({"ledger_id": ledger_id(name, salts[name]), **common}) - stamp = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M%S") + stamp = datetime.datetime.now(datetime.timezone.utc).strftime("%Y%m%d_%H%M%S") # Different legitimate operations in the same second must not replace evidence. man = os.path.join(out_dir, f"manifest_{stamp}_{uuid.uuid4().hex}.json") manifest = {"_type": "ots_anchor_manifest", - "ts": datetime.datetime.utcnow().isoformat() + "Z", + "ts": datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat() + "Z", "purpose": "Bitcoin timestamp of mirror-stack ledger heads — " "proves no-backdating, NOT content truth.", "ledger_count": len(rows), "ledgers": rows} @@ -181,25 +208,36 @@ def _explorer_block(height: int, explorer: str): def verify(ots_path: str, explorer: str = DEFAULT_EXPLORER) -> dict: """Verify a Bitcoin-anchored proof WITHOUT a local node, by cross-checking the block - merkle root on a public explorer. Returns block height + independent-match.""" + merkle root on a public explorer. Returns block height + independent-match. + + Uses the EARLIEST attestation in the proof. A proof stamped on several calendars holds + one attestation per calendar; the first one printed is not necessarily the earliest + block (a real 2026-07-25 proof listed 959655 before 959599), and reporting a later + block understates how early the data existed. + + ``proof_file_sha256`` is the digest the proof is about. This function does NOT check + it against any file — use ``bind()`` to tie the proof to a manifest and a ledger.""" info = _info(ots_path) - m = _BLOCK_RE.search(info) - if not m: + atts = _attestations(info) + if not atts: return {"verified": False, "state": "pending", + "proof_file_sha256": _proof_digest(info), "note": "no Bitcoin attestation yet — run mm_anchor_upgrade first"} - height = int(m.group(1)) - rm = _ROOT_RE.search(info) - expected = rm.group(1).lower() if rm else None + height, expected = min(atts, key=lambda a: a[0]) + base = {"block_height": height, "expected_merkle_root": expected, + "attested_blocks": sorted({h for h, _ in atts}), + "proof_file_sha256": _proof_digest(info)} try: bhash, actual, ts = _explorer_block(height, explorer) except Exception as e: # network / explorer issue — attestation still embedded - return {"verified": False, "block_height": height, "expected_merkle_root": expected, + return {"verified": False, **base, "note": f"explorer fetch failed ({e}); embedded Bitcoin attestation is present"} match = expected is not None and actual is not None and actual.lower() == expected - return {"verified": match, "block_height": height, - "expected_merkle_root": expected, "explorer_merkle_root": actual, + return {"verified": match, **base, + "explorer_merkle_root": actual, "block_hash": bhash, - "block_time_utc": (datetime.datetime.utcfromtimestamp(ts).isoformat() + "Z") if ts else None, + "block_time_utc": (datetime.datetime.fromtimestamp(ts, datetime.timezone.utc) + .strftime("%Y-%m-%dT%H:%M:%SZ")) if ts else None, "explorer": explorer, "proves": "ledger heads existed before this Bitcoin block (no backdating)", "does_not_prove": ["content truth (GIGO)", "an external judging witness exists"]} @@ -230,3 +268,75 @@ def locate_ledger(manifest_path: str, ledger_path: str, *, name: str | None = No result["name_matches"] = row.get("ledger_id") == want_id or row.get("ledger") == name return result return {"found": False, "format": manifest.get("format", 1)} + + +def bind(ledger_path: str, manifest_path: str, ots_path: str, *, + explorer: str = DEFAULT_EXPLORER, verify_fn=None) -> dict: + """Tie an OTS proof to a manifest, the manifest to a ledger prefix, and report which + entries of THIS ledger existed before the proof's Bitcoin block. + + Each step must hold for the next to mean anything: + + 1. proof -> manifest: the digest the proof is about equals sha256(manifest file). + Without this, any valid proof for any file "verifies". + 2. manifest -> ledger: some manifest row pins the first ``bytes`` bytes of this + ledger by sha256 (``locate_ledger``). Appends after stamping are fine. + 3. proof -> Bitcoin: the earliest attested block's merkle root matches a public + explorer (``verify``). + + Only when all three hold are entries inside the pinned prefix reported as existing + before that block. Entries after the prefix are listed as NOT covered by this proof. + Says nothing about content truth, author identity, or what happened off-ledger. + + ``verify_fn`` replaces ``verify`` (tests; offline use). + """ + vf = verify_fn or verify + out: dict = {"bound": False, "ledger": str(ledger_path), "manifest": str(manifest_path), + "ots_proof": str(ots_path)} + manifest_sha = _sha256(manifest_path) + proof = vf(ots_path, explorer) + out["bitcoin"] = proof + proof_sha = proof.get("proof_file_sha256") + out["proof_matches_manifest"] = proof_sha == manifest_sha + if proof_sha is None: + out["note"] = "proof does not report which file it stamps; cannot bind" + return out + if proof_sha != manifest_sha: + out["note"] = (f"proof is for sha256 {proof_sha[:16]}…, manifest is " + f"{manifest_sha[:16]}… — this proof does not stamp this manifest") + return out + loc = locate_ledger(manifest_path, ledger_path) + out["manifest_pins_ledger"] = bool(loc.get("found")) + if not loc.get("found"): + out["note"] = ("no manifest row pins a prefix of this ledger — it was rewritten, or " + "is a different ledger") + return out + out["pinned_bytes"] = loc["pinned_bytes"] + out["pinned_lines"] = loc["pinned_lines"] + with open(ledger_path, "rb") as f: + data = f.read() + covered, later = [], [] + for i, raw in enumerate(data.splitlines(keepends=True)): + if not raw.strip(): + continue + try: + e = json.loads(raw) + except ValueError: + e = {} + row = {"line": i + 1, "type": e.get("_type", "preregistration" if "metric" in e else None), + "claim_id": e.get("claim_id"), "seal": e.get("seal"), "ts": e.get("ts")} + (covered if i < loc["pinned_lines"] else later).append(row) + out["covered_entries"] = covered + out["uncovered_entries"] = later + if not proof.get("verified"): + out["note"] = ("proof stamps this manifest and the manifest pins this ledger, but the " + "Bitcoin block is NOT confirmed: " + str(proof.get("note", "explorer mismatch"))) + return out + out["bound"] = True + out["existed_before"] = {"block_height": proof["block_height"], + "block_time_utc": proof.get("block_time_utc")} + out["proves"] = (f"the first {loc['pinned_lines']} ledger lines existed before Bitcoin block " + f"{proof['block_height']} ({proof.get('block_time_utc')})") + out["does_not_prove"] = ["content truth", "author identity", + "anything about lines after the pinned prefix"] + return out diff --git a/mirror_stack_mcp/verify.py b/mirror_stack_mcp/verify.py index fce95f1..7b04722 100644 --- a/mirror_stack_mcp/verify.py +++ b/mirror_stack_mcp/verify.py @@ -2,20 +2,22 @@ """🪞🔎🪪 mirror-stack-verify — one command for an OUTSIDER to confirm a ledger, without trusting us, without an MCP client, without config. - mirror-stack-verify LEDGER.jsonl [--ots PROOF.ots] [--explorer URL] + mirror-stack-verify LEDGER.jsonl [--ots PROOF.ots [--manifest MANIFEST.json]] [--explorer URL] Verification scope: 1. integrity — recompute both links AND content hashes from one ledger snapshot. No network; stdlib-only MIRROR-SPEC verification. Optional identity signatures are NOT verified; legacy 16-hex seals remain weaker. - 2. bitcoin — if an OpenTimestamps proof is given, cross-check its Bitcoin block - against a PUBLIC block explorer. This CLI does NOT check binding - between that proof and this ledger, so ledger precedence remains - UNVERIFIED. (needs the `ots` CLI + network.) - -Honest scope: this checks hash INTEGRITY, not external-clock PRECEDENCE. -It does NOT prove the content is true, nor that an independent judge witnessed it. + 2. bitcoin — if an OpenTimestamps proof is given, cross-check its EARLIEST Bitcoin + block against a PUBLIC block explorer. (needs the `ots` CLI + network.) + 3. binding — with --manifest as well: the proof must stamp that manifest (sha256), + and the manifest must pin a prefix of THIS ledger. Only then are the + pinned lines reported as existing before the block (EXTERNAL_TIME). + Without --manifest, ledger precedence remains UNVERIFIED. + +Honest scope: without a bound proof this checks hash INTEGRITY only, not +external-clock PRECEDENCE. It never proves the content is true, nor that an independent judge witnessed it. """ import argparse import sys @@ -53,6 +55,8 @@ def main(argv=None): formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("ledger", help="path to a mirror ledger (.jsonl)") ap.add_argument("--ots", help="OpenTimestamps proof (.ots) for the Bitcoin cross-check") + ap.add_argument("--manifest", help="the anchor manifest the --ots proof stamps; binds the " + "proof to this ledger so precedence can be reported") ap.add_argument("--explorer", help="block explorer API base (default: blockstream)") a = ap.parse_args(argv) @@ -65,7 +69,40 @@ def main(argv=None): print(f"{WARN} legacy 16-hex seals: weaker collision resistance") ok_btc = True - if a.ots: + bound = None + if a.manifest and not a.ots: + print(f"{FAIL} [binding] --manifest needs --ots (the proof that stamps it)") + ok_btc = False + elif a.ots and a.manifest: + try: + from . import ots_anchor + kw = {"explorer": a.explorer} if a.explorer else {} + bound = ots_anchor.bind(a.ledger, a.manifest, a.ots, **kw) + except Exception as e: # ots CLI missing / unreadable files + bound = {"bound": False, "bitcoin": {}, "note": f"binding check unavailable: {e}"} + res = bound.get("bitcoin") or {} + if res.get("block_height"): + print(f"{OK if res.get('verified') else WARN} [bitcoin] earliest block " + f"{res['block_height']} @ {res.get('block_time_utc')} — " + f"{'merkle root matches the explorer' if res.get('verified') else res.get('note', 'not confirmed')}") + print(f"{OK if bound.get('proof_matches_manifest') else FAIL} [binding] proof stamps the manifest") + if bound.get("proof_matches_manifest"): + print(f"{OK if bound.get('manifest_pins_ledger') else FAIL} [binding] manifest pins " + f"this ledger's first {bound.get('pinned_lines', '?')} line(s)") + if bound.get("bound"): + n_later = len(bound.get("uncovered_entries", [])) + print(f"{OK} [EXTERNAL_TIME] {bound['proves']}") + pre = [r["claim_id"] for r in bound.get("covered_entries", []) + if r.get("type") == "preregistration" and r.get("claim_id")] + if pre: + shown = ", ".join(pre[:10]) + (f" … (+{len(pre) - 10})" if len(pre) > 10 else "") + print(f"{OK} [EXTERNAL_TIME] preregistrations covered: {shown}") + if n_later: + print(f"{WARN} [EXTERNAL_TIME] {n_later} later line(s) are NOT covered by this proof") + else: + print(f"{FAIL} [EXTERNAL_TIME] not established — {bound.get('note')}") + ok_btc = bool(bound.get("bound")) + elif a.ots: try: ok_btc, res = check_bitcoin(a.ots, a.explorer) except Exception as e: # ots CLI missing / network — be explicit @@ -80,10 +117,15 @@ def main(argv=None): print(f"{WARN} [bitcoin] skipped — pass --ots PROOF.ots for the external-clock check") good = ok_chain and ok_btc - print(f"=== verdict: {'CONFIRMED' if good else 'NOT CONFIRMED'} (hash integrity) ===") - print("scope: hash integrity only; NOT author identity, content truth or independent reproduction.") - print("external time: ledger precedence UNVERIFIED — " - "a supplied Bitcoin proof is checked separately; ledger-to-proof binding is not checked here.") + scope = "hash integrity + external time" if bound and bound.get("bound") else "hash integrity" + print(f"=== verdict: {'CONFIRMED' if good else 'NOT CONFIRMED'} ({scope}) ===") + print("scope: NOT author identity, content truth or independent reproduction.") + if bound and bound.get("bound"): + print("external time: the pinned lines existed before the Bitcoin block above; " + "later lines are not covered.") + else: + print("external time: ledger precedence UNVERIFIED — " + "pass --ots PROOF.ots --manifest MANIFEST.json to bind a proof to this ledger.") return 0 if good else 1 diff --git a/tests/test_ots_binding.py b/tests/test_ots_binding.py new file mode 100644 index 0000000..3efc6ad --- /dev/null +++ b/tests/test_ots_binding.py @@ -0,0 +1,117 @@ +"""Proof -> manifest -> ledger binding, and earliest-attestation selection. + +`ots info` and the block explorer are faked: the cloud CI has neither the calendars' +real proofs for a test ledger nor guaranteed network access. The fake `ots info` text +mirrors the real layout (checked against a real 2026-07-25 proof): the file digest on +the first line, and each merkle-root comment right AFTER its attestation line, with the +earliest block NOT listed first. +""" +import hashlib +from pathlib import Path + +import pytest +from measure_mirror import mm + +from mirror_stack_mcp import ots_anchor as o +from mirror_stack_mcp import verify + +ROOT_LATE, ROOT_EARLY = "d" * 64, "f" * 64 +BLOCKS = {959655: ROOT_LATE, 959599: ROOT_EARLY} + + +def _fake_info(digest): + return (f"File sha256 hash: {digest}\n" + "Timestamp:\n" + "append aa\nsha256\n" + " -> append bb\n" + " verify BitcoinBlockHeaderAttestation(959655)\n" + f" # Bitcoin block merkle root {ROOT_LATE}\n" + " -> append cc\n" + " verify BitcoinBlockHeaderAttestation(959599)\n" + f" # Bitcoin block merkle root {ROOT_EARLY}\n") + + +@pytest.fixture +def anchored(tmp_path, monkeypatch): + led = tmp_path / "claims.jsonl" + for cid in ("c1", "c2"): + mm.preregister(str(led), cid, metric="acc", min_n=10, baseline=0.5, + pass_threshold=0.6, kill_condition="acc < 0.55") + man, sha = o.build_manifest([str(led)], str(tmp_path / "anchors")) + proof = man + ".ots" + Path(proof).write_bytes(b"fake") + mm.preregister(str(led), "c3_after_stamp", metric="acc", min_n=10, baseline=0.5, + pass_threshold=0.6) + state = {"digest": sha} + monkeypatch.setattr(o, "_info", lambda p: _fake_info(state["digest"])) + monkeypatch.setattr(o, "_explorer_block", + lambda h, e: (f"hash{h}", BLOCKS[h], 1785000000)) + return led, Path(man), Path(proof), state + + +def test_attestations_pair_each_root_with_its_block(): + assert o._attestations(_fake_info("0" * 64)) == [(959655, ROOT_LATE), (959599, ROOT_EARLY)] + + +def test_verify_uses_the_earliest_block(anchored): + _, _, proof, _ = anchored + r = o.verify(str(proof)) + assert r["block_height"] == 959599 + assert r["expected_merkle_root"] == ROOT_EARLY + assert r["verified"] is True + assert r["attested_blocks"] == [959599, 959655] + + +def test_bind_reports_only_the_pinned_prefix(anchored): + led, man, proof, _ = anchored + r = o.bind(str(led), str(man), str(proof)) + assert r["bound"] is True + assert r["existed_before"]["block_height"] == 959599 + assert [e["claim_id"] for e in r["covered_entries"]] == ["c1", "c2"] + assert [e["claim_id"] for e in r["uncovered_entries"]] == ["c3_after_stamp"] + assert {e["type"] for e in r["covered_entries"]} == {"preregistration"} + + +def test_proof_for_another_file_does_not_bind(anchored): + led, man, proof, state = anchored + state["digest"] = hashlib.sha256(b"some other manifest").hexdigest() + r = o.bind(str(led), str(man), str(proof)) + assert r["bound"] is False and r["proof_matches_manifest"] is False + assert "does not stamp this manifest" in r["note"] + + +def test_rewritten_ledger_does_not_bind(anchored): + led, man, proof, _ = anchored + lines = led.read_text(encoding="utf-8").splitlines(keepends=True) + led.write_text(lines[1] + lines[0] + lines[2], encoding="utf-8") + r = o.bind(str(led), str(man), str(proof)) + assert r["bound"] is False and r["manifest_pins_ledger"] is False + + +def test_explorer_mismatch_does_not_bind(anchored, monkeypatch): + led, man, proof, _ = anchored + monkeypatch.setattr(o, "_explorer_block", lambda h, e: (f"hash{h}", "e" * 64, 1785000000)) + r = o.bind(str(led), str(man), str(proof)) + assert r["bound"] is False + assert r["proof_matches_manifest"] is True and r["manifest_pins_ledger"] is True + + +def test_cli_reports_external_time_only_when_bound(anchored, capsys): + led, man, proof, state = anchored + assert verify.main([str(led), "--ots", str(proof), "--manifest", str(man)]) == 0 + out = capsys.readouterr().out + assert "[EXTERNAL_TIME] the first 2 ledger lines existed before Bitcoin block 959599" in out + assert "preregistrations covered: c1, c2" in out + assert "1 later line(s) are NOT covered" in out + assert "UNVERIFIED" not in out + + state["digest"] = "0" * 64 + assert verify.main([str(led), "--ots", str(proof), "--manifest", str(man)]) == 1 + out = capsys.readouterr().out + assert "[EXTERNAL_TIME] not established" in out + assert "ledger precedence UNVERIFIED" in out + + +def test_cli_manifest_without_proof_fails(anchored, capsys): + led, man, _, _ = anchored + assert verify.main([str(led), "--manifest", str(man)]) == 1 From 8bf09689723405aa54e2345532b1b78f739c7e5a Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 24 Nov 2026 02:51:40 +0000 Subject: [PATCH 2/2] fix(ots): surface ots crashes; find ots next to the interpreter On Windows, opentimestamps-client crashes on import (python-bitcoinlib finds no OpenSSL library). _info() returned the empty stdout, which bind() then misreported as a proof that names no file. It now raises with the client's error. Also look for ots beside sys.executable when the venv is not active. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Aq8kkjKAMDjSSK54hcWnuc --- CHANGELOG.md | 4 ++++ mirror_stack_mcp/ots_anchor.py | 43 ++++++++++++++++++++++++++++++---- tests/test_ots_binding.py | 23 ++++++++++++++++++ 3 files changed, 66 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 608cab7..586fc4c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ merkle root with its own block. It used the first one printed, which in a real multi-calendar proof was 56 blocks later than the earliest. Also reports `attested_blocks` and `proof_file_sha256`. +- `ots info` failures now raise with the client's own error instead of returning empty + output, which was misreported as "proof does not report which file it stamps" (seen on + Windows, where opentimestamps-client crashes on import). `ots` is also found next to the + running interpreter when the venv is not activated. - Replace deprecated `datetime.utcnow()` / `utcfromtimestamp()` (same output format). - OTS anchoring: optional publishable manifest (format 2). `stamp()` / `build_manifest()` diff --git a/mirror_stack_mcp/ots_anchor.py b/mirror_stack_mcp/ots_anchor.py index 50ab8ff..ba4cf68 100644 --- a/mirror_stack_mcp/ots_anchor.py +++ b/mirror_stack_mcp/ots_anchor.py @@ -19,12 +19,33 @@ import json import os import re +import shutil import subprocess +import sys import urllib.request import uuid from pathlib import Path -OTS = os.environ.get("OTS_BIN", "ots") +def _find_ots() -> str: + """`OTS_BIN`, else `ots` on PATH, else the `ots` installed next to this Python. + + pip puts the `ots` script beside the interpreter (venv `bin/` or `Scripts\\`). Without + this fallback, a venv that is not activated could not find it (seen on Windows). + """ + if os.environ.get("OTS_BIN"): + return os.environ["OTS_BIN"] + found = shutil.which("ots") + if found: + return found + here = os.path.dirname(sys.executable) + for name in ("ots", "ots.exe"): + cand = os.path.join(here, name) + if os.path.exists(cand): + return cand + return "ots" + + +OTS = _find_ots() DEFAULT_EXPLORER = os.environ.get("OTS_EXPLORER", "https://blockstream.info/api") _BLOCK_RE = re.compile(r"BitcoinBlockHeaderAttestation\((\d+)\)") _ROOT_RE = re.compile(r"Bitcoin block merkle root ([0-9a-fA-F]{64})") @@ -158,8 +179,18 @@ def build_manifest(ledger_paths: list[str], out_dir: str, *, def _info(ots_path: str) -> str: - return subprocess.run([OTS, "info", ots_path], capture_output=True, - text=True, timeout=60).stdout + """`ots info` output. Raises if `ots` fails, instead of returning partial stdout. + + A crashing client (e.g. opentimestamps-client on Windows, where python-bitcoinlib + cannot find an OpenSSL library) used to look like a proof with no file digest or + attestation — a wrong diagnosis. Now the real error surfaces. + """ + r = subprocess.run([OTS, "info", ots_path], capture_output=True, + text=True, encoding="utf-8", errors="replace", timeout=60) + if r.returncode != 0: + tail = (r.stderr or r.stdout or "").strip().splitlines()[-1:] or ["no output"] + raise RuntimeError(f"`ots info` failed (exit {r.returncode}): {tail[0][:300]}") + return r.stdout def stamp(ledger_paths: list[str], out_dir: str, *, id_map_path: str | None = None) -> dict: @@ -191,7 +222,11 @@ def upgrade(ots_path: str) -> dict: subprocess.run([OTS, "upgrade", ots_path], capture_output=True, text=True, timeout=120) except FileNotFoundError: return {"state": "error", "error": f"`{OTS}` not found — pip install opentimestamps-client"} - m = _BLOCK_RE.search(_info(ots_path)) + try: + info = _info(ots_path) + except RuntimeError as e: + return {"state": "error", "error": str(e)} + m = _BLOCK_RE.search(info) if m: return {"state": "bitcoin_confirmed", "block_height": int(m.group(1)), "next": f"mm_anchor_verify('{ots_path}')"} diff --git a/tests/test_ots_binding.py b/tests/test_ots_binding.py index 3efc6ad..a006fc0 100644 --- a/tests/test_ots_binding.py +++ b/tests/test_ots_binding.py @@ -115,3 +115,26 @@ def test_cli_reports_external_time_only_when_bound(anchored, capsys): def test_cli_manifest_without_proof_fails(anchored, capsys): led, man, _, _ = anchored assert verify.main([str(led), "--manifest", str(man)]) == 1 + + +def test_ots_crash_is_reported_not_misread(tmp_path, monkeypatch): + """A crashing `ots` must surface its error, not look like a proof without a digest.""" + import subprocess as sp + + class R: + returncode, stdout = 1, "" + stderr = "Traceback ...\nTypeError: argument of type 'NoneType' is not iterable" + + monkeypatch.setattr(o.subprocess, "run", lambda *a, **k: R()) + with pytest.raises(RuntimeError, match="ots info. failed .exit 1.: TypeError"): + o._info("x.ots") + assert o.upgrade(str(tmp_path / "x.ots"))["state"] == "error" + + +def test_ots_found_next_to_the_interpreter(tmp_path, monkeypatch): + monkeypatch.delenv("OTS_BIN", raising=False) + monkeypatch.setattr(o.shutil, "which", lambda name: None) + exe = tmp_path / "python" + (tmp_path / "ots").write_text("") + monkeypatch.setattr(o.sys, "executable", str(exe)) + assert o._find_ots() == str(tmp_path / "ots")