#!/usr/bin/env python3
"""Aigistry record verifier (rules 2.0). Needs Python 3.8+ and the 'cryptography' package.
Usage:
  verify.py <record.json | https://.../r/<hash>.json> [--key HEX | --keys public-key.json | --keys-url URL]
Prints VALID or INVALID with the reason. Exit code 0 only when valid.
It checks, in order: (1) SHA-256 of the exact signed text equals record_hash; (2) the Ed25519 signature over that
hash (as ASCII hex) verifies under the named key. It uses the raw signed text, never a re-encoded copy."""
import sys, json, hashlib, urllib.request, argparse
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature

def load(src):
    if src.startswith(('http://', 'https://')):
        with urllib.request.urlopen(src, timeout=30) as r: return r.read()
    with open(src, 'rb') as f: return f.read()

def split(raw):
    t = raw.decode('utf-8')
    if not t.startswith('{"signed":'): raise ValueError('not an Aigistry record file')
    i = t.index(',"record_hash":')
    return t[len('{"signed":'):i], json.loads('{' + t[i + 1:])

def verify(raw, keys):
    signed, meta = split(raw)
    h = hashlib.sha256(signed.encode('utf-8')).hexdigest()
    if h != meta.get('record_hash'): return False, 'the signed text does not match the record hash'
    if meta.get('signature_algorithm') != 'Ed25519': return False, 'unexpected signature algorithm'
    key = keys.get(meta.get('public_key_id')) or (keys.get('*') if '*' in keys else None)
    if not key: return False, 'no key supplied for key id %s' % meta.get('public_key_id')
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(key)).verify(bytes.fromhex(meta['signature']), h.encode('ascii'))
    except (InvalidSignature, ValueError): return False, 'the signature does not verify'
    rec = json.loads(signed)
    return True, 'format %s, %s, %s, revision %s, received %s' % (rec.get('format'), rec.get('organization'), rec.get('domain'), rec.get('revision'), rec.get('received_at'))

if __name__ == '__main__':
    a = argparse.ArgumentParser(); a.add_argument('record'); a.add_argument('--key'); a.add_argument('--keys'); a.add_argument('--keys-url', default='https://aigistry.com/public-key.json')
    o = a.parse_args(); keys = {}
    if o.key: keys['*'] = o.key
    else:
        kj = json.loads(load(o.keys or o.keys_url)); keys = {k['key_id']: k['public_key'] for k in kj['keys']}
    ok, why = verify(load(o.record), keys); print(('VALID: ' if ok else 'INVALID: ') + why); sys.exit(0 if ok else 1)
