#!/usr/bin/env python3
"""Reproducible check: the "proof" signature published on 2016-05-02 is a copy of a 2009 on-chain signature.
Pure Python 3 standard library. Steps:
 1. Download the Wayback Machine capture of the original 2016 post, extract the base64 signature.
 2. Download raw tx 828ef3b0...09fe (block 248, 2009-01-12) and locate the DER bytes in input 0's scriptSig.
 3. Download the spent tx 12b5633b...91ba, take output 1's scriptPubKey (P2PK) and pubkey.
 4. Rebuild the legacy SIGHASH_ALL digest for input 0 and verify ECDSA/secp256k1 -> prints True.
"""
import base64, hashlib, re, sys, urllib.request, time

ARCHIVE = "https://web.archive.org/web/20160502203734id_/http://www.drcraigwright.net/jean-paul-sartre-signing-significance/"
TXID = "828ef3b079f9c23829c56fe86e85b4a69d9e06e5b54ea597eef5fb3ffef509fe"
API = "https://mempool.space/api/tx/{}/hex"   # any raw-tx source works (e.g. blockstream.info/api/tx/{}/hex)

def get(url, tries=6):
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 (verify script)"})
            return urllib.request.urlopen(req, timeout=60).read()
        except Exception as e:
            if i == tries - 1: raise
            time.sleep(5 * (i + 1))

# ---------- tx parsing ----------
def varint(b, i):
    n = b[i]
    if n < 0xfd: return n, i + 1
    if n == 0xfd: return int.from_bytes(b[i+1:i+3], 'little'), i + 3
    if n == 0xfe: return int.from_bytes(b[i+1:i+5], 'little'), i + 5
    return int.from_bytes(b[i+1:i+9], 'little'), i + 9
def enc_varint(n):
    if n < 0xfd: return bytes([n])
    if n <= 0xffff: return b'\xfd' + n.to_bytes(2, 'little')
    return b'\xfe' + n.to_bytes(4, 'little')
def parse_tx(b):
    i = 0; ver = b[0:4]; i = 4
    n, i = varint(b, i); ins = []
    for _ in range(n):
        prev = b[i:i+32]; vout = b[i+32:i+36]; i += 36
        l, i = varint(b, i); ss = b[i:i+l]; i += l
        seq = b[i:i+4]; i += 4
        ins.append(dict(prev=prev, vout=vout, script=ss, seq=seq))
    n, i = varint(b, i); outs = []
    for _ in range(n):
        val = b[i:i+8]; i += 8
        l, i = varint(b, i); spk = b[i:i+l]; i += l
        outs.append(dict(value=val, spk=spk))
    lock = b[i:i+4]
    return dict(ver=ver, ins=ins, outs=outs, lock=lock)
def dsha(x): return hashlib.sha256(hashlib.sha256(x).digest()).digest()

def legacy_sighash_all(tx, idx, script_code):
    out = tx['ver'] + enc_varint(len(tx['ins']))
    for j, t in enumerate(tx['ins']):
        sc = script_code if j == idx else b''
        out += t['prev'] + t['vout'] + enc_varint(len(sc)) + sc + t['seq']
    out += enc_varint(len(tx['outs']))
    for o in tx['outs']: out += o['value'] + enc_varint(len(o['spk'])) + o['spk']
    out += tx['lock'] + (1).to_bytes(4, 'little')
    return dsha(out)

# ---------- secp256k1 ECDSA verify ----------
P = 2**256 - 2**32 - 977; N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
def add(a, b):
    if a is None: return b
    if b is None: return a
    if a[0] == b[0] and (a[1] + b[1]) % P == 0: return None
    if a == b: l = 3 * a[0] * a[0] * pow(2 * a[1], -1, P) % P
    else: l = (b[1] - a[1]) * pow(b[0] - a[0], -1, P) % P
    x = (l * l - a[0] - b[0]) % P
    return (x, (l * (a[0] - x) - a[1]) % P)
def mul(k, pt):
    r = None
    while k:
        if k & 1: r = add(r, pt)
        pt = add(pt, pt); k >>= 1
    return r
def parse_pub(pk):
    if pk[0] == 4: return (int.from_bytes(pk[1:33], 'big'), int.from_bytes(pk[33:65], 'big'))
    x = int.from_bytes(pk[1:33], 'big'); y = pow((x**3 + 7) % P, (P + 1) // 4, P)
    if (y & 1) != (pk[0] & 1): y = P - y
    return (x, y)
def parse_der(sig):
    assert sig[0] == 0x30 and sig[1] == len(sig) - 2, "not strict DER"
    i = 2; assert sig[i] == 2; lr = sig[i+1]; r = int.from_bytes(sig[i+2:i+2+lr], 'big'); i += 2 + lr
    assert sig[i] == 2; ls = sig[i+1]; s = int.from_bytes(sig[i+2:i+2+ls], 'big')
    return r, s
def ecdsa_verify(pub, z, r, s):
    w = pow(s, -1, N); pt = add(mul(z * w % N, G), mul(r * w % N, pub))
    return pt is not None and pt[0] % N == r

def main():
    # optional: pass a locally saved copy of the archived page as argv[1] (e.g. if web.archive.org rate-limits)
    html = (open(sys.argv[1], encoding='utf-8', errors='replace').read() if len(sys.argv) > 1
            else get(ARCHIVE).decode('utf-8', 'replace'))
    import html as _h
    text = _h.unescape(re.sub(r'<[^>]+>', '', html))           # drop tags, decode entities (&#43; -> +)
    flat = re.sub(r'\s+', '', text)                            # signature may be wrapped across lines
    cands = sorted(set(re.findall(r'ME[QU][A-Za-z0-9+/]{88,}={0,2}', flat)))
    print("[1] base64 signatures found in archived 2016 post:", cands)
    assert len(cands) == 1, "expected exactly one signature in the post"
    sig16 = base64.b64decode(cands[0]); print("    DER (%d bytes): %s" % (len(sig16), sig16.hex()))

    raw = bytes.fromhex(get(API.format(TXID)).decode().strip())
    assert dsha(raw)[::-1].hex() == TXID, "raw tx does not hash to txid"
    tx = parse_tx(raw)
    found = [(k, t) for k, t in enumerate(tx['ins']) if sig16 in t['script']]
    assert found, "signature not found in tx inputs"
    idx, inp = found[0]; ss = inp['script']
    pos = ss.index(sig16)
    print("[2] found in tx %s input %d scriptSig at offset %d; next byte (sighash type) = %02x" % (TXID, idx, pos, ss[pos + len(sig16)]))
    assert ss[pos - 1] == len(sig16) + 1 and ss[pos + len(sig16)] == 0x01  # push of DER+hashtype, SIGHASH_ALL

    prev_txid = inp['prev'][::-1].hex(); vout = int.from_bytes(inp['vout'], 'little')
    praw = bytes.fromhex(get(API.format(prev_txid)).decode().strip())
    assert dsha(praw)[::-1].hex() == prev_txid
    spk = parse_tx(praw)['outs'][vout]['spk']
    print("[3] spent output %s:%d scriptPubKey = %s" % (prev_txid, vout, spk.hex()))
    assert spk[-1] == 0xac and spk[0] in (33, 65), "expected P2PK"
    pub = parse_pub(spk[1:1 + spk[0]])

    z = int.from_bytes(legacy_sighash_all(tx, idx, spk), 'big')
    r, s = parse_der(sig16)
    ok = ecdsa_verify(pub, z, r, s)
    print("[4] legacy SIGHASH_ALL digest = %064x" % z)
    print("    ECDSA secp256k1 verify(2016 signature, 2009 tx digest, spent-output pubkey) =", ok)
    # negative control: the same signature must NOT verify against a different digest
    print("    negative control (digest+1) =", ecdsa_verify(pub, (z + 1) % N, r, s))
    return 0 if ok else 1

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