#!/usr/bin/env python3
"""Verify the preserved 0.bitmap transaction and its block commitments.

Standard library only. A commitment proof authenticates bytes against a block
header; it does not independently validate the entire Bitcoin header chain.
"""
from __future__ import annotations
import hashlib
import json
from pathlib import Path
from typing import Any

ROOT = Path(__file__).resolve().parents[1]

def hash256(value: bytes) -> bytes:
    return hashlib.sha256(hashlib.sha256(value).digest()).digest()

def compact(data: bytes, pos: int) -> tuple[int, int]:
    if pos >= len(data): raise ValueError('Truncated CompactSize')
    tag = data[pos]; pos += 1
    size = {253: 2, 254: 4, 255: 8}.get(tag, 0)
    if not size: return tag, pos
    if pos + size > len(data): raise ValueError('Truncated CompactSize value')
    value = int.from_bytes(data[pos:pos + size], 'little')
    if value < {2:253, 4:65536, 8:4294967296}[size]: raise ValueError('Noncanonical CompactSize')
    return value, pos + size

def transaction(data: bytes, start: int = 0) -> tuple[dict[str, Any], int]:
    pos = start + 4
    if len(data) < pos + 2: raise ValueError('Truncated transaction')
    witness = data[pos:pos+2] == b'\x00\x01'
    if witness: pos += 2
    body_start = pos
    inputs, pos = compact(data, pos)
    scripts = []
    for _ in range(inputs):
        pos += 36
        length, pos = compact(data, pos)
        scripts.append(data[pos:pos+length]); pos += length + 4
    outputs, pos = compact(data, pos)
    output_scripts = []
    for _ in range(outputs):
        pos += 8
        length, pos = compact(data, pos)
        output_scripts.append(data[pos:pos+length]); pos += length
    body_end = pos
    witnesses = []
    if witness:
        for _ in range(inputs):
            count, pos = compact(data, pos)
            items = []
            for _ in range(count):
                length, pos = compact(data, pos)
                items.append(data[pos:pos+length]); pos += length
            witnesses.append(items)
    end = pos + 4
    if end > len(data): raise ValueError('Truncated transaction body')
    raw = data[start:end]
    stripped = data[start:start+4] + data[body_start:body_end] + data[pos:end]
    return {'raw':raw, 'txid':hash256(stripped), 'wtxid':hash256(raw), 'scripts':scripts,
            'outputs':output_scripts, 'witnesses':witnesses}, end

def merkle_path(digest: bytes, index: int, siblings: list[str]) -> bytes:
    for value in siblings:
        sibling = bytes.fromhex(value)
        if len(sibling) != 32: raise ValueError('Merkle sibling must be 32 bytes')
        digest = hash256(sibling + digest if index & 1 else digest + sibling)
        index >>= 1
    if index: raise ValueError('Incomplete Merkle proof')
    return digest

def require(condition: bool, message: str) -> None:
    if not condition: raise ValueError(message)

def verify(proof: dict[str, Any]) -> dict[str, Any]:
    header = bytes.fromhex(proof['header_hex'])
    require(len(header) == 80, 'Invalid block header length')
    block_hash = hash256(header)[::-1].hex()
    require(block_hash == proof['block_hash'], 'Header hash mismatch')
    bits = int.from_bytes(header[72:76], 'little')
    exponent, coefficient = bits >> 24, bits & 0x007fffff
    require(not bits & 0x00800000, 'Negative target')
    target = coefficient << (8*(exponent-3)) if exponent >= 3 else coefficient >> (8*(3-exponent))
    require(0 < int.from_bytes(hash256(header), 'little') <= target, 'Header proof of work mismatch')
    raw = bytes.fromhex(proof['reveal_hex']); reveal, end = transaction(raw)
    require(end == len(raw), 'Trailing reveal bytes')
    require(reveal['txid'][::-1].hex() == proof['inscription_id'].split('i')[0], 'Reveal txid mismatch')
    require(merkle_path(reveal['txid'], proof['transaction_index'], proof['transaction_branch']) == header[36:68], 'Transaction inclusion mismatch')
    coinbase_raw = bytes.fromhex(proof['coinbase_hex']); coinbase, end = transaction(coinbase_raw)
    require(end == len(coinbase_raw), 'Trailing coinbase bytes')
    require(merkle_path(coinbase['txid'], 0, proof['coinbase_branch']) == header[36:68], 'Coinbase inclusion mismatch')
    script = coinbase['scripts'][0]
    require(int.from_bytes(script[1:1+script[0]], 'little') == proof['height'], 'Coinbase height mismatch')
    reserved = coinbase['witnesses'][0][0]
    require(len(reserved) == 32, 'Invalid witness reserved value')
    witness_root = merkle_path(reveal['wtxid'], proof['transaction_index'], proof['witness_branch'])
    commitments = [script[6:38] for script in coinbase['outputs'] if len(script) >= 38 and script.startswith(bytes.fromhex('6a24aa21a9ed'))]
    require(commitments and hash256(witness_root + reserved) == commitments[-1], 'Witness commitment mismatch')
    envelope = bytes.fromhex('0063036f7264010118746578742f706c61696e3b636861727365743d7574662d380008') + b'0.bitmap' + b'\x68'
    require(len(reveal['witnesses']) == 1 and envelope in reveal['witnesses'][0][-2], 'Expected inscription envelope missing')
    require(proof['content'] == '0.bitmap', 'Content metadata mismatch')
    return {'block_hash':block_hash, 'height':proof['height'], 'transaction_index':proof['transaction_index'],
            'txid':reveal['txid'][::-1].hex(), 'content':proof['content'],
            'verified':['header hash and target', 'coinbase height', 'reveal txid', 'transaction Merkle path', 'coinbase Merkle path', 'witness commitment', 'inscription envelope']}

if __name__ == '__main__':
    import argparse
    default = ROOT/'public/records/bitmap/0-bitmap-proof.json'
    if not default.exists(): default = Path(__file__).with_name('0-bitmap-proof.json')
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('proof', nargs='?', type=Path, default=default)
    proof = json.loads(parser.parse_args().proof.read_text())
    print(json.dumps(verify(proof), indent=2))
