#!/usr/bin/env python3
"""
Independent Python reference for Prepared's public-timestamp anchors
(prepared-board.chain-anchors.v1): the anchor digest and the Merkle path.
https://preparedboard.com/standard#anchors

Standard library only (Python 3.8+). Shares no code with the JavaScript
verifier or the server.

    python3 verify_anchor.py --vectors anchor-vectors.json
    python3 verify_anchor.py bundle.zip            # or an unzipped bundle folder
    python3 verify_anchor.py bundle.zip --extract out/

For each anchor in anchors.json it checks:
  1. headHash equals the contentHash of the seal at that seq in seals.json;
  2. anchorDigest = SHA-256 of the canonical JSON of
     {schema: "prepared-board.chain-anchor.v1", boardId, seq, headHash, salt};
  3. folding merklePath from leaf = SHA-256(0x00 || digest) with
     node = SHA-256(0x01 || left || right) gives merkleRoot (RFC 6962).

It does not check the timestamps themselves. --extract writes each anchor's
RFC 3161 token and OpenTimestamps proof as files and prints the standard
tools' commands for them (openssl ts -verify, ots verify), or use
verify-bundle.mjs, which checks both offline.

Exit codes: 0 = every check passed, 1 = a check failed, 2 = could not read input.
"""
import base64
import hashlib
import io
import json
import os
import sys
import zipfile

CHAIN_ANCHOR_SCHEMA = "prepared-board.chain-anchor.v1"
CHAIN_ANCHORS_SCHEMA = "prepared-board.chain-anchors.v1"
MAX_SAFE = 2**53 - 1
_SHORT = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}


def _string(s):
    out = ['"']
    for ch in s:
        o = ord(ch)
        if ch in _SHORT:
            out.append(_SHORT[ch])
        elif o < 0x20 or 0xD800 <= o <= 0xDFFF:
            out.append("\\u%04x" % o)
        else:
            out.append(ch)
    out.append('"')
    return "".join(out)


def canonical_json(v):
    """prepared-board.canonical-json.v1 (keys sorted by UTF-16 code units)."""
    if v is None:
        return "null"
    if v is True:
        return "true"
    if v is False:
        return "false"
    if isinstance(v, int):
        if abs(v) > MAX_SAFE:
            raise ValueError("integer outside the safe range")
        return str(v)
    if isinstance(v, str):
        return _string(v)
    if isinstance(v, list):
        return "[" + ",".join(canonical_json(x) for x in v) + "]"
    if isinstance(v, dict):
        items = sorted(v.items(), key=lambda kv: kv[0].encode("utf-16-be", "surrogatepass"))
        return "{" + ",".join(_string(k) + ":" + canonical_json(x) for k, x in items) + "}"
    raise ValueError("canonical JSON cannot hold %s" % type(v).__name__)


def sha256(b):
    return hashlib.sha256(b).digest()


def anchor_digest(board_id, seq, head_hash, salt):
    obj = {"schema": CHAIN_ANCHOR_SCHEMA, "boardId": board_id, "seq": seq, "headHash": head_hash, "salt": salt}
    return sha256(canonical_json(obj).encode("utf-8")).hex()


def leaf_hash(digest_hex):
    return sha256(b"\x00" + bytes.fromhex(digest_hex)).hex()


def node_hash(left_hex, right_hex):
    return sha256(b"\x01" + bytes.fromhex(left_hex) + bytes.fromhex(right_hex)).hex()


def fold_path(digest_hex, path):
    acc = leaf_hash(digest_hex)
    for step in path:
        if step["side"] == "left":
            acc = node_hash(step["hash"], acc)
        elif step["side"] == "right":
            acc = node_hash(acc, step["hash"])
        else:
            raise ValueError("side must be left or right")
    return acc


def merkle_root(digests):
    """RFC 6962 Merkle tree hash: split at the largest power of two below n."""
    leaves = [leaf_hash(d) for d in digests]

    def mth(xs):
        if len(xs) == 1:
            return xs[0]
        k = 1
        while k * 2 < len(xs):
            k *= 2
        return node_hash(mth(xs[:k]), mth(xs[k:]))

    if not leaves:
        raise ValueError("no leaves")
    return mth(leaves)


def run_vectors(path):
    with open(path, "r", encoding="utf-8") as f:
        v = json.load(f)
    passed = failed = 0

    def check(ok, what):
        nonlocal passed, failed
        if ok:
            passed += 1
        else:
            failed += 1
            print("FAIL  " + what)

    for c in v["anchorDigest"]["cases"]:
        i = c["input"]
        canon = canonical_json(dict(schema=CHAIN_ANCHOR_SCHEMA, **i))
        check(canon == c["canonical"], "canonical JSON for %s" % i["boardId"])
        check(anchor_digest(i["boardId"], i["seq"], i["headHash"], i["salt"]) == c["anchorDigest"], "anchorDigest for %s" % i["boardId"])
    for t in v["merkle"]["trees"]:
        n = t["leafCount"]
        check([leaf_hash(d) for d in t["digests"]] == t["leafHashes"], "leaf hashes, %d leaves" % n)
        check(merkle_root(t["digests"]) == t["root"], "root, %d leaves" % n)
        for i, d in enumerate(t["digests"]):
            check(fold_path(d, t["paths"][i]) == t["root"], "path %d of %d" % (i, n))
    print("%d/%d vectors passed" % (passed, passed + failed))
    return 0 if failed == 0 else 1


def read_bundle(target):
    """Return {path: bytes}, paths relative to the bundle root."""
    files = {}
    if os.path.isdir(target):
        for root, _dirs, names in os.walk(target):
            for name in names:
                full = os.path.join(root, name)
                rel = os.path.relpath(full, target).replace(os.sep, "/")
                with open(full, "rb") as f:
                    files[rel] = f.read()
    else:
        with open(target, "rb") as f:
            data = f.read()
        with zipfile.ZipFile(io.BytesIO(data)) as z:
            for name in z.namelist():
                if not name.endswith("/"):
                    files[name] = z.read(name)
    # Bundles may sit inside one top-level folder.
    hits = sorted((p for p in files if p == "seals.json" or p.endswith("/seals.json")), key=lambda p: p.count("/"))
    prefix = hits[0][: -len("seals.json")] if hits else ""
    return {p[len(prefix):]: b for p, b in files.items() if p.startswith(prefix)}


def check_bundle(target, extract_dir=None):
    files = read_bundle(target)
    if "anchors.json" not in files:
        print("No anchors.json in this bundle: nothing to check (bundles without public timestamps are normal).")
        return 0
    anchors = json.loads(files["anchors.json"].decode("utf-8"))
    if anchors.get("schema") != CHAIN_ANCHORS_SCHEMA:
        print("FAIL  anchors.json schema is not %s" % CHAIN_ANCHORS_SCHEMA)
        return 1
    seals = {}
    if "seals.json" in files:
        for s in json.loads(files["seals.json"].decode("utf-8"))["seals"]:
            seals[(s["boardId"], s["seq"])] = s["contentHash"]
    bad = 0
    for i, a in enumerate(anchors["anchors"]):
        problems = []
        seal = seals.get((a["boardId"], a["seq"]))
        if seal is None:
            note = "no seal at this seq in seals.json (link to a record not checked)"
        else:
            note = "matches seals.json"
            if seal != a["headHash"]:
                problems.append("headHash does not match seal seq %d in seals.json" % a["seq"])
        digest = anchor_digest(a["boardId"], a["seq"], a["headHash"], a["salt"])
        if digest != a["anchorDigest"]:
            problems.append("anchorDigest does not match boardId, seq, headHash and salt")
        if fold_path(digest, a["merklePath"]) != a["merkleRoot"]:
            problems.append("the Merkle path does not lead to merkleRoot")
        status = "FAIL" if problems else "OK  "
        print("%s  board %s seq %d: digest and path to root %s; headHash %s" % (status, a["boardId"], a["seq"], a["merkleRoot"], note))
        for p in problems:
            print("        - " + p)
        bad += 1 if problems else 0
        if extract_dir:
            os.makedirs(extract_dir, exist_ok=True)
            stem = os.path.join(extract_dir, "anchor-%d" % (i + 1))
            if a.get("rfc3161"):
                with open(stem + ".tst", "wb") as f:
                    f.write(base64.b64decode(a["rfc3161"]["token"]))
                print("        openssl ts -verify -token_in -in %s.tst -digest %s -CAfile <TSA root you trust>" % (stem, a["merkleRoot"]))
            if a.get("opentimestamps"):
                with open(stem + ".ots", "wb") as f:
                    f.write(base64.b64decode(a["opentimestamps"]["proof"]))
                print("        ots verify -d %s %s.ots" % (a["merkleRoot"], stem))
    print("%d anchor(s), %d failed. Timestamps not checked here; use --extract with openssl/ots, or verify-bundle.mjs." % (len(anchors["anchors"]), bad))
    return 0 if bad == 0 else 1


def main(argv):
    if len(argv) == 2 and argv[0] == "--vectors":
        return run_vectors(argv[1])
    extract = None
    if "--extract" in argv:
        i = argv.index("--extract")
        if i + 1 >= len(argv):
            print("usage: --extract DIR", file=sys.stderr)
            return 2
        extract = argv[i + 1]
        argv = argv[:i] + argv[i + 2:]
    if len(argv) != 1 or argv[0].startswith("-"):
        print("usage: python3 verify_anchor.py --vectors anchor-vectors.json | <bundle.zip | folder> [--extract DIR]", file=sys.stderr)
        return 2
    try:
        return check_bundle(argv[0], extract)
    except (OSError, ValueError, KeyError, zipfile.BadZipFile) as e:
        print("could not read %s: %s" % (argv[0], e), file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
