Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

## [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`.
- `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()`
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
Expand Down
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 17 additions & 3 deletions docs/ANCHORING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
177 changes: 161 additions & 16 deletions mirror_stack_mcp/ots_anchor.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,63 @@
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})")
_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:
Expand Down Expand Up @@ -110,11 +158,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}
Expand All @@ -131,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:
Expand Down Expand Up @@ -164,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}')"}
Expand All @@ -181,25 +243,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"]}
Expand Down Expand Up @@ -230,3 +303,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
Loading
Loading