#!/usr/bin/env python3
# SPDX-License-Identifier: MIT  (Copyright (c) 2026 Timestamped.io; see LICENSE)
"""
Standalone verifier for timestamped.io proofs. No dependencies beyond the
Python standard library; nothing here talks to timestamped.io.

  public:   python3 timestamped_verify.py public  --hash <sha256 hex> --txid <txid>
  private:  python3 timestamped_verify.py private --proof <proof blob hex> --txid <txid> [--hash <sha256> | --file <path>]
  legacy:   python3 timestamped_verify.py legacy  --hash <sha256 hex> --txid <txid>
  url:      python3 timestamped_verify.py url --proof-package proof.json --screenshot page.png [--text page.txt]
  envelope: python3 timestamped_verify.py envelope --certificate certificate.json [--file <signed document>]
  receipt:  python3 timestamped_verify.py receipt --receipt r1.json [--receipt r2.json ...] [--file <document>] [--issuer-key key.pem] [--account <tag>]
  fetch:    python3 timestamped_verify.py fetch --txid <txid> [--txid ...] --out <folder>

Every check takes --evidence <folder> (files written by `fetch`, or gathered from any source)
and --offline (use only that folder, never the network).

Two things are checked: that the transaction commits to the claim, and that the transaction
is in a block (Merkle proof against an 80-byte block header with valid proof of work).
  exit 0  VALID        both hold
  exit 1  INVALID      the claim or the block proof fails
  exit 2  UNCONFIRMED  the claim holds, but there is no Merkle proof or header (not mined yet?)
          (envelope: INCOMPLETE, also exit 2, when it is not notarized yet)
Block headers must have difficulty >= 1e9 (real BSV blocks: ~3e10); --min-difficulty overrides.
The formats are documented in docs/proof-format.md of the API repository.
"""
import argparse
import base64
import datetime
import hashlib
import json
import os
import struct
import sys
import urllib.error
import urllib.request

PROTOCOL_MAGIC = b"timestamped.io/v1"
SILENT_MAGIC = b"timestamped.io/silent"
LEGACY_PREFIX = b"timestamped.io"


# ---------------------------------------------------------------- hashing
def sha256(b: bytes) -> bytes:
    return hashlib.sha256(b).digest()


def ripemd160(b: bytes) -> bytes:
    try:
        return hashlib.new("ripemd160", b).digest()
    except ValueError:
        return _ripemd160_pure(b)


def _ripemd160_pure(message: bytes) -> bytes:
    """Pure-Python RIPEMD-160 (RFC-style reference), used when OpenSSL lacks it."""
    def rol(x, n): return ((x << n) | (x >> (32 - n))) & 0xFFFFFFFF
    r = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
         3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
         4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]
    rr = [5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
          15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
          12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]
    s = [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
         11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
         9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6]
    ss = [8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
          9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
          8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11]
    K = [0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]
    KK = [0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]
    F = [lambda x, y, z: x ^ y ^ z, lambda x, y, z: (x & y) | (~x & z), lambda x, y, z: (x | ~y) ^ z,
         lambda x, y, z: (x & z) | (y & ~z), lambda x, y, z: x ^ (y | ~z)]
    h = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]
    ml = len(message) * 8
    message += b"\x80" + b"\x00" * ((56 - (len(message) + 1) % 64) % 64) + struct.pack("<Q", ml)
    for off in range(0, len(message), 64):
        X = list(struct.unpack("<16L", message[off:off + 64]))
        al, bl, cl, dl, el = h
        ar, br, cr, dr, er = h
        for j in range(80):
            rnd = j // 16
            t = (rol((al + F[rnd](bl, cl, dl) + X[r[j]] + K[rnd]) & 0xFFFFFFFF, s[j]) + el) & 0xFFFFFFFF
            al, el, dl, cl, bl = el, dl, rol(cl, 10), bl, t
            t = (rol((ar + F[4 - rnd](br, cr, dr) + X[rr[j]] + KK[rnd]) & 0xFFFFFFFF, ss[j]) + er) & 0xFFFFFFFF
            ar, er, dr, cr, br = er, dr, rol(cr, 10), br, t
        t = (h[1] + cl + dr) & 0xFFFFFFFF
        h = [t, (h[2] + dl + er) & 0xFFFFFFFF, (h[3] + el + ar) & 0xFFFFFFFF,
             (h[4] + al + br) & 0xFFFFFFFF, (h[0] + bl + cr) & 0xFFFFFFFF]
    return struct.pack("<5L", *h)


# ---------------------------------------------------------------- secp256k1 (pure Python, verification-speed is fine)
_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F
_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
      0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)


def _ec_add(p, q):
    if p is None: return q
    if q is None: return p
    (x1, y1), (x2, y2) = p, q
    if x1 == x2 and (y1 + y2) % _P == 0: return None
    if p == q:
        lam = (3 * x1 * x1) * pow(2 * y1, _P - 2, _P) % _P
    else:
        lam = (y2 - y1) * pow(x2 - x1, _P - 2, _P) % _P
    x3 = (lam * lam - x1 - x2) % _P
    return x3, (lam * (x1 - x3) - y1) % _P


def _ec_mul(k, p=_G):
    result = None
    while k:
        if k & 1: result = _ec_add(result, p)
        p = _ec_add(p, p)
        k >>= 1
    return result


def pubkey_compressed(private_key: bytes) -> bytes:
    k = int.from_bytes(private_key, "big")
    if not 0 < k < _N:
        raise ValueError("private key out of range")
    x, y = _ec_mul(k)
    return (b"\x02" if y % 2 == 0 else b"\x03") + x.to_bytes(32, "big")


# ---------------------------------------------------------------- base58 / addresses
_B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"


def base58check(payload: bytes) -> str:
    data = payload + sha256(sha256(payload))[:4]
    n = int.from_bytes(data, "big")
    out = ""
    while n:
        n, rem = divmod(n, 58)
        out = _B58[rem] + out
    pad = len(data) - len(data.lstrip(b"\x00"))
    return "1" * pad + out


def hash160(b: bytes) -> bytes:
    return ripemd160(sha256(b))


def derive_address(proof_blob: bytes) -> str:
    """Private/Anonymous modes: seed = SHA-256(proof blob) is the private key; P2PKH of its compressed pubkey."""
    return base58check(b"\x00" + hash160(pubkey_compressed(sha256(proof_blob))))


def p2pkh_script_for(address: str) -> str:
    # decode base58check to the 20-byte hash160
    n = 0
    for ch in address:
        n = n * 58 + _B58.index(ch)
    raw = n.to_bytes(25, "big")  # leading '1's become leading zero bytes
    if sha256(sha256(raw[:-4]))[:4] != raw[-4:]:
        raise ValueError("bad address checksum")
    return "76a914" + raw[1:21].hex() + "88ac"


# ---------------------------------------------------------------- transaction parsing
def varint(n: int) -> bytes:
    if n < 0xFD: return bytes([n])
    if n <= 0xFFFF: return b"\xfd" + n.to_bytes(2, "little")
    if n <= 0xFFFFFFFF: return b"\xfe" + n.to_bytes(4, "little")
    return b"\xff" + n.to_bytes(8, "little")


def pushdata(b: bytes) -> bytes:
    n = len(b)
    if n <= 75: return bytes([n]) + b
    if n <= 255: return b"\x4c" + bytes([n]) + b
    if n <= 65535: return b"\x4d" + n.to_bytes(2, "little") + b
    return b"\x4e" + n.to_bytes(4, "little") + b


def _read_varint(data: bytes, pos: int):
    first = data[pos]
    if first < 0xFD: return first, pos + 1
    if first == 0xFD: return int.from_bytes(data[pos + 1:pos + 3], "little"), pos + 3
    if first == 0xFE: return int.from_bytes(data[pos + 1:pos + 5], "little"), pos + 5
    return int.from_bytes(data[pos + 1:pos + 9], "little"), pos + 9


def txid_of(raw_tx_hex: str) -> str:
    """A txid is the double SHA-256 of the raw transaction, byte-reversed."""
    return sha256(sha256(bytes.fromhex(raw_tx_hex.strip())))[::-1].hex()


def check_txid(raw_tx_hex: str, txid: str) -> bool:
    """The explorer must have returned the transaction we asked for."""
    return txid_of(raw_tx_hex) == txid.strip().lower()


def parse_outputs(raw_tx_hex: str):
    data = bytes.fromhex(raw_tx_hex.strip())
    pos = 4
    n_in, pos = _read_varint(data, pos)
    for _ in range(n_in):
        pos += 36
        l, pos = _read_varint(data, pos)
        pos += l + 4
    n_out, pos = _read_varint(data, pos)
    outs = []
    for _ in range(n_out):
        value = int.from_bytes(data[pos:pos + 8], "little"); pos += 8
        l, pos = _read_varint(data, pos)
        outs.append((value, data[pos:pos + l].hex())); pos += l
    return outs


def _script_pushes(script: bytes):
    """Yield the data pushes of a script in order (opcodes are skipped)."""
    i = 0
    while i < len(script):
        op = script[i]; i += 1
        if 1 <= op <= 75: yield script[i:i + op]; i += op
        elif op == 0x4C: n = script[i]; i += 1; yield script[i:i + n]; i += n
        elif op == 0x4D: n = int.from_bytes(script[i:i + 2], "little"); i += 2; yield script[i:i + n]; i += n
        elif op == 0x4E: n = int.from_bytes(script[i:i + 4], "little"); i += 4; yield script[i:i + n]; i += n


# ---------------------------------------------------------------- the three checks
def verify_public(raw_tx_hex: str, file_hash_hex: str) -> bool:
    """Public mode: an output script pushes the 32-byte hash followed by either the structured
    payload (which repeats the hash) or, in the early layout, the plain 'timestamped.io' prefix."""
    want = bytes.fromhex(file_hash_hex)
    for _, script_hex in parse_outputs(raw_tx_hex):
        pushes = list(_script_pushes(bytes.fromhex(script_hex)))
        if len(pushes) < 2 or pushes[0] != want:
            continue
        payload = pushes[1]
        try:
            if payload.startswith(PROTOCOL_MAGIC):
                algo_len = payload[len(PROTOCOL_MAGIC) + 3]
                start = len(PROTOCOL_MAGIC) + 3 + 1 + algo_len
                if payload[start:start + 32] == want:
                    return True
            elif len(payload) == 14 and payload.rstrip(b"\x00") == LEGACY_PREFIX:
                return True  # early layout (January 2026): <hash> "timestamped.io" [<metadata>] OP_2DROP OP_DROP
        except (IndexError, ValueError):
            continue  # a truncated or malformed payload is simply not a proof
    return False


def parse_proof_blob(blob: bytes) -> dict:
    """Split a Private/Anonymous proof blob into its fields (see proof-format.md section 2.1)."""
    if not blob.startswith(SILENT_MAGIC):
        raise ValueError("not a timestamped.io/silent proof blob")
    i = len(SILENT_MAGIC)
    version = blob[i:i + 3].decode(); i += 3
    n = blob[i]; i += 1; algo = blob[i:i + n].decode(); i += n
    file_hash = blob[i:i + 32].hex(); i += 32
    n = blob[i]; i += 1; mode = blob[i:i + n].decode(); i += n
    n = blob[i]; i += 1; notes = blob[i:i + n].decode("utf-8", "replace"); i += n
    return {"version": version, "algorithm": algo, "file_hash": file_hash, "mode": mode, "notes": notes}


def verify_private(raw_tx_hex: str, proof_blob_hex: str) -> bool:
    """Private/Anonymous: the tx pays at least 1 satoshi to the address derived from the proof blob."""
    blob = bytes.fromhex(proof_blob_hex)
    if not blob.startswith(SILENT_MAGIC):
        return False
    expected = p2pkh_script_for(derive_address(blob))
    return any(value >= 1 and script == expected for value, script in parse_outputs(raw_tx_hex))


def verify_legacy(raw_tx_hex: str, file_hash_hex: str) -> bool:
    """Legacy OP_RETURN: 'timestamped.io <hex hash> ...' as a single push after OP_FALSE OP_RETURN."""
    for _, script_hex in parse_outputs(raw_tx_hex):
        script = bytes.fromhex(script_hex)
        if script[:2] != b"\x00\x6a":
            continue
        for push in _script_pushes(script[2:]):
            parts = push.split(b" ")
            if len(parts) >= 2 and parts[0] == LEGACY_PREFIX and parts[1].lower() == file_hash_hex.lower().encode():
                return True
    return False


def verify_url_package(package: dict, screenshot: bytes, text, raw_tx_hex: str) -> bool:
    """URL timestamp: combined = SHA-256(text_hash || screenshot_hash), anchored in Public mode.

    The service only keeps the text's hash, not the text, so unless you have the page text
    yourself the text hash is taken from the package on trust; the screenshot bytes are
    always re-hashed locally.
    """
    hashes_ = package["hashes"]
    text_hash = hashlib.sha256(text).hexdigest() if text is not None else hashes_["text_content_hash"]
    shot_hash = hashlib.sha256(screenshot).hexdigest()
    combined = hashlib.sha256((text_hash + shot_hash).encode()).hexdigest()
    return combined == hashes_["combined_hash"] and verify_public(raw_tx_hex, combined)


def public_metadata(raw_tx_hex: str, file_hash_hex: str):
    """The user metadata of a structured Public-mode payload for this hash (section 1.1), parsed as JSON.
    None when there is no structured payload, no metadata, or the metadata is not valid JSON (it is truncated at 200 bytes)."""
    want = bytes.fromhex(file_hash_hex)
    for _, script_hex in parse_outputs(raw_tx_hex):
        pushes = list(_script_pushes(bytes.fromhex(script_hex)))
        if len(pushes) < 2 or pushes[0] != want or not pushes[1].startswith(PROTOCOL_MAGIC):
            continue
        p = pushes[1]
        try:
            i = len(PROTOCOL_MAGIC) + 3
            i += 1 + p[i] + 32
            i += 1 + p[i]
            n = int.from_bytes(p[i:i + 2], "big")
            return json.loads(p[i + 2:i + 2 + n]) if n else None
        except (IndexError, ValueError):
            return None
    return None


# ---------------------------------------------------------------- block inclusion (Merkle proof + block header)
# Hashes are written in display order (byte-reversed), like txids and block hashes on explorers.
POW_LIMIT = 0xFFFF << 208  # difficulty 1 (bits 1d00ffff)
# Real BSV blocks since the first timestamped.io record (2026) have difficulty around 3e10. At difficulty 1
# a header can be forged in minutes; the default floor makes forging one cost real mining. Override with
# --min-difficulty if BSV difficulty ever falls below it.
MIN_DIFFICULTY = 1e9


def dsha256(b: bytes) -> bytes:
    return sha256(sha256(b))


def _is_hash_hex(s) -> bool:
    return isinstance(s, str) and len(s) == 64 and all(c in "0123456789abcdefABCDEF" for c in s)


def _merkle_parent(left_hex: str, right_hex: str) -> str:
    return dsha256(bytes.fromhex(left_hex)[::-1] + bytes.fromhex(right_hex)[::-1])[::-1].hex()


def merkle_root_from_tsc(txid: str, proof: dict) -> str:
    """BRC-10 (TSC) single-branch proof, the shape Bitails and WhatsOnChain return:
    {"index", "txOrId", "target", "nodes"}, where a node "*" repeats the working hash."""
    if proof.get("composite") or proof.get("proofType", "branch") != "branch":
        raise ValueError("only single-branch TSC proofs are supported")
    tx_or_id = str(proof.get("txOrId", "")).lower()
    proven = tx_or_id if len(tx_or_id) == 64 else txid_of(tx_or_id)
    if proven != txid.lower():
        raise ValueError("the Merkle proof is for a different transaction")
    index = proof.get("index")
    if not isinstance(index, int) or isinstance(index, bool) or index < 0:
        raise ValueError("the Merkle proof has no valid index")
    h = proven
    for node in proof.get("nodes", []):
        if node == "*":
            if index & 1:
                raise ValueError("a right-hand node cannot repeat the working hash")
            sibling = h
        elif _is_hash_hex(node):
            sibling = node.lower()
        else:
            raise ValueError("the Merkle proof has a malformed node")
        h = _merkle_parent(sibling, h) if index & 1 else _merkle_parent(h, sibling)
        index >>= 1
    if index:
        raise ValueError("the index does not fit the Merkle proof's tree")
    return h


def parse_bump(bump) -> dict:
    """BRC-74 BUMP, as the JSON object or as the binary encoding in hex."""
    if isinstance(bump, dict):
        return bump
    data = bytes.fromhex(bump.strip())
    height, pos = _read_varint(data, 0)
    tree_height = data[pos]; pos += 1
    path = []
    for _ in range(tree_height):
        n, pos = _read_varint(data, pos)
        leaves = []
        for _ in range(n):
            offset, pos = _read_varint(data, pos)
            flags = data[pos]; pos += 1
            leaf = {"offset": offset}
            if flags & 1:
                leaf["duplicate"] = True
            else:
                if flags & 2:
                    leaf["txid"] = True
                leaf["hash"] = data[pos:pos + 32][::-1].hex(); pos += 32
            leaves.append(leaf)
        path.append(leaves)
    if pos != len(data):
        raise ValueError("trailing bytes after the BUMP")
    return {"blockHeight": height, "path": path}


def merkle_root_from_bump(txid: str, bump):
    """Merkle root and block height from a BRC-74 BUMP that contains txid."""
    bump = parse_bump(bump)
    txid = txid.lower()
    leaf = next((l for l in bump["path"][0] if str(l.get("hash", "")).lower() == txid), None)
    if leaf is None:
        raise ValueError("the BUMP does not contain this transaction")
    index, h = leaf["offset"], txid
    for height, leaves in enumerate(bump["path"]):
        offset = (index >> height) ^ 1
        sib = next((l for l in leaves if l.get("offset") == offset), None)
        if sib is None:
            raise ValueError(f"the BUMP has no sibling hash at height {height}")
        if sib.get("duplicate"):
            if offset % 2 == 0:
                raise ValueError("a left-hand node cannot repeat the working hash")
            sibling = h
        elif _is_hash_hex(sib.get("hash")):
            sibling = sib["hash"].lower()
        else:
            raise ValueError("the BUMP has a malformed hash")
        h = _merkle_parent(sibling, h) if offset % 2 == 0 else _merkle_parent(h, sibling)
    return h, bump["blockHeight"]


def tsc_to_bump(txid: str, proof: dict, block_height: int) -> dict:
    """Single-transaction BUMP (BRC-74 JSON) equivalent to a TSC proof; BUMP needs the block height, TSC does not carry it."""
    merkle_root_from_tsc(txid, proof)  # validates the proof first
    index, nodes = proof["index"], proof["nodes"]
    path = []
    for height, node in enumerate(nodes):
        sib = {"offset": (index >> height) ^ 1}
        if node == "*":
            sib["duplicate"] = True
        else:
            sib["hash"] = node.lower()
        path.append([{"offset": index, "txid": True, "hash": txid.lower()}, sib] if height == 0 else [sib])
    if path:
        path[0].sort(key=lambda l: l["offset"])
    return {"blockHeight": block_height, "path": path}


def parse_header(header_hex: str) -> dict:
    """An 80-byte block header: its hash, Merkle root, time, and whether its proof of work meets its own target."""
    h = bytes.fromhex(header_hex.strip())
    if len(h) != 80:
        raise ValueError("a block header is exactly 80 bytes")
    block_hash = dsha256(h)[::-1].hex()
    bits = int.from_bytes(h[72:76], "little")
    exponent, mantissa = bits >> 24, bits & 0x007FFFFF
    target = 0 if bits & 0x00800000 else (mantissa << (8 * (exponent - 3)) if exponent >= 3 else mantissa >> (8 * (3 - exponent)))
    return {
        "hash": block_hash,
        "prev_hash": h[4:36][::-1].hex(),
        "merkle_root": h[36:68][::-1].hex(),
        "time": int.from_bytes(h[68:72], "little"),
        "bits": f"{bits:08x}",
        "pow_ok": 0 < target <= POW_LIMIT and int(block_hash, 16) <= target,
        "difficulty": POW_LIMIT / target if target else 0.0,
    }


def verify_inclusion(txid: str, merkle_proof, header_hex: str, min_difficulty: float = MIN_DIFFICULTY) -> dict:
    """Prove that txid is in the block whose header is given. Raises ValueError with the reason when it is not.
    This proves membership of that block only; whether the block is on the main chain depends on where the header came from."""
    header = parse_header(header_hex)
    if not header["pow_ok"]:
        raise ValueError("the block header does not meet its proof-of-work target")
    if header["difficulty"] < min_difficulty:
        raise ValueError(f"the block header's difficulty {header['difficulty']:.3g} is below the floor {min_difficulty:.3g}"
                         " (real BSV blocks are far above it; a low-difficulty header is cheap to forge)")
    height = None
    if isinstance(merkle_proof, str) or "path" in merkle_proof:
        root, height = merkle_root_from_bump(txid, merkle_proof)
    else:
        root = merkle_root_from_tsc(txid, merkle_proof)
        target_type = merkle_proof.get("targetType", "hash")
        target = str(merkle_proof.get("target", "")).lower()
        expected = {"hash": header["hash"], "header": header_hex.strip().lower(), "merkleRoot": root}.get(target_type)
        if expected is None:
            raise ValueError(f"unsupported TSC targetType {target_type!r}")
        if target != expected:
            raise ValueError("the Merkle proof points at a different block than this header")
    if root != header["merkle_root"]:
        raise ValueError("the Merkle proof does not lead to this block's Merkle root")
    return {"block_hash": header["hash"], "block_time": header["time"], "block_height": height}


# ---------------------------------------------------------------- signature envelopes (section 5)
_RSA_OID = bytes.fromhex("2a864886f70d010101")
SIGN_DOMAIN = "timestamped.io/v1/envelope-sign"
NOTARIZE_DOMAIN = "timestamped.io/v1/envelope-notarize"


def _der(data: bytes, pos: int):
    tag, n = data[pos], data[pos + 1]; pos += 2
    if n & 0x80:
        k = n & 0x7F; n = int.from_bytes(data[pos:pos + k], "big"); pos += k
    return tag, data[pos:pos + n], pos + n


def rsa_public_key(pem: str):
    """(n, e, SubjectPublicKeyInfo DER) of an RSA key in "BEGIN PUBLIC KEY" PEM, the form browsers export."""
    lines = [l.strip() for l in pem.strip().splitlines() if l.strip()]
    if lines[0] != "-----BEGIN PUBLIC KEY-----" or lines[-1] != "-----END PUBLIC KEY-----":
        raise ValueError("expected a PEM SubjectPublicKeyInfo (BEGIN PUBLIC KEY)")
    der = base64.b64decode("".join(lines[1:-1]))
    _, spki, _ = _der(der, 0)
    _, algorithm, pos = _der(spki, 0)
    _, oid, _ = _der(algorithm, 0)
    if oid != _RSA_OID:
        raise ValueError("not an RSA public key")
    tag, bits, _ = _der(spki, pos)
    if tag != 0x03 or bits[0] != 0:
        raise ValueError("malformed public key")
    _, rsa_key, _ = _der(bits[1:], 0)
    _, n, pos = _der(rsa_key, 0)
    _, e, _ = _der(rsa_key, pos)
    return int.from_bytes(n, "big"), int.from_bytes(e, "big"), der


def _mgf1(seed: bytes, length: int) -> bytes:
    out = b""
    for counter in range((length + 31) // 32):
        out += sha256(seed + counter.to_bytes(4, "big"))
    return out[:length]


def rsa_pss_verify(pem: str, signature_hex: str, message: bytes, salt_len: int = 32) -> bool:
    """RSASSA-PSS with SHA-256, MGF1-SHA-256 and a 32-byte salt (RFC 8017 section 8.1.2), as the envelope signers use."""
    try:
        n, e, _ = rsa_public_key(pem)
        sig = bytes.fromhex(signature_hex)
    except (ValueError, IndexError, TypeError):
        return False
    k = (n.bit_length() + 7) // 8
    s = int.from_bytes(sig, "big")
    if len(sig) != k or s >= n:
        return False
    em_bits = n.bit_length() - 1
    em_len = (em_bits + 7) // 8
    m = pow(s, e, n)
    if m >> (8 * em_len):
        return False
    em = m.to_bytes(em_len, "big")
    if em_len < 32 + salt_len + 2 or em[-1] != 0xBC:
        return False
    masked, h = em[:em_len - 33], em[em_len - 33:-1]
    zero_bits = 8 * em_len - em_bits
    if masked[0] & ~(0xFF >> zero_bits) & 0xFF:
        return False
    db = bytes(a ^ b for a, b in zip(masked, _mgf1(h, len(masked))))
    db = bytes([db[0] & (0xFF >> zero_bits)]) + db[1:]
    ps_len = em_len - 32 - salt_len - 2
    if db[:ps_len] != b"\x00" * ps_len or db[ps_len] != 1:
        return False
    return sha256(b"\x00" * 8 + sha256(message) + db[-salt_len:]) == h


def pubkey_fingerprint(pem: str) -> str:
    return sha256(rsa_public_key(pem)[2]).hex()[:16]


def signer_message(envelope_id: str, file_hash: str, slot: int) -> str:
    return f"{SIGN_DOMAIN}\nenvelope_id:{envelope_id}\nfile_hash:{file_hash}\nslot:{slot}\n"


def notary_message(envelope_id: str, file_hash: str, signers) -> str:
    lines = [NOTARIZE_DOMAIN, f"envelope_id:{envelope_id}", f"file_hash:{file_hash}"]
    for s in signers:
        lines += [f"signer_{s['slot']}_pubkey_fpr:{pubkey_fingerprint(s['public_key_pem'])}", f"signer_{s['slot']}_txid:{s['txid']}"]
    return "\n".join(lines) + "\n"


def verify_envelope_signatures(cert: dict) -> list:
    """Offline checks of an envelope certificate: every signature and canonical message. Returns [(check, ok)]."""
    eid, fh = cert["id"], cert["file_hash"]
    signers = sorted(cert["signers"], key=lambda s: s["slot"])
    out = []
    for s in signers:
        msg = signer_message(eid, fh, s["slot"])
        out.append((f"signer {s['slot']} message is the canonical one", s.get("canonical_message") == msg))
        out.append((f"signer {s['slot']} signature (RSA-PSS)", bool(s.get("signature_hex")) and rsa_pss_verify(s.get("public_key_pem") or "", s["signature_hex"], msg.encode())))
    if cert.get("notary_signature_hex"):
        # A notary signature over fewer than two signed, anchored signers says nothing the spec promises (5.5).
        complete = [s.get("slot") for s in signers] == [1, 2] and all(
            s.get("txid") and s.get("signature_hex") and s.get("public_key_pem") for s in signers)
        out.append(("both signers are present, signed and anchored", complete))
        try:
            msg = notary_message(eid, fh, signers)
        except (ValueError, IndexError, TypeError, KeyError):
            msg = None
        out.append(("notary message binds both signers' keys and txids", msg is not None and cert.get("notary_canonical_message") == msg))
        out.append(("notary signature (RSA-PSS)", msg is not None and rsa_pss_verify(cert.get("notary_public_key_pem") or "", cert["notary_signature_hex"], msg.encode())))
    return out


def envelope_anchors(cert: dict) -> list:
    """(role, txid) of every on-chain anchor in a certificate."""
    anchors = [(f"signer_{s['slot']}", s["txid"]) for s in sorted(cert["signers"], key=lambda s: s["slot"]) if s.get("txid")]
    if cert.get("notary_txid"):
        anchors.append(("notary", cert["notary_txid"]))
    return anchors


def verify_envelope_anchor(raw_tx_hex: str, cert: dict, role: str) -> bool:
    """The anchor commits to the document hash, in Public mode, tagged with this envelope id and role."""
    return verify_public(raw_tx_hex, cert["file_hash"]) and \
        public_metadata(raw_tx_hex, cert["file_hash"]) == {"envelope_id": cert["id"], "envelope_role": role}


# ---------------------------------------------------------------- agent records, Merkle batches, streams (section 10)
RECORD_MAGIC = b"timestamped.io/record"
METADATA_DOMAIN = b"timestamped.io/metadata/1.0"


def _hex32(h):
    if h is None:
        return b"\x00" * 32
    b = bytes.fromhex(h)
    if len(b) != 32:
        raise ValueError("expected a 32-byte hash")
    return b


def receipt_digest(record: dict) -> str:
    """SHA-256 of the record bytes (section 10.1)."""
    sid = (record.get("stream_id") or "").encode()
    if len(sid) > 64:
        raise ValueError("stream_id is longer than 64 bytes")
    raw = (RECORD_MAGIC + b"1.0" + _hex32(record["nonce"]) + _hex32(record["file_hash"])
           + _hex32(record.get("metadata_commitment")) + bytes([len(sid)]) + sid
           + int(record.get("sequence") or 0).to_bytes(8, "big") + _hex32(record.get("prev_digest")))
    return sha256(raw).hex()


def batch_root(index: int, size: int, digest_hex: str, path) -> str:
    """Root of an RFC 9162 Merkle tree from one leaf and its audit path (leaf level first), by recursive split."""
    if not 0 <= index < size:
        raise ValueError("leaf index out of range")
    leaf = sha256(b"\x00" + bytes.fromhex(digest_hex))
    path = [_hex32(p) for p in path]

    def up(i, n, path):
        if n == 1:
            if path:
                raise ValueError("the audit path is too long")
            return leaf
        if not path:
            raise ValueError("the audit path is too short")
        k = 1
        while k * 2 < n:
            k *= 2
        if i < k:
            return sha256(b"\x01" + up(i, k, path[:-1]) + path[-1])
        return sha256(b"\x01" + path[-1] + up(i - k, n - k, path[:-1]))
    return up(index, size, path).hex()


def check_receipt(receipt: dict) -> list:
    """Offline checks of a receipt (section 10.6 steps 1-3 before the chain). Returns [(check, ok)] and the anchored hash."""
    if receipt.get("format") != "timestamped.io/receipt" or receipt.get("version") != "1.0":
        raise ValueError("not a timestamped.io/receipt 1.0")
    rec, anchor = receipt["record"], receipt["anchor"]
    out = [("the record bytes hash to the digest", receipt_digest(rec) == receipt["digest"])]
    meta = receipt.get("metadata")
    if meta is not None:
        c = sha256(METADATA_DOMAIN + bytes.fromhex(meta["salt"]) + meta["json"].encode("utf-8")).hex()
        out.append(("the metadata matches the record's commitment", c == rec.get("metadata_commitment")))
    if anchor["method"] == "merkle":
        m = anchor["merkle"]
        try:
            ok = batch_root(m["index"], m["size"], receipt["digest"], m["path"]) == m["root"]
        except (ValueError, TypeError):
            ok = False
        out.append((f"the digest is leaf {m['index']} of a batch of {m['size']} with this root", ok))
        anchored = m["root"]
    elif anchor["method"] == "single":
        anchored = receipt["digest"]
    else:
        raise ValueError(f"unknown anchor method {anchor['method']!r}")
    return out, anchored


ISSUE_DOMAIN = "timestamped.io/v1/receipt-issue"


def issuer_key_matches(receipt: dict, key_pem: str) -> bool:
    """Whether this public key is the one the receipt says signed it (keys are replaced over time)."""
    try:
        return pubkey_fingerprint(key_pem) == receipt["issuer"].get("key_id")
    except (ValueError, IndexError, TypeError):
        return False


def check_issuer(receipt: dict, anchored: str, key_pem: str) -> list:
    """Section 10.8: the service's signature over the account tag and the anchored commitment, with the key
    the receipt names. Returns [(check, ok)]."""
    issuer = receipt["issuer"]
    message = f"{ISSUE_DOMAIN}\naccount:{issuer.get('account')}\ncommitment:{anchored}\n".encode()
    return [("issued by the holder of the given key for this account (RSA-PSS)",
             issuer_key_matches(receipt, key_pem) and rsa_pss_verify(key_pem, issuer.get("signature") or "", message))]


def anchor_matches(raw_tx_hex: str, receipt: dict, anchored: str) -> bool:
    """The anchor is a Public-mode stamp of the digest or root, tagged as section 10.4 says (with the batch size n)."""
    if not verify_public(raw_tx_hex, anchored):
        return False
    meta = public_metadata(raw_tx_hex, anchored) or {}
    if receipt["anchor"]["method"] == "merkle":
        return meta == {"t": "batch", "v": "1.0", "n": receipt["anchor"]["merkle"]["size"]}
    return meta == {"t": "record", "v": "1.0"}


def check_chain(receipts: list) -> list:
    """Links of a stream (section 10.7): one stream id, sequence 1, 2, 3 …, each prev_digest = the previous digest."""
    recs = sorted(receipts, key=lambda r: r["record"].get("sequence") or 0)
    out = []
    ids = {r["record"].get("stream_id") for r in recs}
    out.append((f"all receipts are in one stream ({', '.join(map(str, ids))})", len(ids) == 1 and None not in ids))
    expect_seq, prev = recs[0]["record"]["sequence"] if recs else 1, None
    if expect_seq != 1:
        out.append((f"these receipts start at sequence {expect_seq}; records before it are not checked", True))
        prev = recs[0]["record"]["prev_digest"]
    for r in recs:
        seq = r["record"]["sequence"]
        out.append((f"sequence {seq} follows {expect_seq - 1}", seq == expect_seq))
        out.append((f"sequence {seq} links to the previous digest", r["record"].get("prev_digest") == prev))
        prev, expect_seq = r["digest"], seq + 1
    return out


# ---------------------------------------------------------------- evidence: from a folder, or from public explorers
# A folder holds, per transaction: <txid>.rawtx.hex, <txid>.proof.json (TSC or BUMP JSON, or a BUMP in hex)
# and <txid>.header.hex (the 80-byte header of the block the proof points at). Any source can supply them.
def _get(url: str) -> str:
    req = urllib.request.Request(url, headers={"User-Agent": "timestamped-verify/1.1"})
    with urllib.request.urlopen(req, timeout=20) as r:
        return r.read().decode().strip()


def fetch_raw_tx(txid: str) -> str:
    for url in (f"https://api.bitails.io/download/tx/{txid}/hex",
                f"https://api.whatsonchain.com/v1/bsv/main/tx/{txid}/hex"):
        try:
            body = _get(url)
            if body and all(c in "0123456789abcdefABCDEF" for c in body):
                return body
        except Exception:
            continue
    raise SystemExit(f"could not fetch raw transaction {txid} from any explorer")


def fetch_merkle_proof(txid: str):
    """TSC proof from a public explorer, or None. Sets fetch_merkle_proof.why to the reason for None."""
    reasons = []
    for url in (f"https://api.bitails.io/tx/{txid}/proof/tsc",
                f"https://api.whatsonchain.com/v1/bsv/main/tx/{txid}/proof/tsc"):
        try:
            proof = json.loads(_get(url))
            proof = proof[0] if isinstance(proof, list) and proof else proof
            if isinstance(proof, dict) and "nodes" in proof:
                proof.pop("__meta", None)
                return proof
            reasons.append("none")
        except urllib.error.HTTPError as exc:
            reasons.append("none" if exc.code == 404 else f"HTTP {exc.code}")
        except Exception as exc:
            reasons.append(exc.__class__.__name__)
    fetch_merkle_proof.why = ("the explorers have no Merkle proof (the transaction may not be mined yet)"
                              if all(r == "none" for r in reasons) else
                              f"could not get a Merkle proof from the explorers ({', '.join(reasons)}); try again later")
    return None


def fetch_header(block_hash: str):
    try:
        header = json.loads(_get(f"https://api.bitails.io/block/{block_hash}/header"))["header"]
        return header if len(header) == 160 else None
    except Exception:
        return None


def _read(path):
    try:
        with open(path) as f:
            return f.read().strip()
    except FileNotFoundError:
        return None


def _load_proof(text):
    if text is None:
        return None
    text = text.strip()
    if not text.startswith(("{", "[")):
        return text  # BUMP, binary encoding in hex
    proof = json.loads(text)
    proof = proof[0] if isinstance(proof, list) and proof else proof
    if isinstance(proof, dict) and "raw_transaction_hex" in proof:
        proof = proof.get("merkle_proof")  # a saved GET /v1/proof/{txid} response
    return proof


def gather(txid: str, evidence=None, offline=False) -> dict:
    """Raw tx, Merkle proof and header for txid: from the evidence folder first, then (unless offline) from explorers."""
    path = lambda kind: os.path.join(evidence, f"{txid}.{kind}") if evidence else None
    note = None
    raw = _read(path("rawtx.hex")) if evidence else None
    proof = _load_proof(_read(path("proof.json"))) if evidence else None
    header = _read(path("header.hex")) if evidence else None
    if not offline:
        if raw is None:
            raw = fetch_raw_tx(txid)
        if proof is None:
            proof = fetch_merkle_proof(txid)
            if proof is None:
                note = getattr(fetch_merkle_proof, "why", None)
        if header is None and isinstance(proof, dict) and proof.get("targetType", "hash") == "hash" and _is_hash_hex(proof.get("target")):
            header = fetch_header(proof["target"])
    if raw is None:
        raise SystemExit(f"no raw transaction for {txid} in {evidence} (and --offline)")
    return {"raw": raw, "proof": proof, "header": header, "note": note}


def save_evidence(txid: str, out_dir: str) -> dict:
    """Download everything needed to verify txid later without any network access."""
    os.makedirs(out_dir, exist_ok=True)
    ev = gather(txid)
    if not check_txid(ev["raw"], txid):
        raise SystemExit(f"the explorer returned a transaction whose id is not {txid}")
    files = {"rawtx.hex": ev["raw"]}
    if ev["proof"] is not None:
        files["proof.json"] = json.dumps(ev["proof"], indent=1)
    if ev["header"] is not None:
        files["header.hex"] = ev["header"]
    for kind, body in files.items():
        with open(os.path.join(out_dir, f"{txid}.{kind}"), "w") as f:
            f.write(body + "\n")
    return files


def inclusion_status(txid: str, ev: dict, min_difficulty: float = MIN_DIFFICULTY):
    """(True, details) when proven, (False, reason) when the evidence contradicts, (None, reason) when it is missing."""
    if ev["proof"] is None:
        return None, ev.get("note") or "no Merkle proof (the transaction may not be mined yet)"
    if ev["header"] is None:
        return None, "no block header for the block the Merkle proof points at"
    if len(bytes.fromhex(ev["raw"])) == 64:
        return False, "a 64-byte transaction is ambiguous with a Merkle tree node"
    try:
        return True, verify_inclusion(txid, ev["proof"], ev["header"], min_difficulty)
    except (ValueError, KeyError, IndexError, TypeError) as exc:
        return False, str(exc)


def _block_line(info: dict) -> str:
    when = datetime.datetime.fromtimestamp(info["block_time"], datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
    height = f" (height {info['block_height']} as stated by the BUMP)" if info["block_height"] is not None else ""
    return f"  in block {info['block_hash']}{height}, block time {when}"


TRUST_NOTE = ("  The block time is set by the miner (within about two hours). Check that this block hash is on the\n"
              "  main chain with a header source you trust: your own node, or any explorer.")


def main(argv=None) -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    sub = p.add_subparsers(dest="mode", required=True)
    common = argparse.ArgumentParser(add_help=False)
    common.add_argument("--evidence", help="folder with <txid>.rawtx.hex, <txid>.proof.json, <txid>.header.hex")
    common.add_argument("--offline", action="store_true", help="use only --evidence; never touch the network")
    common.add_argument("--min-difficulty", type=float, default=MIN_DIFFICULTY,
                        help=f"lowest block difficulty accepted (default {MIN_DIFFICULTY:.0e})")
    a = sub.add_parser("public", parents=[common]); a.add_argument("--hash", required=True); a.add_argument("--txid", required=True)
    b = sub.add_parser("private", parents=[common]); b.add_argument("--proof", required=True); b.add_argument("--txid", required=True)
    b.add_argument("--hash", help="SHA-256 of your file; checked against the hash inside the proof blob")
    b.add_argument("--file", help="your file; hashed locally and checked against the proof blob")
    c = sub.add_parser("legacy", parents=[common]); c.add_argument("--hash", required=True); c.add_argument("--txid", required=True)
    d = sub.add_parser("url", parents=[common]); d.add_argument("--proof-package", required=True); d.add_argument("--screenshot", required=True)
    d.add_argument("--text", help="the page's visible text, if you have it; otherwise its hash is taken from the package")
    e = sub.add_parser("envelope", parents=[common]); e.add_argument("--certificate", required=True)
    e.add_argument("--file", help="the signed document; hashed locally and checked against the certificate")
    r = sub.add_parser("receipt", parents=[common], help="one or more agent-record receipts; several from one stream are also checked as a chain")
    r.add_argument("--receipt", required=True, action="append")
    r.add_argument("--file", help="the recorded document; hashed locally and checked against a single receipt")
    r.add_argument("--issuer-key", help="PEM file with the service's receipt-signing public key; without it service signatures are not checked")
    r.add_argument("--account", help="the account tag you expect in service-signed receipts (issuer.account)")
    f = sub.add_parser("fetch", help="save the evidence for txids, to verify later with --offline")
    f.add_argument("--txid", required=True, action="append"); f.add_argument("--out", required=True)
    args = p.parse_args(argv)
    try:
        return _run(args)
    except SystemExit:
        raise
    except Exception as exc:  # malformed input or explorer data: a verdict, never a traceback
        print(f"INVALID: could not verify ({exc.__class__.__name__}: {exc})")
        return 1


def _check_claim(args, txid: str, raw: str, package=None):
    """(ok, message) for what the transaction commits to; message is printed on failure, or extra lines on success."""
    if args.mode == "url":
        with open(args.screenshot, "rb") as f: shot = f.read()
        text = None
        if args.text:
            with open(args.text, "rb") as f: text = f.read()
        return verify_url_package(package, shot, text, raw), "the transaction does not commit to this claim"
    if args.mode == "private":
        try:
            info = parse_proof_blob(bytes.fromhex(args.proof))
        except (ValueError, IndexError):
            return False, "the proof blob is not a timestamped.io/silent proof"
        claimed = args.hash.lower() if args.hash else None
        if args.file:
            with open(args.file, "rb") as f: claimed = hashlib.sha256(f.read()).hexdigest()
        if claimed and claimed != info["file_hash"]:
            return False, f"the proof blob commits to {info['file_hash']}, not to {claimed}"
        if not verify_private(raw, args.proof):
            return False, "the transaction does not commit to this claim"
        extra = f"  file hash (from the proof): {info['file_hash']}\n  notes: {info['notes'] or '(none)'}"
        if not claimed:
            extra += "\n  (pass --hash or --file to check that this is the hash of your document)"
        return True, extra
    ok = {"public": verify_public, "legacy": verify_legacy}[args.mode](raw, args.hash)
    return ok, "the transaction does not commit to this claim"


def _verify_tx(args, txid: str, check) -> tuple:
    """Run one transaction through the claim check and the inclusion check. Returns (exit code, lines)."""
    ev = gather(txid, args.evidence, args.offline)
    if not check_txid(ev["raw"], txid):
        return 1, [f"INVALID: the raw transaction's id is not {txid}"]
    ok, msg = check(ev["raw"])
    if not ok:
        return 1, [f"INVALID: {msg}"]
    extra = [msg] if msg and ok is True and msg.startswith("  ") else []
    proven, info = inclusion_status(txid, ev, args.min_difficulty)
    if proven is False:
        return 1, [f"INVALID: the transaction commits to the claim, but its block proof fails: {info}"]
    if proven is None:
        return 2, [f"UNCONFIRMED: the transaction commits to the claim, but its inclusion in a block is not proven: {info}"] + extra
    return 0, ["VALID", _block_line(info)] + extra


def _run(args) -> int:
    if args.mode == "fetch":
        for txid in args.txid:
            files = save_evidence(txid.lower(), args.out)
            missing = {"proof.json", "header.hex"} - set(files)
            print(f"{txid}: saved {', '.join(sorted(files))}" + (f"; missing {', '.join(sorted(missing))} (not mined yet?)" if missing else ""))
        return 0
    if args.mode == "envelope":
        return _run_envelope(args)
    if args.mode == "receipt":
        return _run_receipts(args)
    package = None
    if args.mode == "url":
        with open(args.proof_package) as f: package = json.load(f)
        txid = package["blockchain"]["txid"]
    else:
        txid = args.txid
    code, lines = _verify_tx(args, txid.strip().lower(), lambda raw: _check_claim(args, txid, raw, package))
    print("\n".join(lines))
    if code == 0:
        print(TRUST_NOTE)
    return code


def _run_receipts(args) -> int:
    receipts = []
    for path in args.receipt:
        with open(path) as f: receipts.append(json.load(f))
    results, code = [], 0
    issuer_key, unchecked = None, set()
    if args.issuer_key:
        with open(args.issuer_key) as f: issuer_key = f.read()
    if args.file:
        if len(receipts) != 1:
            print("INVALID: --file needs exactly one --receipt"); return 1
        with open(args.file, "rb") as f:
            results.append(("the document matches the receipt's file hash", hashlib.sha256(f.read()).hexdigest() == receipts[0]["record"]["file_hash"]))
    for rc in receipts:
        label = f"seq {rc['record']['sequence']}" if rc["record"].get("stream_id") else rc["digest"][:16]
        checks, anchored = check_receipt(rc)
        results += [(f"{label}: {c}", ok) for c, ok in checks]
        if not all(ok for _, ok in checks):
            continue
        if "issuer" in rc:
            # The verifier never contacts timestamped.io: the signing key comes from the caller. A receipt
            # signed with another key (keys are replaced over time) is left unchecked, not called invalid.
            if issuer_key and issuer_key_matches(rc, issuer_key):
                results += [(f"{label}: {c}", ok) for c, ok in check_issuer(rc, anchored, issuer_key)]
            else:
                unchecked.add(rc["issuer"].get("key_id"))
            if args.account:
                results.append((f"{label}: issued for the account you named", rc["issuer"].get("account") == args.account))
        txid = rc["anchor"].get("txid")
        if not txid:
            results.append((f"{label}: not anchored yet (no txid)", None)); continue
        c, lines = _verify_tx(args, txid.lower(), lambda raw, r=rc, h=anchored: (anchor_matches(raw, r, h), "the transaction does not anchor this receipt"))
        results.append((f"{label}: anchor {txid}: {lines[0]}" + ("" if c else "\n" + lines[1]), True if c == 0 else (False if c == 1 else None)))
    if len(receipts) > 1:
        results += [(f"chain: {c}", ok) for c, ok in check_chain(receipts)]
        accounts = {rc["issuer"].get("account") for rc in receipts if "issuer" in rc}
        if accounts and all(rc["record"].get("stream_id") for rc in receipts):
            results.append(("chain: every service-signed receipt is for the same account", len(accounts) == 1))
    for check, ok in results:
        print(f"  [{ {True: 'ok', False: '--', None: '..'}[ok] }] {check}")
    if any(ok is False for _, ok in results):
        code = 1
    elif any(ok is None for _, ok in results):
        code = 2
    print({0: "VALID", 1: "INVALID: see the failed checks above", 2: "UNCONFIRMED: an anchor is missing or not proven in a block"}[code])
    if unchecked:
        print(f"  Service signatures made with key {', '.join(sorted(str(k) for k in unchecked))} were not checked: pass that public key\n"
              "  with --issuer-key <pem file> (https://timestamped.io/api/v1/receipt-key serves the current one).")
    unsigned = sum(1 for rc in receipts if "issuer" not in rc)
    if unsigned:
        print(f"  {unsigned} of {len(receipts)} receipt(s) carry no service signature: they show that the content existed by the\n"
              "  block time, not that timestamped.io issued them (anyone can anchor a record in this format).")
    if any(r["record"].get("stream_id") for r in receipts):
        print("  Records removed from the end of a stream cannot be detected from these receipts alone; compare\n"
              "  with the latest sequence number you hold.")
    if code == 0:
        print(TRUST_NOTE)
    return code


def _run_envelope(args) -> int:
    with open(args.certificate) as f: cert = json.load(f)
    results = []
    if args.file:
        with open(args.file, "rb") as f: results.append(("the document matches the certificate's file hash", hashlib.sha256(f.read()).hexdigest() == cert["file_hash"]))
    results += verify_envelope_signatures(cert)
    code = 0 if all(ok for _, ok in results) else 1
    for role, txid in envelope_anchors(cert):
        c, lines = _verify_tx(args, txid.lower(), lambda raw, role=role: (verify_envelope_anchor(raw, cert, role), f"the transaction does not anchor this envelope as {role}"))
        results.append((f"{role} anchor {txid}: {lines[0]}" + ("" if c else "\n" + lines[1]), c == 0))
        code = 1 if 1 in (code, c) else max(code, c)
    notarized = bool(cert.get("notary_signature_hex") and cert.get("notary_txid"))
    if not notarized and code == 0:
        code = 2
    for check, ok in results:
        print(f"  [{'ok' if ok else '--'}] {check}")
    verdict = {0: "VALID", 1: "INVALID: see the failed checks above",
               2: "UNCONFIRMED: an anchor's inclusion in a block is not proven" if notarized else
                  "INCOMPLETE: the envelope is not notarized; the checks above cover what exists so far"}[code]
    print(verdict)
    print("  The signatures and the chain prove which keys signed this document hash, and that the notary signed\n"
          "  after both signer anchors existed. Names, emails and how each signer authenticated are statements by\n"
          "  timestamped.io; nothing here proves who held the keys.")
    if code == 0:
        print(TRUST_NOTE)
    return code


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