#!/usr/bin/env python3
"""Check witness co-signatures on a honesty.tools receipt-log checkpoint, offline.

    python3 verify_cosignatures.py log/cosigned/23

Checks, with no network call:
  1. the checkpoint is signed by the pinned receipt-log key (C2SP signed-note, Ed25519, type 0x01);
  2. each witness line verifies under that witness's key in log/witnesses.txt
     (C2SP tlog-cosignature, cosignature/v1, type 0x04);
  3. if log/checkpoints/<size> exists, the co-signed body is byte-identical to it.

A co-signature means: that witness saw this log head at that time, and it was consistent with every
earlier head that witness had signed for this log. It says nothing about whether any entry is true.
Needs Python 3.9+ and the `cryptography` package.
"""
import base64, hashlib, os, struct, sys
from datetime import datetime, timezone
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

LOG_VKEY = "www.honesty.tools/receipts+fcd79bdd+AUF/J2nQKn90Ba52NjK0jqgIYayocRQGAYsK7PUdD7+C"  # = log/receipt-log.vkey


def parse_vkey(vkey, kind):
    name, kid, b64 = vkey.strip().split("+", 2)
    raw = base64.b64decode(b64)
    if raw[0] != kind or hashlib.sha256(name.encode() + b"\n" + raw).digest()[:4].hex() != kid:
        raise ValueError(f"bad vkey {vkey!r}")
    return name, bytes.fromhex(kid), Ed25519PublicKey.from_public_bytes(raw[1:])


def main(path):
    here = os.path.dirname(os.path.abspath(path))
    note = open(path, encoding="utf-8").read()
    body, _, sigs = note.partition("\n\n")
    body = (body + "\n").encode()
    lines = [l for l in sigs.splitlines() if l.startswith("\u2014 ")]
    origin, size = body.decode().splitlines()[:2]
    ok = True
    name, kid, key = parse_vkey(LOG_VKEY, 0x01)
    good = False
    for l in lines:
        _, who, sig = l.split(" ")
        blob = base64.b64decode(sig)
        if who == name and blob[:4] == kid:
            try:
                key.verify(blob[4:], body); good = True
            except Exception:
                pass
    print(("  \u2713" if good else "  \u2717") + f" log signature ({name}) on {origin} size {size}")
    ok &= good
    wfile = os.path.join(here, "..", "witnesses.txt") if os.path.basename(here) == "cosigned" else os.path.join(here, "witnesses.txt")
    for vkey in open(wfile, encoding="utf-8"):
        if not vkey.strip() or vkey.startswith("#"):
            continue
        name, kid, key = parse_vkey(vkey, 0x04)
        when = None
        for l in lines:
            _, who, sig = l.split(" ")
            blob = base64.b64decode(sig)
            if who != name or blob[:4] != kid:
                continue
            t = struct.unpack(">Q", blob[4:12])[0]
            try:
                key.verify(blob[12:], f"cosignature/v1\ntime {t}\n".encode() + body); when = t
            except Exception:
                pass
        if when is None:
            print(f"  - {name}: no valid co-signature on this checkpoint")
        else:
            print(f"  \u2713 {name} co-signed at {datetime.fromtimestamp(when, timezone.utc):%Y-%m-%d %H:%M:%S} UTC")
    pinned = os.path.join(here, "..", "checkpoints", size) if os.path.basename(here) == "cosigned" else None
    if pinned and os.path.exists(pinned):
        same = open(pinned, "rb").read().split(b"\n\n")[0] + b"\n" == body
        print(("  \u2713" if same else "  \u2717") + f" body matches log/checkpoints/{size}")
        ok &= same
    return 0 if ok else 1


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