#!/usr/bin/env python3
"""Reads a vault's spend and says in plain words what it does, before you send it.

    python3 read-spend.py FUND.hex LOCK.spend.hex [--expect ADDRESS] [--network main|test|regtest]

FUND.hex is the payment that funded the vault, LOCK.spend.hex the spend the PQSB
tools built. Both are public data: this never opens LOCK.json and needs no secret.

It shares no code with the tools that built the spend. It parses the two
transactions itself, so a mistake in them (a wrong address, a wrong amount, a
surprise second output) shows here. The last line of its checks runs Bitcoin
Core's own consensus code on the spend, through the verifier in the PQSB folder.

Nothing is sent anywhere. Exit status 0 means every check passed.
"""
import argparse
import hashlib
import os
import subprocess
import sys

HRP = {'main': 'bc', 'test': 'tb', 'regtest': 'bcrt'}
BASE58_VERSIONS = {'main': (0x00, 0x05), 'test': (0x6f, 0xc4), 'regtest': (0x6f, 0xc4)}
BECH32 = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'


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


# ---------------------------------------------------------------- transactions
class Reader:
    def __init__(self, raw): self.raw, self.at = raw, 0

    def take(self, n):
        if self.at + n > len(self.raw): raise ValueError('the transaction ends early')
        piece = self.raw[self.at:self.at + n]; self.at += n
        return piece

    def number(self, n): return int.from_bytes(self.take(n), 'little')

    def count(self):
        first = self.number(1)
        return first if first < 0xfd else self.number({0xfd: 2, 0xfe: 4, 0xff: 8}[first])


def parse(hex_text):
    raw = bytes.fromhex(''.join(hex_text.split()))
    r = Reader(raw)
    version = r.take(4)
    segwit = raw[4:6] == b'\x00\x01'
    if segwit: r.take(2)
    body_start = r.at
    inputs = []
    for _ in range(r.count()):
        txid = r.take(32)[::-1].hex(); vout = r.number(4)
        r.take(r.count())                                   # scriptSig
        inputs.append({'txid': txid, 'vout': vout, 'sequence': r.number(4), 'witness': []})
    outputs = []
    for _ in range(r.count()):
        at = r.at; value = r.number(8)
        outputs.append({'value': value, 'script': r.take(r.count()), 'at': at})
    body_end = r.at
    if segwit:
        for i in inputs:
            i['witness'] = [r.take(r.count()) for _ in range(r.count())]
    locktime = r.take(4)
    if r.at != len(raw): raise ValueError('there are bytes left over after the transaction')
    base = version + raw[body_start:body_end] + locktime    # the transaction without its witness
    weight = len(base) * 3 + len(raw)
    return {'inputs': inputs, 'outputs': outputs, 'txid': sha256d(base)[::-1].hex(),
            'vsize': -(-weight // 4), 'locktime': int.from_bytes(locktime, 'little')}


# ---------------------------------------------------------------- addresses
def _polymod(values):
    chk = 1
    for v in values:
        top = chk >> 25
        chk = (chk & 0x1ffffff) << 5 ^ v
        for i, g in enumerate((0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3)):
            if top >> i & 1: chk ^= g
    return chk


def segwit_address(hrp, version, program):
    acc = bits = 0; data = [version]
    for byte in program:
        acc = acc << 8 | byte; bits += 8
        while bits >= 5:
            bits -= 5; data.append(acc >> bits & 31)
    if bits: data.append(acc << (5 - bits) & 31)
    expanded = [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]
    const = 1 if version == 0 else 0x2bc830a3              # bech32, or bech32m from version 1
    mod = _polymod(expanded + data + [0] * 6) ^ const
    return hrp + '1' + ''.join(BECH32[d] for d in data + [mod >> 5 * (5 - i) & 31 for i in range(6)])


def base58_address(version, payload):
    raw = bytes([version]) + payload
    raw += sha256d(raw)[:4]
    n = int.from_bytes(raw, 'big'); text = ''
    while n: n, rem = divmod(n, 58); text = BASE58[rem] + text
    return '1' * (len(raw) - len(raw.lstrip(b'\0'))) + text


def address_of(script, network):
    s = script
    if len(s) in (22, 34) and s[0] == 0 and s[1] == len(s) - 2:
        return segwit_address(HRP[network], 0, s[2:])
    if 4 <= len(s) <= 42 and 0x51 <= s[0] <= 0x60 and s[1] == len(s) - 2:
        return segwit_address(HRP[network], s[0] - 0x50, s[2:])
    if len(s) == 25 and s[:3] == b'\x76\xa9\x14' and s[23:] == b'\x88\xac':
        return base58_address(BASE58_VERSIONS[network][0], s[3:23])
    if len(s) == 23 and s[:2] == b'\xa9\x14' and s[22:] == b'\x87':
        return base58_address(BASE58_VERSIONS[network][1], s[2:22])
    return None


def commitments(script):
    """How many 20-byte hashes the script begins with: the vault's sealed secrets."""
    n = at = 0
    while script[at:at + 1] == b'\x14' and at + 21 <= len(script): n += 1; at += 21
    return n


# ---------------------------------------------------------------- the checks
def verifier_path():
    home = os.environ.get('PQSB_HOME') or os.path.expanduser('~/Documents/GitHub/PQSB')
    path = os.path.join(home, 'pqai-btc-everything', 'implementation-app', 'verifier', 'target', 'release', 'qsb_verify')
    return path if os.access(path, os.X_OK) else None


def consensus(prev_script, amount, spend_hex):
    """True or False from Bitcoin Core's consensus library, None when the verifier is not built."""
    path = verifier_path()
    if not path: return None
    line = f'{prev_script.hex()} {amount} {spend_hex} 0\n'
    out = subprocess.run([path], input=line, capture_output=True, text=True, timeout=60).stdout.strip()
    return out == '1'


def sats(n): return f'{n:,} sat'


def main():
    p = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    p.add_argument('funding', help='the payment that funded the vault, as hex (FUND.hex)')
    p.add_argument('spend', help='the spend the PQSB tools built, as hex (LOCK.spend.hex)')
    p.add_argument('--expect', metavar='ADDRESS', help='the address the spend should pay, for example the one felt shows')
    p.add_argument('--network', choices=sorted(HRP), default='main')
    a = p.parse_args()

    spend_hex = ''.join(open(a.spend).read().split())
    try:
        fund, spend = parse(open(a.funding).read()), parse(spend_hex)
    except (ValueError, KeyError) as e:
        sys.exit(f'Could not read a transaction: {e}')

    problems = []

    def check(ok, good, bad):
        print(f'  {"ok " if ok else "NO "} {good if ok else bad}')
        if not ok: problems.append(bad)

    if len(spend['inputs']) != 1:
        sys.exit(f'This transaction spends {len(spend["inputs"])} coins. A vault spend has exactly one.')
    coin = spend['inputs'][0]
    if coin['txid'] != fund['txid'] or coin['vout'] >= len(fund['outputs']):
        sys.exit(f'The spend takes its coin from {coin["txid"]}:{coin["vout"]}, which is not in the funding file '
                 f'({fund["txid"]}). Fetch the right funding transaction and try again.')
    prev = fund['outputs'][coin['vout']]
    paid = sum(o['value'] for o in spend['outputs'])
    fee = prev['value'] - paid
    witness = coin['witness']
    script = witness[-1] if witness else b''
    is_vault = len(prev['script']) == 34 and prev['script'][:2] == b'\x00\x20'

    print('What this transaction does')
    print(f'  Takes   {sats(prev["value"])} out of the vault {address_of(prev["script"], a.network) or prev["script"].hex()}')
    for o in spend['outputs']:
        print(f'  Pays    {sats(o["value"])} to {address_of(o["script"], a.network) or "a script with no address: " + o["script"].hex()}')
    print(f'  Fee     {sats(fee)}, which is {fee / spend["vsize"]:.2f} sat/vB for its {spend["vsize"]:,} vB')
    print()
    print('How it unlocks the vault')
    print(f'  {len(witness)} pieces of unlocking data, the last one the vault\'s script of {len(script):,} bytes.')
    if commitments(script):
        print(f'  The script begins with {commitments(script)} sealed secrets (their hashes). An ordinary payment')
        print('  unlocks with 2 pieces: a signature and a public key.')
    print()
    print('Checks')
    check(fee > 0, 'The fee is positive: nothing is created from nowhere.', 'The outputs add up to more than the vault holds.')
    check(is_vault and sha256(script) == prev['script'][2:],
          'The script shown is the one the vault\'s address was made from.',
          'The script shown does not hash to the vault\'s address.')
    if a.expect:
        pays = [o for o in spend['outputs'] if address_of(o['script'], a.network) == a.expect.strip()]
        check(len(pays) == len(spend['outputs']) == 1,
              f'Everything it pays goes to the address you gave, {a.expect.strip()}.',
              f'It does not pay only {a.expect.strip()}. Do not send it.')
    verdict = consensus(prev['script'], prev['value'], spend_hex)
    if verdict is None:
        print('  --   Bitcoin Core\'s consensus code was not run: the verifier is not built in the PQSB folder.')
    else:
        check(verdict, 'Bitcoin Core\'s consensus code accepts it, as every node will.',
              'Bitcoin Core\'s consensus code REFUSES it. Do not send it.')
        first = spend['outputs'][0]
        if verdict and first['value'] > 1:
            # The same unlocking data on a transaction that differs by one satoshi.
            raw = bytearray(bytes.fromhex(spend_hex))
            raw[first['at']:first['at'] + 8] = (first['value'] - 1).to_bytes(8, 'little')
            check(consensus(prev['script'], prev['value'], raw.hex()) is False,
                  'Changed to pay 1 sat less, the same unlocking data is refused: it fits this transaction only.',
                  'The unlocking data also fits a changed transaction. Do not send it, and tell Claude.')
    print()
    print(f'Its ID once sent: {spend["txid"]}')
    if problems:
        sys.exit('\nSomething is wrong. Do not send this transaction.')
    if verdict is None:
        print('\nEvery check that ran passed. The consensus check did not run.')
    else:
        print('\nEvery check passed. Nothing has been sent.')


if __name__ == '__main__':
    main()
