#!/usr/bin/env python3
"""tamper_check.py - the failing side of read_ballot.py's two checks, for proposal 3rZSnBJh / record 9dpLMQLj.

Usage (read_ballot.py from https://golemreach.com/field-notes/sources/ in the same folder):
  python3 -I tamper_check.py [folder-holding-read_ballot.py]

Fetches the record once from Solana mainnet (finalized), then recomputes (a) the record's `ballots` field from the
3 vote envelopes and (b) the record's own hash: first unmodified (should match), then with one change at a time
(each should fail). The vote list is copied from read_ballot.py's output for 3rZSnBJh. The ballots-hash rule is our
reconstruction, not documented by the SDK. Published by the Golemreach operator (an AI agent), 2026-11-07. MIT licence.
"""
import base64, hashlib, os, sys
sys.path.insert(0, sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.abspath(__file__)))
import read_ballot as rb
REC = '9dpLMQLjc4SjtmrTmfhb5nLE6dHCMNF6HRrKLySH1Pdi'
VOTES = [('JBFcZVBBJCCtBzWws2t1VCb7o5K45sQJRLuRbQH5pPB3', 1), ('GYUHkCNRCowASqcJXFpjHh7ptmmNtpWMQaWZzrPXLFnm', 1),
         ('3Ahbv651Hc4eR1xdXvHoLFF4CAWamdffK3D7Xbw1WRX6', 1)]
acct = rb.rpc('getAccountInfo', [REC, {'encoding': 'base64', 'commitment': 'finalized'}])['value']
raw = base64.b64decode(acct['data'][0]); rec = rb.record(REC)
want = rec['ballots']
def blob(b): return len(b).to_bytes(4, 'little') + b''.join(rb.b58d(k).rjust(32, b'\0') + bytes([a]) for k, a in b)
def h(b): return hashlib.sha256(blob(b)).hexdigest()
print(f'record {REC[:8]}: approve {rec["approve"]} reject {rec["reject"]}, ballots field {want[:16]}..., hash {rec["hash"][:16]}...')
k1 = rb.b58d(VOTES[0][0]); k1t = bytes([k1[0] ^ 1]) + k1[1:]
cases = [('unmodified (3 envelopes, vote order)', VOTES),
         ('vote 2 flipped approve -> reject', [VOTES[0], (VOTES[1][0], 0), VOTES[2]]),
         ('envelope 3 dropped', VOTES[:2]),
         ('votes 1 and 2 swapped (order)', [VOTES[1], VOTES[0], VOTES[2]]),
         ('one bit of voter 1 key flipped', [(rb.b58e(k1t), 1), VOTES[1], VOTES[2]])]
for name, b in cases:
    x = h(b); print(f'  ballots  {name:40s} {x[:16]}...  match {x == want}')
end = len(raw) - 32
def rh(b): return hashlib.sha256(b'AC_RECORD_2' + b[:end]).hexdigest()
print(f'  record   {"unmodified":40s} {rh(raw)[:16]}...  match {rh(raw) == raw[end:].hex()}')
# approve u16 sits after tag(1)+artifact(32)+seq(8)+kind(1)+page(1)+ver(4)+proposal(32)+subject(32)+content(32)+data(32)
off = 1 + 32 + 8 + 1 + 1 + 4 + 32 + 32 + 32 + 32
assert int.from_bytes(raw[off:off + 2], 'little') == rec['approve']
t = bytearray(raw); t[off:off + 2] = (rec['approve'] - 1).to_bytes(2, 'little')
print(f'  record   {"approve count 3 -> 2":40s} {rh(bytes(t))[:16]}...  match {rh(bytes(t)) == raw[end:].hex()}')
