#!/usr/bin/env python3
"""Check Ecoregions' daily timestamps against Bitcoin. Python 3.8+, nothing to install.

    python3 verify-stamp.py 2026-10-22.txt.ots           one proof (the .txt sits beside it)
    python3 verify-stamp.py --run https://ecoregionsworld.com/data/stamps/
                                                         every published day, and the run
    python3 verify-stamp.py --run <folder>               the same, for proofs you downloaded
    python3 verify-stamp.py --offline ...                no network: digests and structure only
    python3 verify-stamp.py --node ...                   ask your own Bitcoin Core (bitcoin-cli)

WHAT IT DOES, for each proof:

  1. hashes the .txt and compares it with the digest written inside the .ots;
  2. replays the proof, step by step, from that digest to every Bitcoin block it names;
  3. fetches each block's 80-byte header from two public explorers, checks that the header
     hashes to the block id they give and carries real proof of work, and compares its merkle
     root with what the proof computed;
  4. with --run, checks that no day is missing between the first stamp and the last, and that
     no stamp reached Bitcoin later than LATE_AFTER_HOURS after its stated day ended.

Only block heights and block ids are sent to the explorers, never your files.

WHAT A MATCH SHOWS: the text in the .txt existed no later than that block's time. It does not
show who wrote it, or that anything in it is true. Check 4 is what makes back-dating visible:
a text that says "2026-10-26" but first reached Bitcoin on the 29th was written after its date.

You do not have to trust this script. The OpenTimestamps project's own client (`ots verify`)
and the verifier at https://opentimestamps.org read the same two files and must agree with it.

Exit code: 0 if everything checked agreed (a pending newest proof is fine); 1 if anything
disagreed, a day is missing, or a stamp was late; 2 if nothing could be checked.
"""
import argparse, datetime, hashlib, json, os, re, subprocess, sys, urllib.parse, urllib.request

HEADER_MAGIC = b"\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94"
BITCOIN = bytes.fromhex("0588960d73d71901")
PENDING = bytes.fromhex("83dfe30d2ef90c8e")
LITECOIN = bytes.fromhex("06869a0d73d71b45")
EXPLORERS = ["https://mempool.space/api", "https://blockstream.info/api"]

# A stamp is late if its first Bitcoin block is more than this long after its stated day has
# ended everywhere on Earth (midnight at UTC-12). The job's first block has followed within about
# an hour every night so far (13-25 Oct 2026), but the public calendars have held commitments for
# more than a day during fee spikes (Dec 2023, Apr 2024), and a block time is forever: one slow
# night at a 24 h threshold would flip the whole run to "late" for every reader. Three days bounds
# back-dating to days, which is what this check is for; the publisher's refusal of a never-published
# day inside the published range is the finer guard.
LATE_AFTER_HOURS = 72

# Proof of work, in bits, that a header must carry before its merkle root is believed.
# Difficulty-1 headers (32 bits) can be mined on a laptop in minutes, so a lying explorer could
# forge one; Bitcoin in 2026 needs about 78 bits. 64 bits is roughly 2e19 hashes: an explorer
# would have to burn real mining revenue to fake a single block, and the second explorer would
# still have to agree.
MIN_WORK_BITS = 64


class Bad(Exception):
    """The proof is malformed, or disagrees with the file it claims to stamp."""


class Reader:
    def __init__(self, data):
        self.data, self.pos = data, 0

    def take(self, n):
        if self.pos + n > len(self.data):
            raise Bad("the .ots file ends in the middle of a field")
        out = self.data[self.pos:self.pos + n]
        self.pos += n
        return out

    def varuint(self):
        value = shift = 0
        while True:
            b = self.take(1)[0]
            value |= (b & 0x7F) << shift
            if not b & 0x80:
                return value
            shift += 7
            if shift > 63:
                raise Bad("a number in the .ots file is impossibly long")

    def varbytes(self, max_len, min_len=0):
        n = self.varuint()
        if not min_len <= n <= max_len:
            raise Bad("a field of %d bytes is outside %d..%d" % (n, min_len, max_len))
        return self.take(n)


def _ripemd160(m):
    try:
        return hashlib.new("ripemd160", m).digest()
    except ValueError:
        raise Bad("this proof uses RIPEMD-160, which this Python's OpenSSL lacks; use `ots verify`")


UNARY = {0x08: lambda m: hashlib.sha256(m).digest(), 0x02: lambda m: hashlib.sha1(m).digest(),
         0x03: _ripemd160, 0xF2: lambda m: m[::-1], 0xF3: lambda m: m.hex().encode()}
BINARY = {0xF0: lambda m, a: m + a, 0xF1: lambda m, a: a + m}  # append, prepend


def walk(r, msg, out, depth=0):
    """Read one timestamp node and everything under it, applying each operation to msg.
    Appends (kind, payload, msg-at-that-point) for every attestation found."""
    if depth > 256:
        raise Bad("the proof nests deeper than any real proof does")

    def one(tag):
        if tag == 0x00:
            kind = r.take(8)
            payload = Reader(r.varbytes(8192))
            if kind == BITCOIN:
                out.append(("bitcoin", payload.varuint(), msg))
            elif kind == PENDING:
                out.append(("pending", payload.varbytes(1000).decode("ascii", "replace"), msg))
            elif kind == LITECOIN:
                out.append(("litecoin", payload.varuint(), msg))
            else:
                out.append(("unknown", kind.hex(), msg))
        elif tag in UNARY:
            walk(r, UNARY[tag](msg), out, depth + 1)
        elif tag in BINARY:
            arg = r.varbytes(4096, min_len=1)
            res = BINARY[tag](msg, arg)
            if len(res) > 4096:
                raise Bad("an operation produced more than 4096 bytes")
            walk(r, res, out, depth + 1)
        elif tag == 0x67:
            raise Bad("this proof uses Keccak-256 (an Ethereum attestation); use `ots verify`")
        else:
            raise Bad("unknown operation 0x%02x in the proof" % tag)

    tag = r.take(1)[0]
    while tag == 0xFF:  # 0xff means "another branch follows this one"
        one(r.take(1)[0])
        tag = r.take(1)[0]
    one(tag)


def parse(ots_bytes, txt_bytes):
    """Return the list of attestations, or raise Bad. Checks the digest first."""
    r = Reader(ots_bytes)
    if r.take(len(HEADER_MAGIC)) != HEADER_MAGIC:
        raise Bad("not an OpenTimestamps proof (wrong header)")
    if r.varuint() != 1:
        raise Bad("an OpenTimestamps format version this script does not know")
    op = r.take(1)[0]
    if op != 0x08:
        raise Bad("the proof hashes its file with op 0x%02x, not SHA-256" % op)
    digest = r.take(32)
    if hashlib.sha256(txt_bytes).digest() != digest:
        raise Bad("DIGEST DIFFERS: the .txt is not the file this proof stamps")
    out = []
    walk(r, digest, out)
    if r.pos != len(ots_bytes):
        raise Bad("%d unexplained bytes after the end of the proof" % (len(ots_bytes) - r.pos))
    return digest, out


# ---- Bitcoin headers ---------------------------------------------------------------------

def http(url, timeout=30):
    req = urllib.request.Request(url, headers={"User-Agent": "ecoregions-verify-stamp/2"})
    with urllib.request.urlopen(req, timeout=timeout) as resp:
        return resp.read()


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


def check_header(header, block_id):
    """Check an 80-byte header against the id it was served under. Returns (merkle, time, bits)."""
    if len(header) != 80:
        raise Bad("a block header of %d bytes, not 80" % len(header))
    h = sha256d(header)
    if h[::-1].hex() != block_id:
        raise Bad("the header does not hash to the block id the explorer gave")
    nbits = int.from_bytes(header[72:76], "little")
    exp, mant = nbits >> 24, nbits & 0x007FFFFF
    target = mant << (8 * (exp - 3)) if exp > 3 else mant >> (8 * (3 - exp))
    if target <= 0 or int.from_bytes(h, "little") > target:
        raise Bad("the header does not meet its own proof-of-work target")
    work_bits = 256 - target.bit_length()
    if work_bits < MIN_WORK_BITS:
        raise Bad("the header carries only %d bits of work; anyone could mint it" % work_bits)
    return header[36:68], int.from_bytes(header[68:72], "little"), work_bits


_cache = {}


def headers_for(height, use_node):
    """Yield (source, merkle_root_internal_order, unix_time, work_bits) or (source, error)."""
    if height in _cache:
        yield from _cache[height]
        return
    got = []
    if use_node:
        sources = [("bitcoin-cli", None)]
    else:
        sources = [(urllib.parse.urlparse(e).netloc, e) for e in EXPLORERS]
    for name, base in sources:
        try:
            if base is None:
                bid = subprocess.check_output(["bitcoin-cli", "getblockhash", str(height)], text=True).strip()
                hdr = subprocess.check_output(["bitcoin-cli", "getblockheader", bid, "false"], text=True).strip()
            else:
                bid = http("%s/block-height/%d" % (base, height)).decode().strip()
                if not re.fullmatch(r"[0-9a-f]{64}", bid):
                    raise Bad("the explorer gave no block id for height %d" % height)
                hdr = http("%s/block/%s/header" % (base, bid)).decode().strip()
            merkle, t, work = check_header(bytes.fromhex(hdr), bid)
            got.append((name, merkle, t, work))
        except Bad as e:
            got.append((name, "REFUSED: %s" % e))
        except Exception as e:  # network, DNS, a missing bitcoin-cli
            got.append((name, "unreachable (%s)" % type(e).__name__))
    _cache[height] = got
    yield from got


# ---- one proof -----------------------------------------------------------------------------

def utc(t):
    return datetime.datetime.fromtimestamp(t, datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC")


def stated_date(txt_bytes):
    m = re.search(rb"\b(20\d\d-\d\d-\d\d)\b", txt_bytes.split(b"\n", 1)[0])
    return datetime.date.fromisoformat(m.group(1).decode()) if m else None


def check_one(name, txt_bytes, ots_bytes, offline, use_node, say):
    """Returns a dict: ok (bool or None if nothing could be checked), date, first_time, late, status."""
    res = {"name": name, "date": stated_date(txt_bytes), "ok": None, "first_time": None,
           "late": False, "status": "pending", "matched": 0, "disagreed": 0}
    try:
        digest, atts = parse(ots_bytes, txt_bytes)
    except Bad as e:
        say("  %s  FAIL  %s" % (name, e))
        res["ok"], res["status"] = False, "bad"
        return res
    btc = sorted({(h, m) for k, h, m in atts if k == "bitcoin"})
    pending = [p for k, p, _ in atts if k == "pending"]
    say("  %s  digest ok (sha256 %s…)  Bitcoin blocks: %s%s" % (
        name, digest.hex()[:16], ", ".join(str(h) for h, _ in btc) or "none yet",
        "" if btc else "  (pending at %d calendar%s)" % (len(pending), "" if len(pending) == 1 else "s")))
    if not btc:
        return res
    res["status"] = "complete"
    if offline:
        res["ok"] = True
        return res
    times = []
    for height, msg in btc:
        if len(msg) != 32:
            say("    block %d  FAIL  the proof ends in %d bytes, not a 32-byte merkle root" % (height, len(msg)))
            res["disagreed"] += 1
            continue
        for row in headers_for(height, use_node):
            if len(row) == 2:
                say("    block %d  %-18s %s" % (height, row[0], row[1]))
                if row[1].startswith("REFUSED"):
                    res["disagreed"] += 1
                continue
            src, merkle, t, work = row
            if merkle == msg:
                res["matched"] += 1
                times.append(t)
                say("    block %d  %-18s MATCH  block time %s, %d bits of work" % (height, src, utc(t), work))
            else:
                res["disagreed"] += 1
                say("    block %d  %-18s DIFFERENT  the block's merkle root is not what the proof computes" % (height, src))
    sources = {row[0] for h, _ in btc for row in headers_for(h, use_node) if len(row) == 4}
    res["sources"] = len(sources)
    if res["disagreed"]:
        res["ok"] = False
    elif res["matched"]:
        res["ok"] = True
        if len(sources) < 2 and not use_node:
            say("    note: only %d explorer answered; the match rests on one source" % len(sources))
    if times:
        res["first_time"] = min(times)
        if res["date"]:
            # The stated day ends everywhere at (date + 1) 00:00 in UTC-12, i.e. (date + 1) 12:00 UTC.
            end = datetime.datetime.combine(res["date"] + datetime.timedelta(days=1), datetime.time(12),
                                            datetime.timezone.utc)
            deadline = end + datetime.timedelta(hours=LATE_AFTER_HOURS)
            first = datetime.datetime.fromtimestamp(res["first_time"], datetime.timezone.utc)
            delay_h = (first - end).total_seconds() / 3600 + 12  # from the stated day's end at UTC, roughly
            if first > deadline:
                res["late"], res["ok"] = True, False
                say("    LATE  the text says %s but first reached Bitcoin %s, after %s" % (
                    res["date"], utc(res["first_time"]), deadline.strftime("%Y-%m-%d %H:%M UTC")))
            else:
                say("    existed by %s; stated date %s; first block %.0f h after that day ended (UTC)" % (
                    utc(res["first_time"]), res["date"], delay_h))
    return res


# ---- a run of days ------------------------------------------------------------------------

def load_run(where):
    """Yield (name, txt_bytes, ots_bytes, expected) for every proof in a folder or a site."""
    if re.match(r"https?://", where):
        base = where if where.endswith("/") else where + "/"
        index = json.loads(http(base + "index.json"))
        for s in index["stamps"]:
            txt, ots = http(base + s["txt"]), http(base + s["ots"])
            yield s["txt"], txt, ots, s
        return
    idx = os.path.join(where, "index.json")
    if os.path.exists(idx):
        with open(idx) as f:
            entries = json.load(f)["stamps"]
    else:
        entries = [{"txt": n[:-4], "ots": n} for n in sorted(os.listdir(where)) if n.endswith(".txt.ots")]
    for s in entries:
        with open(os.path.join(where, s["txt"]), "rb") as f:
            txt = f.read()
        with open(os.path.join(where, s["ots"]), "rb") as f:
            ots = f.read()
        yield s["txt"], txt, ots, s


def run(where, offline, use_node, say):
    results, mismatched = [], 0
    for name, txt, ots, expected in load_run(where):
        for key, data in (("txt_sha256", txt), ("ots_sha256", ots)):
            if key in expected and hashlib.sha256(data).hexdigest() != expected[key]:
                say("  %s  the index lists a different %s; the file changed after the index was written" % (name, key))
                mismatched += 1
        results.append(check_one(name, txt, ots, offline, use_node, say))
    if not results:
        say("no proofs found in %s" % where)
        return 2
    dates = sorted(r["date"] for r in results if r["date"])
    have = set(dates)
    gaps = []
    d = dates[0]
    while d <= dates[-1]:
        if d not in have:
            gaps.append(d)
        d += datetime.timedelta(days=1)
    dupes = len(dates) - len(have)
    # The newest proof is normally pending: it was stamped tonight and its block comes later.
    newest = max(results, key=lambda r: r["date"] or datetime.date.min)
    stale_pending = [r["name"] for r in results if r["status"] == "pending" and r is not newest]
    bad = [r["name"] for r in results if r["ok"] is False]
    say("")
    say("%d stamped days, %s to %s" % (len(have), dates[0], dates[-1]))
    say("missing days: %s" % (", ".join(map(str, gaps)) if gaps else "none"))
    if dupes:
        say("days stamped more than once: %d" % dupes)
    say("failed: %s" % (", ".join(bad) if bad else "none"))
    if stale_pending:
        say("still pending, though not the newest (upgrade them with `ots upgrade`): %s" % ", ".join(stale_pending))
    if offline:
        say("NOT checked against Bitcoin (--offline): digests and proof structure only")
    else:
        checked = sum(1 for r in results if r["ok"] is True)
        one = sum(1 for r in results if r["ok"] is True and r.get("sources", 2) < 2)
        say("checked against Bitcoin: %d of %d days%s" % (checked, len(results),
            "; %d of them by one explorer only" % one if one else ""))
    if bad or gaps or mismatched:
        return 1
    if not offline and not any(r["ok"] for r in results):
        return 2
    return 0


def main(argv):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("path", nargs="?", help="a .txt.ots (or its .txt)")
    ap.add_argument("--run", metavar="FOLDER_OR_URL", help="check every day in a folder or a site's data/stamps/")
    ap.add_argument("--offline", action="store_true", help="no network: digests and structure only")
    ap.add_argument("--node", action="store_true", help="read headers from your own bitcoin-cli")
    ap.add_argument("--quiet", action="store_true", help="print only the summary")
    a = ap.parse_args(argv)
    say = print
    if a.quiet:
        say = lambda s: print(s) if not s.startswith("  ") else None
    if a.run:
        return run(a.run, a.offline, a.node, say)
    if not a.path:
        ap.print_help()
        return 2
    ots_path = a.path if a.path.endswith(".ots") else a.path + ".ots"
    txt_path = ots_path[:-4]
    with open(txt_path, "rb") as f:
        txt = f.read()
    with open(ots_path, "rb") as f:
        ots = f.read()
    r = check_one(os.path.basename(txt_path), txt, ots, a.offline, a.node, say)
    if r["ok"] is None:
        say("nothing checked against Bitcoin yet (%s)" % ("pending proof" if r["status"] == "pending" else "no explorer reachable"))
        return 2
    return 0 if r["ok"] else 1


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