#!/usr/bin/env python3
"""Check CropPath's daily integrity anchors (#202) without trusting CropPath: Python 3.10+, standard library only.

One file on purpose: a buyer or an auditor downloads it, reads it, and runs it on any machine with Python, without
installing the platform or any package. The encoding it recomputes is "Canonical encoding" in integrity-anchors.md
(served at /developers/downloads/integrity-anchors.md); this file is independent of the platform's own code, and the
platform's tests check that both give the same bytes.

    # the whole chain: every anchor recomputed from the previous one, days consecutive, each time-stamp token's
    # imprint equal to its anchor and its genTime at most --max-lag-hours (48) after its day ended, and a verified
    # token for every day that ended longer ago than that (--allow-unstamped for a platform without a TSA; add
    # --tsa-ca to have `openssl ts -verify` check the token's signature too)
    python3 verify_anchors.py chain --api https://txng.theio.vn [--tsa-ca tsa-root.pem]
    python3 verify_anchors.py chain --anchors anchors.json
    # ... and the copy you saved earlier is an unchanged prefix of the live chain
    python3 verify_anchors.py chain --api https://txng.theio.vn --anchors saved.json

    # the inclusion proof of a public lot's seal, or of one of its events, against the published chain
    python3 verify_anchors.py proof --api https://txng.theio.vn --lot 074eb09b371fc71c380da235aea9c14a [--event ID]
    python3 verify_anchors.py proof --file proof.json --anchors anchors.json

    # one day recomputed from an auditor's export (a day's records, exported by CropPath's operators)
    python3 verify_anchors.py day --file export.json [--anchors anchors.json | --api https://txng.theio.vn]

`anchors.json` is the `items` of GET /v1/public/anchors pages (a JSON list), or one such page. Exit status: 0 every
check passed, 1 a check failed (each failure is printed), 2 the input could not be read.
"""

from __future__ import annotations

import argparse
import base64
import datetime as dt
import hashlib
import json
import os
import shutil
import struct
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request
from typing import Any

GENESIS = bytes(32)
EMPTY_ROOT = hashlib.sha256(b"").digest()
NULL, INT, FLOAT, TEXT = 0, 1, 2, 3
KINDS = ("audit", "evidence", "seal", "review", "held")
KIND_TAG = {"audit": 1, "evidence": 2, "seal": 3, "review": 4, "held": 5}
FIELDS = {
    "audit": (("id", INT), ("at", FLOAT), ("actor", TEXT), ("tenant", TEXT), ("action", TEXT), ("entity", TEXT),
              ("entity_id", TEXT), ("before_hash", TEXT), ("after", TEXT), ("request_id", TEXT), ("ip_hash", TEXT)),
    "evidence": (("id", TEXT), ("received_at", FLOAT), ("payload_sha256", TEXT)),
    "seal": (("manifest_sha256", TEXT), ("sealed_at", FLOAT), ("fruit_count", INT), ("event_count", INT)),
    "review": (("envelope_id", TEXT), ("decision", TEXT), ("reviewer", TEXT), ("note", TEXT), ("reviewed_at", FLOAT)),
    "held": (("id", TEXT), ("status", TEXT)),
}  # fmt: skip
# The fields that fix an anchor: a saved copy must hold the same values as the live chain.
ANCHOR_FIELDS = ("day", "seq", "version", "prev_anchor", *(f"{k}_root" for k in KINDS), "day_root",
                 *(f"{k}_count" for k in KINDS), "anchor")  # fmt: skip
OID_SHA256 = "2.16.840.1.101.3.4.2.1"
MAX_PAGES = 10000
MAX_LAG_HOURS = 48.0  # a token's genTime at most this long after its day ended (--max-lag-hours)


class Failed(Exception):
    """A check that did not pass."""


# --- the canonical encoding -------------------------------------------------------------------------------------------


def encode_field(value: Any, kind: int) -> bytes:
    if value is None:
        return b"\x00"
    if kind == INT:
        if isinstance(value, bool) or not isinstance(value, int):
            raise ValueError("not an integer")
        return b"\x01" + value.to_bytes(8, "big", signed=True)
    if kind == FLOAT:
        if isinstance(value, bool) or not isinstance(value, (int, float)):
            raise ValueError("not a number")
        return b"\x02" + struct.pack(">d", float(value))
    if not isinstance(value, str):
        raise ValueError("not a text")
    data = value.encode("utf-8")
    return b"\x03" + len(data).to_bytes(4, "big") + data


def encode_record(kind: str, values: list[Any]) -> bytes:
    if len(values) != len(FIELDS[kind]):
        raise ValueError(f"a {kind} record has {len(FIELDS[kind])} fields")
    return bytes([KIND_TAG[kind]]) + b"".join(encode_field(v, t) for v, (_, t) in zip(values, FIELDS[kind]))


def leaf_hash(record: bytes) -> bytes:
    return hashlib.sha256(b"\x00" + record).digest()


def node_hash(left: bytes, right: bytes) -> bytes:
    return hashlib.sha256(b"\x01" + left + right).digest()


def merkle_root(leaves: list[bytes]) -> bytes:
    """RFC 9162 2.1.1 MTH, by its definition: split at the largest power of two smaller than n."""
    if not leaves:
        return EMPTY_ROOT
    if len(leaves) == 1:
        return leaves[0]
    k = 1
    while k * 2 < len(leaves):
        k *= 2
    return node_hash(merkle_root(leaves[:k]), merkle_root(leaves[k:]))


def verify_inclusion(index: int, size: int, leaf: bytes, path: list[bytes], root: bytes) -> bool:
    """RFC 9162 2.1.3.2."""
    if index >= size:
        return False
    fn, sn, r = index, size - 1, leaf
    for p in path:
        if sn == 0:
            return False
        if fn & 1 or fn == sn:
            r = node_hash(p, r)
            while not fn & 1 and fn != 0:
                fn >>= 1
                sn >>= 1
        else:
            r = node_hash(r, p)
        fn >>= 1
        sn >>= 1
    return sn == 0 and r == root


def day_root(*roots: bytes) -> bytes:
    """SHA-256(02 || the roots of KINDS, in that order)."""
    if len(roots) != len(KINDS):
        raise ValueError(f"{len(KINDS)} roots expected")
    return hashlib.sha256(b"\x02" + b"".join(roots)).digest()


def chain_anchor(prev: bytes, root: bytes, day: str, counts: tuple[int, ...]) -> bytes:
    if len(counts) != len(KINDS):
        raise ValueError(f"{len(KINDS)} counts expected")
    return hashlib.sha256(prev + root + day.encode("ascii") + b"".join(n.to_bytes(8, "big") for n in counts)).digest()


def next_day(day: str) -> str:
    return (dt.date.fromisoformat(day) + dt.timedelta(days=1)).isoformat()


def day_roots(records: dict[str, list[list[Any]]]) -> dict[str, tuple[bytes, int]]:
    """Per kind, (root, count) of the records of an export, the leaves sorted by their hash as the encoding says."""
    out = {}
    for kind in KINDS:
        leaves = sorted(leaf_hash(encode_record(kind, values)) for values in records.get(kind) or [])
        out[kind] = (merkle_root(leaves), len(leaves))
    return out


# --- RFC 3161 token (only what is needed: the message imprint and genTime of the TSTInfo) -----------------------------


def _tlv(data: bytes, pos: int) -> tuple[int, bytes, int]:
    tag, n = data[pos], data[pos + 1]
    pos += 2
    if n & 0x80:
        size = n & 0x7F
        if size == 0 or size > 4:
            raise ValueError("unsupported DER length")
        n = int.from_bytes(data[pos:pos + size], "big")
        pos += size
    if pos + n > len(data):
        raise ValueError("truncated DER")
    return tag, data[pos:pos + n], pos + n


def _children(content: bytes) -> list[tuple[int, bytes]]:
    out, pos = [], 0
    while pos < len(content):
        tag, value, pos = _tlv(content, pos)
        out.append((tag, value))
    return out


def _oid(value: bytes) -> str:
    first = value[0]
    parts, n = [first // 40 if first < 80 else 2, first % 40 if first < 80 else first - 80], 0
    for b in value[1:]:
        n = (n << 7) | (b & 0x7F)
        if not b & 0x80:
            parts.append(n)
            n = 0
    return ".".join(map(str, parts))


def token_imprint(token: bytes) -> tuple[str, bytes, str]:
    """(hash algorithm OID, hashed message, genTime as written) of a TimeStampToken's TSTInfo. Nothing is verified
    here: the signature and the certificate chain are `openssl ts -verify`'s (--tsa-ca)."""
    tag, content_info, _ = _tlv(token, 0)
    parts = _children(content_info)
    if tag != 0x30 or len(parts) != 2 or _oid(parts[0][1]) != "1.2.840.113549.1.7.2":
        raise ValueError("not a CMS SignedData")
    signed = _children(_children(parts[1][1])[0][1])  # [0] EXPLICIT SignedData
    encap = _children(signed[2][1])  # encapContentInfo: eContentType, [0] EXPLICIT OCTET STRING
    if _oid(encap[0][1]) != "1.2.840.113549.1.9.16.1.4":
        raise ValueError("not a TSTInfo")
    tst_der = _children(encap[1][1])[0][1]
    tst = _children(_children(tst_der)[0][1])  # version, policy, messageImprint, serialNumber, genTime, ...
    imprint = _children(tst[2][1])
    algorithm = _oid(_children(imprint[0][1])[0][1])
    return algorithm, imprint[1][1], tst[4][1].decode("ascii")


def gen_time_seconds(gen_time: str) -> float:
    """A GeneralizedTime as a token writes it (YYYYMMDDHHMMSS[.fff]Z) in Unix seconds."""
    if not gen_time.endswith("Z") or len(gen_time) < 15:
        raise ValueError("genTime is not YYYYMMDDHHMMSS[.f]Z")
    whole = dt.datetime.strptime(gen_time[:14], "%Y%m%d%H%M%S").replace(tzinfo=dt.timezone.utc)
    fraction = gen_time[14:-1]
    return whole.timestamp() + (float("0" + fraction) if fraction else 0.0)


def day_end(day: str) -> float:
    return dt.datetime.fromisoformat(day).replace(tzinfo=dt.timezone.utc).timestamp() + 86400


def token_lag(anchor: dict[str, Any]) -> float | None:
    """How long after its day ended an anchor's verified token was made (seconds); None without one or unreadable."""
    ts = anchor.get("timestamp")
    if not ts or ts.get("status") != "verified":
        return None
    try:
        return gen_time_seconds(token_imprint(base64.b64decode(ts["token"], validate=True))[2]) - day_end(anchor["day"])
    except (KeyError, TypeError, ValueError, IndexError):
        return None


def check_token(anchor: dict[str, Any], tsa_ca: str | None, max_lag_hours: float = MAX_LAG_HOURS,
                backfill_before: str | None = None, *, allow_unstamped: bool = False,
                now: float | None = None) -> list[str]:  # fmt: skip
    """The failures of an anchor's time-stamp: a verified token of another anchor, made before its day ended, or made
    more than `max_lag_hours` after it; no verified token (pending, or none at all) once its day ended more than
    `max_lag_hours` before `now` (default: this machine's clock), unless `allow_unstamped` (a platform without a TSA).
    Neither lag applies to a day before `backfill_before` (the days the job back-filled when anchoring started, stamped
    all at once). A late or missing token is a failure because whoever rewrites a past day and rebuilds the later
    anchors can have the TSA stamp them again only later, or leave them unstamped."""
    backfilled = bool(backfill_before) and anchor["day"] < backfill_before
    ts = anchor.get("timestamp")
    if not ts or ts.get("status") != "verified":
        waited = (time.time() if now is None else now) - day_end(anchor["day"])
        if allow_unstamped or backfilled or waited <= max_lag_hours * 3600:
            return []
        return [f"{anchor['day']}: no verified time-stamp token {waited / 3600:.1f} h after its day ended, more than"
                f" {max_lag_hours:g} h (an anchor stamped late may have been rebuilt; --allow-unstamped when the"
                " platform has no TSA)"]  # fmt: skip
    try:
        token = base64.b64decode(ts["token"], validate=True)
        algorithm, digest, gen_time = token_imprint(token)
        lag = gen_time_seconds(gen_time) - day_end(anchor["day"])
    except (KeyError, TypeError, ValueError, IndexError) as e:
        return [f"{anchor['day']}: the time-stamp token cannot be read ({type(e).__name__})"]
    failures = []
    if algorithm != OID_SHA256 or digest.hex() != anchor["anchor"]:
        failures.append(f"{anchor['day']}: the time-stamp token is not of this anchor")
    if lag <= 0:  # the day is anchored only once it is over
        failures.append(f"{anchor['day']}: the time-stamp is not after its day")
    elif lag > max_lag_hours * 3600 and not backfilled:
        failures.append(f"{anchor['day']}: time-stamped {lag / 3600:.1f} h after its day ended, more than"
                        f" {max_lag_hours:g} h (an anchor stamped late may have been rebuilt)")  # fmt: skip
    if tsa_ca is not None:
        failures += _openssl_verify(anchor, token, tsa_ca)
    return failures


def _openssl_verify(anchor: dict[str, Any], token: bytes, tsa_ca: str) -> list[str]:
    openssl = shutil.which("openssl")
    if openssl is None:
        return [f"{anchor['day']}: --tsa-ca given but no openssl command found"]
    with tempfile.TemporaryDirectory() as tmp:
        path = os.path.join(tmp, "token.der")
        with open(path, "wb") as f:
            f.write(token)
        run = subprocess.run(
            [openssl, "ts", "-verify", "-digest", anchor["anchor"], "-in", path, "-token_in", "-CAfile", tsa_ca],
            capture_output=True, text=True, check=False,
        )  # fmt: skip
    if run.returncode != 0 or "Verification: OK" not in run.stdout:
        return [f"{anchor['day']}: openssl ts -verify refused the time-stamp token"]
    return []


# --- checks -----------------------------------------------------------------------------------------------------------


def check_anchor(anchor: dict[str, Any], prev: bytes) -> list[str]:
    """The failures of one anchor recomputed from its stored roots and counts and `prev`."""
    day = anchor["day"]
    roots = [bytes.fromhex(anchor[f"{k}_root"]) for k in KINDS]
    counts = tuple(int(anchor[f"{k}_count"]) for k in KINDS)
    failures = []
    if anchor["prev_anchor"] != prev.hex():
        failures.append(f"{day}: prev_anchor is not the previous day's anchor")
    if day_root(*roots).hex() != anchor["day_root"]:
        failures.append(f"{day}: day_root does not match its roots")
    if chain_anchor(prev, bytes.fromhex(anchor["day_root"]), day, counts).hex() != anchor["anchor"]:
        failures.append(f"{day}: the anchor does not recompute")
    return failures


def check_chain(anchors: list[dict[str, Any]], tsa_ca: str | None = None, max_lag_hours: float = MAX_LAG_HOURS,
                backfill_before: str | None = None, *, allow_unstamped: bool = False,
                now: float | None = None) -> list[str]:  # fmt: skip
    """Every anchor from the first (genesis) on: consecutive days, each recomputed, each token's imprint and time,
    and a token for every day past the lag limit (check_token)."""
    failures, prev, day = [], GENESIS, None
    for i, anchor in enumerate(anchors):
        if anchor.get("version") != 1:
            failures.append(f"{anchor.get('day')}: encoding version {anchor.get('version')} is not 1")
            continue
        if int(anchor["seq"]) != i:
            failures.append(f"{anchor['day']}: seq {anchor['seq']} is not {i} (a missing or extra day)")
        if day is not None and anchor["day"] != next_day(day):
            failures.append(f"{anchor['day']}: does not follow {day}")
        failures += check_anchor(anchor, prev)
        failures += check_token(anchor, tsa_ca, max_lag_hours, backfill_before, allow_unstamped=allow_unstamped,
                                now=now)  # fmt: skip
        prev, day = bytes.fromhex(anchor["anchor"]), anchor["day"]
    return failures


def check_saved(saved: list[dict[str, Any]], live: list[dict[str, Any]]) -> list[str]:
    """A copy of the anchors saved earlier must be an unchanged prefix of the live chain: the same anchors, day for
    day, and the same token where the copy already held a verified one. A past day rewritten since, with every later
    anchor rebuilt and stamped again, passes check_chain but not this."""
    failures = []
    for i, mine in enumerate(saved):
        if i >= len(live):
            failures.append(f"{mine.get('day')}: in your saved copy, no longer in the live chain")
            continue
        theirs = live[i]
        differ = [name for name in ANCHOR_FIELDS if mine.get(name) != theirs.get(name)]
        if differ:
            failures.append(f"{mine.get('day')}: the live chain differs from your saved copy ({', '.join(differ)})")
        token = (mine.get("timestamp") or {}).get("token")
        if token is not None and token != (theirs.get("timestamp") or {}).get("token"):
            failures.append(f"{mine.get('day')}: the live time-stamp token differs from your saved copy")
    return failures


def lag_report(anchors: list[dict[str, Any]]) -> str:
    """One line: how many anchors have a verified token, and the longest time from a day's end to its token."""
    lags = [(lag, a["day"]) for a in anchors if (lag := token_lag(a)) is not None]
    if not lags:
        return "no verified time-stamp token"
    lag, day = max(lags)
    return f"{len(lags)} time-stamp token(s); the latest was made {lag / 3600:.1f} h after its day ({day}) ended"


def check_proof(proof: dict[str, Any], anchors: list[dict[str, Any]] | None = None) -> list[str]:
    """An inclusion proof: the leaf recomputed from its record, the path up to the kind's root in the proof's anchor,
    that anchor recomputed, and (with `anchors`, the published chain) the same anchor published for that day."""
    kind, anchor = proof["kind"], proof["anchor"]
    record = proof["record"]
    leaf = leaf_hash(encode_record(kind, [record[name] for name, _ in FIELDS[kind]]))
    failures = []
    if leaf.hex() != proof["leaf_hash"]:
        failures.append("the leaf hash does not recompute from the record")
    if not proof.get("included"):
        failures.append("the record is not among the day's anchored records")
    elif not verify_inclusion(int(proof["leaf_index"]), int(proof["tree_size"]), leaf,
                              [bytes.fromhex(h) for h in proof["path"]], bytes.fromhex(anchor[f"{kind}_root"])):
        failures.append("the inclusion path does not lead to the anchored root")  # fmt: skip
    if int(proof["tree_size"]) != int(anchor[f"{kind}_count"]):
        failures.append("the tree size is not the anchored count")
    failures += check_anchor(anchor, bytes.fromhex(anchor["prev_anchor"]))
    if anchors is not None:
        published = next((a for a in anchors if a["day"] == anchor["day"]), None)
        if published is None or published["anchor"] != anchor["anchor"]:
            failures.append(f"{anchor['day']}: the proof's anchor is not the published one")
    return failures


def check_day(export: dict[str, Any], anchors: list[dict[str, Any]] | None = None) -> list[str]:
    """An auditor's export of one day: its records give the roots and counts of its anchor (the export's own, or the
    published one with `anchors`)."""
    day = export["day"]
    anchor = export.get("anchor")
    if anchors is not None:
        anchor = next((a for a in anchors if a["day"] == day), None)
    if anchor is None:
        return [f"{day}: no anchor to compare with"]
    failures = []
    for kind, (root, count) in day_roots(export["records"]).items():
        if root.hex() != anchor[f"{kind}_root"] or count != int(anchor[f"{kind}_count"]):
            failures.append(f"{day}: the {kind} records do not give the anchored root and count")
    return failures + check_anchor(anchor, bytes.fromhex(anchor["prev_anchor"]))


# --- input ------------------------------------------------------------------------------------------------------------


def _get(url: str) -> Any:
    request = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": "verify_anchors"})
    with urllib.request.urlopen(request, timeout=30) as response:  # noqa: S310 - the URL the user gave
        return json.loads(response.read().decode("utf-8"))


def fetch_anchors(api: str) -> list[dict[str, Any]]:
    """Every published anchor, page by page."""
    items, after = [], None
    for _ in range(MAX_PAGES):
        query = urllib.parse.urlencode({"limit": 100, **({"after": after} if after else {})})
        page = _get(f"{api.rstrip('/')}/v1/public/anchors?{query}")
        items += page["items"]
        after = page.get("next_after")
        if not after:
            return items
    raise ValueError("too many pages")


def read_anchors(path: str) -> list[dict[str, Any]]:
    with open(path, encoding="utf-8") as f:
        data = json.load(f)
    return data["items"] if isinstance(data, dict) else data


def _read_json(path: str) -> Any:
    with open(path, encoding="utf-8") as f:
        return json.load(f)


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(prog="verify_anchors.py", description=__doc__.split("\n\n")[0])
    sub = ap.add_subparsers(dest="command", required=True)
    for name in ("chain", "proof", "day"):
        p = sub.add_parser(name)
        p.add_argument("--api", help="the platform's address, e.g. https://txng.theio.vn")
        p.add_argument("--anchors", help="a file of published anchors instead of --api")
        if name == "chain":
            p.add_argument("--tsa-ca", help="the TSA's root certificate (PEM): also run openssl ts -verify")
            p.add_argument("--max-lag-hours", type=float, default=MAX_LAG_HOURS,
                           help="the longest time from a day's end to its token's genTime (default 48)")
            p.add_argument("--backfill-before", help="a day (YYYY-MM-DD): the days before it may be stamped late"
                                                     " (the back-fill when anchoring started)")  # fmt: skip
            p.add_argument("--allow-unstamped", action="store_true",
                           help="accept anchors without a verified token (a platform without a TSA): only the chain"
                                " itself and a saved copy then protect the history")  # fmt: skip
        else:
            p.add_argument("--file", help="the proof (from the anchor-proof route) or the export")
        if name == "proof":
            p.add_argument("--lot", help="a public lot id (with --api)")
            p.add_argument("--event", help="one of the lot's event ids (with --lot)")
    args = ap.parse_args(argv)
    try:
        anchors = fetch_anchors(args.api) if args.api else read_anchors(args.anchors) if args.anchors else None
        if args.command == "chain":
            if anchors is None:
                ap.error("chain needs --api or --anchors")
            if args.backfill_before is not None:
                dt.date.fromisoformat(args.backfill_before)  # ValueError: exit 2
            failures = check_chain(anchors, args.tsa_ca, args.max_lag_hours, args.backfill_before,
                                   allow_unstamped=args.allow_unstamped)  # fmt: skip
            checked = f"{len(anchors)} anchors"
            if args.api and args.anchors:
                saved = read_anchors(args.anchors)
                failures += check_saved(saved, anchors)
                checked += f", your saved copy of {len(saved)}"
            print(lag_report(anchors))
        elif args.command == "proof":
            if args.file:
                proof = _read_json(args.file)
            elif args.api and args.lot:
                query = "?" + urllib.parse.urlencode({"event": args.event}) if args.event else ""
                lot = urllib.parse.quote(args.lot, safe="")
                proof = _get(f"{args.api.rstrip('/')}/v1/public/lots/{lot}/anchor-proof{query}")
            else:
                ap.error("proof needs --file, or --api with --lot")
            failures = check_proof(proof, anchors)
            checked = f"the {proof['kind']} proof of day {proof['day']}"
        else:
            if not args.file:
                ap.error("day needs --file")
            export = _read_json(args.file)
            failures = check_day(export, anchors)
            checked = f"day {export['day']}"
    except (OSError, ValueError, KeyError, TypeError) as e:
        print(f"error: {type(e).__name__}: {e}", file=sys.stderr)
        return 2
    for failure in failures:
        print(f"FAILED {failure}")
    print(f"{checked}: " + ("every check passed" if not failures else f"{len(failures)} check(s) failed"))
    return 1 if failures else 0


if __name__ == "__main__":
    raise SystemExit(main())
