#!/usr/bin/env python3
"""Open Cord checker. Usage: python3 verify.py sennit-cord.json [--head <fingerprint>]
Standalone: imports nothing from Sennit, so anyone can read and run it.
--head: the fingerprint you kept elsewhere (the monthly report prints it). Without it, a chain
that was re-hashed from start to end, or cut short, still checks out."""
import hashlib
import json
import sys

GENESIS = "0" * 64


def canonical(obj):
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def digest(prev, r):
    body = canonical({"seq": r["seq"], "ts": r["ts"], "kind": r["kind"], "user": r["user"], "data": r["data"]})
    return hashlib.sha256((prev + body).encode("utf-8")).hexdigest()


def check(records):
    prev = GENESIS
    for i, r in enumerate(records, 1):
        if r["seq"] != i:
            if r["seq"] > i:
                return i, "Record %d is missing." % i
            return r["seq"], "Record %d is out of order." % r["seq"]
        if r["prev_hash"] != prev:
            return i, "Record %d does not link to the record before it." % i
        if digest(prev, r) != r["hash"]:
            return i, "Record %d was changed after it was written." % i
        prev = r["hash"]
    return None, ""


def main(argv):
    args, want = argv[1:], None
    if len(args) == 3 and args[1] == "--head":
        args, want = args[:1], args[2].strip().lower()
    if len(args) != 1:
        print("Usage: python3 verify.py <export.json> [--head <fingerprint>]")
        return 2
    path = args[0]
    try:
        with open(path, encoding="utf-8") as f:
            doc = json.load(f)
        records = doc["records"]
        for r in records:
            r["seq"], r["ts"], r["kind"], r["user"], r["data"], r["prev_hash"], r["hash"]
        if doc.get("format") != "sennit-cord-1":
            raise ValueError("format")
    except (OSError, ValueError, KeyError, TypeError):
        print("Could not read %s as a Sennit Cord export." % path)
        return 2
    bad, reason = check(records)
    if bad is not None:
        print("BROKEN at record %d: %s" % (bad, reason))
        return 1
    head = records[-1]["hash"] if records else GENESIS
    if want is not None and head != want:
        print("BROKEN: the export ends at %s, not at the fingerprint you gave (%s). "
              "Records were rewritten or cut off the end." % (head, want))
        return 1
    print("OK: %d records, head %s" % (len(records), head))
    return 0


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