#!/usr/bin/env python3
"""Verify 93 Notary receipts offline (open source; needs `pip install cryptography` and the openssl command).

  python3 notary_verify.py receipts.json [--files DIR] [--cafile TSA_CA.pem ...]

Checks each receipt's Ed25519 signature, its inclusion in the signed tree head (RFC 6962), the head signature, and
(with openssl) each RFC 3161 timestamp over the head. With --files, also matches evidence files by SHA-256.
"""
import argparse, base64, hashlib, json, os, subprocess, sys, tempfile

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey


def sig_ok(pub, data, sig):
    try:
        Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(base64.b64decode(sig), data)
        return True
    except Exception:
        return False


def split(n):
    k = 1
    while k << 1 < n:
        k <<= 1
    return k


def node(l, r):
    return hashlib.sha256(b"\x01" + l + r).digest()


def root_from_path(m, n, lh, path):
    if n <= 1:
        return lh
    k = split(n)
    *rest, sib = path
    return node(root_from_path(m, k, lh, rest), sib) if m < k else node(sib, root_from_path(m - k, n - k, lh, rest))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("package")
    ap.add_argument("--files", help="folder with evidence files to match by SHA-256")
    ap.add_argument("--cafile", action="append", default=[], help="CA certificate(s) for the TSAs (for openssl ts -verify)")
    a = ap.parse_args()
    pkg = json.load(open(a.package))
    pub, head = pkg["public_key"], pkg.get("head")
    bad = 0
    if head:
        hb = head["head"].encode()
        h = json.loads(hb)
        ok = sig_ok(pub, hb, head["sig"])
        print(f"head: tree_size {h['tree_size']} root {h['root'][:16]}… signature {'OK' if ok else 'BAD'}")
        bad += not ok
        digest = hashlib.sha256(hb).hexdigest()
        for t in head.get("tsa") or []:
            with tempfile.NamedTemporaryFile(suffix=".tsr", delete=False) as f:
                f.write(base64.b64decode(t["token"]))
            cmd = ["openssl", "ts", "-verify", "-digest", digest, "-in", f.name]
            for c in a.cafile:
                cmd += ["-CAfile", c]
            r = subprocess.run(cmd, capture_output=True, text=True)
            verdict = "OK" if "Verification: OK" in r.stdout + r.stderr else ("no CA given" if not a.cafile else "FAILED")
            print(f"  timestamp {t['tsa']} at {t['gen_time']}: {verdict}")
            os.unlink(f.name)
    hashes = {}
    if a.files:
        for root, _, names in os.walk(a.files):
            for nm in names:
                p = os.path.join(root, nm)
                hashes[hashlib.sha256(open(p, "rb").read()).hexdigest()] = p
    for r in pkg["receipts"]:
        lb = r["leaf"].encode()
        leaf = json.loads(lb)
        s = sig_ok(pub, lb, r["sig"])
        inc = None
        if head and "path" in r:
            inc = root_from_path(r["idx"], json.loads(head["head"])["tree_size"], hashlib.sha256(b"\x00" + lb).digest(),
                                 [bytes.fromhex(x) for x in r["path"]]).hex() == json.loads(head["head"])["root"]
        f = hashes.get(leaf["sha256"])
        line = f"#{r['idx']} {leaf['received_at']} sha256 {leaf['sha256'][:12]}… signature {'OK' if s else 'BAD'}"
        line += "" if inc is None else f", in head {'OK' if inc else 'BAD'}"
        line += f", file {os.path.relpath(f, a.files)}" if f else ""
        print(line)
        bad += (not s) + (inc is False)
    print("ALL OK" if not bad else f"{bad} PROBLEM(S)")
    sys.exit(1 if bad else 0)


if __name__ == "__main__":
    main()
