#!/usr/bin/env python3
"""Independently verify an OpenTimestamps (.ots) proof anchored on the Bitmark blockchain.

Usage:
    python3 verify_ots.py <file> <file.ots> [--explorer]

What it does (standard library only, no third-party code):
  1. Computes the SHA-256 of <file> and checks it matches the digest inside the proof.
  2. Replays every operation in the proof (appends, prepends, hashes) from that digest.
  3. For each Bitmark block attestation, prints the block height and the Merkle root the
     proof commits to, plus the bitmark-cli commands to check it against your own node.
  4. With --explorer, also fetches that block from explorer.bitmark.cc and compares.

A proof is valid when the Merkle root computed from your file equals the Merkle root in
the header of the attested Bitmark block.
"""
import hashlib, io, re, sys, urllib.request

MAGIC = b'\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94'
PENDING, BLOCK = bytes.fromhex('83dfe30d2ef90c8e'), bytes.fromhex('0588960d73d71901')
UNARY = {0x08: lambda m: hashlib.sha256(m).digest(), 0x02: lambda m: hashlib.sha1(m).digest(),
         0x03: lambda m: hashlib.new('ripemd160', m).digest(), 0xf2: lambda m: m[::-1],
         0xf3: lambda m: m.hex().encode()}

def varuint(f):
    v = s = 0
    while True:
        b = f.read(1)[0]; v |= (b & 0x7f) << s; s += 7
        if not b & 0x80: return v

def varbytes(f):
    n = varuint(f); d = f.read(n)
    if len(d) != n: raise ValueError('truncated proof')
    return d

def walk(f, msg, results):
    """Replay the proof tree from msg, collecting (attestation_tag, payload, committed_msg)."""
    def one(tag):
        if tag == 0x00:
            results.append((f.read(8), varbytes(f), msg))
        elif tag in UNARY:
            walk(f, UNARY[tag](msg), results)
        elif tag in (0xf0, 0xf1):
            arg = varbytes(f)
            walk(f, msg + arg if tag == 0xf0 else arg + msg, results)
        else:
            raise ValueError('unknown operation 0x%02x' % tag)
    tag = f.read(1)[0]
    while tag == 0xff:
        one(f.read(1)[0]); tag = f.read(1)[0]
    one(tag)

def explorer_merkle_root(height):
    url = 'https://explorer.bitmark.cc/?q=%d' % height
    req = urllib.request.Request(url, headers={'User-Agent': 'verify_ots/1.0'})
    html = urllib.request.urlopen(req, timeout=30).read().decode('utf-8', 'replace')
    text = re.sub(r'<[^>]+>', '\n', html)
    lines = [l.strip() for l in text.splitlines() if l.strip()]
    root = lines[lines.index('Merkle Root') + 1]
    bhash = lines[lines.index('Hash') + 1]
    btime = lines[lines.index('Time') + 1]
    return root, bhash, btime

def main():
    args = [a for a in sys.argv[1:] if not a.startswith('--')]
    if len(args) != 2:
        print(__doc__); return 2
    data_path, ots_path = args
    digest = hashlib.sha256(open(data_path, 'rb').read()).digest()
    f = io.BytesIO(open(ots_path, 'rb').read())
    if f.read(len(MAGIC)) != MAGIC: raise SystemExit('Not an OpenTimestamps proof.')
    if varuint(f) != 1 or f.read(1) != b'\x08': raise SystemExit('Unsupported proof version or hash.')
    proof_digest = f.read(32)
    print('File SHA-256 :', digest.hex())
    print('Proof digest :', proof_digest.hex())
    if digest != proof_digest:
        print('RESULT: FAIL, this proof is for a different file.'); return 1
    results = []
    walk(f, digest, results)
    ok = False
    for tag, payload, msg in results:
        p = io.BytesIO(payload)
        if tag == PENDING:
            print('\nPending attestation at calendar', varbytes(p).decode(), '(not yet anchored in this copy)')
        elif tag == BLOCK:
            height = varuint(p)
            root = msg[::-1].hex()   # block explorers display the Merkle root byte-reversed
            print('\nBitmark block attestation')
            print('  Block height        :', height)
            print('  Merkle root (proof) :', root)
            print('  Check with your own node:')
            print('    bitmark-cli getblock $(bitmark-cli getblockhash %d) | grep merkleroot' % height)
            if '--explorer' in sys.argv:
                try:
                    eroot, bhash, btime = explorer_merkle_root(height)
                    print('  Explorer block hash :', bhash)
                    print('  Explorer block time :', btime)
                    print('  Merkle root (block) :', eroot)
                    match = eroot.lower() == root
                    print('  MATCH' if match else '  MISMATCH')
                    ok = ok or match
                except Exception as e:
                    print('  (explorer lookup failed: %s)' % e)
        else:
            print('\nUnknown attestation type', tag.hex())
    if '--explorer' in sys.argv:
        print('\nRESULT:', 'VALID, the file is anchored in the Bitmark blockchain.' if ok else 'NOT CONFIRMED by explorer lookup.')
    return 0 if ok or '--explorer' not in sys.argv else 1

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