#!/usr/bin/env python3
# Independent reference verifier for ScoreCompute receipt v1
# (scorecompute.verify.receipt.v1) and the shareable link container
# (scorecompute.verify.link.v1).
#
# Separate implementation of the documented v1 service format, checked against
# the Node implementation and public test vectors. Standard library only: the
# Ed25519 verification is reimplemented from RFC 8032 (compact reference
# arithmetic) so the check does not depend on Node/OpenSSL.
#
# Usage:
#   python3 verify-receipt.py <receipt.json | link.json | -> <trusted-keyset.json>
# Exit codes: 0 valid, 1 malformed input, 2 verification failed.
import base64
import hashlib
import json
import math
import re
import sys
from fractions import Fraction
from datetime import datetime, timezone

RECEIPT_VERSION = 'scorecompute.verify.receipt.v1'
LINK_VERSION = 'scorecompute.verify.link.v1'
KEYSET_VERSION = 'scorecompute.verify.keys.v1'
MAX_RECEIPT_BYTES = 64 * 1024
MAX_JSON_BYTES = 128 * 1024

# --- RFC 8032 Ed25519 verification (compact reference arithmetic) ------------
P = 2 ** 255 - 19
Q = 2 ** 252 + 27742317777372353535851937790883648493
D = (-121665 * pow(121666, P - 2, P)) % P
I = pow(2, (P - 1) // 4, P)


def x_recover(y):
    xx = (y * y - 1) * pow(D * y * y + 1, P - 2, P)
    x = pow(xx, (P + 3) // 8, P)
    if (x * x - xx) % P != 0:
        x = (x * I) % P
    if x % 2 != 0:
        x = P - x
    return x


BY = (4 * pow(5, P - 2, P)) % P
BX = x_recover(BY)
B = (BX, BY)


def edwards_add(p, q):
    x1, y1 = p
    x2, y2 = q
    x3 = (x1 * y2 + x2 * y1) * pow(1 + D * x1 * x2 * y1 * y2, P - 2, P)
    y3 = (y1 * y2 + x1 * x2) * pow(1 - D * x1 * x2 * y1 * y2, P - 2, P)
    return (x3 % P, y3 % P)


def scalarmult(p, e):
    if e == 0:
        return (0, 1)
    result = scalarmult(p, e // 2)
    result = edwards_add(result, result)
    if e & 1:
        result = edwards_add(result, p)
    return result


def decode_point(data):
    if len(data) != 32:
        raise ValueError('point length')
    y = int.from_bytes(data, 'little') & ((1 << 255) - 1)
    if y >= P:
        raise ValueError('non-canonical point')
    x = x_recover(y)
    if x == 0 and data[31] >> 7:
        raise ValueError('non-canonical point sign')
    if (x & 1) != (data[31] >> 7):
        x = P - x
    if (-x * x + y * y - 1 - D * x * x * y * y) % P != 0:
        raise ValueError('point not on curve')
    return (x, y)


def ed25519_verify(public_key, message, signature):
    if len(signature) != 64 or len(public_key) != 32:
        return False
    r_bytes = signature[:32]
    s = int.from_bytes(signature[32:], 'little')
    if s >= Q:
        return False
    try:
        a = decode_point(public_key)
        r = decode_point(r_bytes)
    except ValueError:
        return False
    # Strict issuer-key profile: reject identity and non-prime-order points.
    # A valid external trust anchor must not admit universal weak-key forgeries.
    if a == (0, 1) or scalarmult(a, Q) != (0, 1) or scalarmult(r, Q) != (0, 1):
        return False
    h = int.from_bytes(hashlib.sha512(r_bytes + public_key + message).digest(), 'little') % Q
    left = scalarmult(B, s)
    right = edwards_add(r, scalarmult(a, h))
    return left == right


# --- receipt verification ----------------------------------------------------

def _expand_decimal(mantissa, exponent):
    sign = ''
    if mantissa.startswith('-'):
        sign, mantissa = '-', mantissa[1:]
    digits = mantissa.replace('.', '')
    int_part = mantissa.split('.')[0] if '.' in mantissa else mantissa
    point = len(int_part) + exponent
    if point <= 0:
        text = '0.' + '0' * (-point) + digits
    elif point >= len(digits):
        text = digits + '0' * (point - len(digits))
    else:
        text = digits[:point] + '.' + digits[point:]
    if '.' in text:
        text = text.rstrip('0').rstrip('.')
    return sign + text


def _js_number(value):
    """Shortest binary64 decimal, nearest candidate and even tie breaking.

    Work with exact rational distances instead of expanding int(float), which
    prints 1000000000000000128 where ECMAScript prints 1000000000000000100.
    JSON numbers have binary64 semantics here, including integer input tokens.
    """
    if isinstance(value, bool):
        return 'true' if value else 'false'
    try:
        value = float(value)
    except (ValueError, OverflowError, TypeError):
        fail('Only finite JSON numbers are accepted.')
    if not math.isfinite(value):
        fail('Only finite JSON numbers are accepted.')
    if value == 0:
        return '0'
    sign, absolute = ('-' if value < 0 else ''), abs(value)
    exact = Fraction(absolute)
    exponent = math.floor(math.log10(absolute))
    power = lambda e: Fraction(10 ** e) if e >= 0 else Fraction(1, 10 ** -e)
    while exact < power(exponent):
        exponent -= 1
    while exact >= power(exponent + 1):
        exponent += 1
    for digits_count in range(1, 18):
        scale_exp = exponent - digits_count + 1
        scale = power(scale_exp)
        center = exact // scale
        candidates = []
        for n in range(max(1, center - 1), center + 3):
            try:
                matches = float(str(n) + 'e' + str(scale_exp)) == absolute
            except OverflowError:
                matches = False
            if matches:
                candidates.append((abs(Fraction(n) * scale - exact), n % 2, n))
        if candidates:
            n = min(candidates)[2]
            while n % 10 == 0:
                n //= 10
                scale_exp += 1
            digits = str(n)
            e = len(digits) - 1 + scale_exp
            mantissa = digits[0] + ('.' + digits[1:] if len(digits) > 1 else '')
            if -6 <= e < 21:
                return sign + _expand_decimal(mantissa, e)
            return sign + mantissa + 'e' + ('+' if e >= 0 else '-') + str(abs(e))
    fail('Could not serialize binary64 number.')


def _quote(value):
    # ECMAScript well-formed JSON.stringify escapes unpaired UTF-16 surrogates.
    value = value.encode('utf-16-le', 'surrogatepass').decode('utf-16-le', 'surrogatepass')
    text = json.dumps(value, ensure_ascii=False, separators=(',', ':'))
    return ''.join('\\u%04x' % ord(c) if 0xd800 <= ord(c) <= 0xdfff else c for c in text)


def _key_order(key):
    # JSON.stringify enumerates array-index keys numerically before all others,
    # even after the service has inserted the keys in UTF-16 lexical order.
    if re.fullmatch(r'0|[1-9][0-9]{0,9}', key) and int(key) < 2 ** 32 - 1:
        return (0, int(key))
    return (1, key.encode('utf-16-be', 'surrogatepass'))


def _write_canonical(value, depth, nodes):
    nodes[0] += 1
    if nodes[0] > 20000 or depth > 32:
        fail('JSON complexity limit exceeded.')
    if value is None:
        return 'null'
    if isinstance(value, (bool, int, float)):
        return _js_number(value)
    if isinstance(value, str):
        return _quote(value)
    if isinstance(value, list):
        return '[' + ','.join(_write_canonical(item, depth + 1, nodes) for item in value) + ']'
    if isinstance(value, dict):
        for key in value:
            if not isinstance(key, str):
                fail('JSON object keys must be strings.')
            if key in ('__proto__', 'constructor', 'prototype'):
                fail('Reserved JSON key.')
        return '{' + ','.join(
            _quote(key) + ':' + _write_canonical(value[key], depth + 1, nodes)
            for key in sorted(value, key=_key_order)
        ) + '}'
    fail('Only JSON data is accepted.')


def canonical_json(value):
    result = _write_canonical(value, 0, [0])
    if len(result.encode('utf-8')) > MAX_JSON_BYTES:
        fail('JSON size limit exceeded.')
    return result


def sha256_hex(text):
    return hashlib.sha256(text.encode('utf-8')).hexdigest()


def fail(reason):
    raise ValueError(reason)


def to_envelope(document):
    if not isinstance(document, dict):
        fail('Receipt must be an object.')
    if document.get('v') == LINK_VERSION:
        allowed = {'v', 'payload_json', 'signature', 'signed_at'}
        if set(document) - allowed:
            fail('Unknown link field: ' + ','.join(sorted(set(document) - allowed)))
        payload_json = document.get('payload_json')
        if not isinstance(payload_json, str):
            fail('Link payload_json must be a string.')
        return {
            'payload': json.loads(payload_json),
            'payload_json': payload_json,
            'payload_sha256': sha256_hex(payload_json),
            'signature': document.get('signature'),
            'signed_at': document.get('signed_at'),
        }
    return document


def parse_iso(value):
    if not isinstance(value, str) or not re.fullmatch(r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z', value):
        fail('Expected canonical UTC ISO timestamp.')
    return datetime.strptime(value, '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone.utc)


def strict_base64(value, length, label):
    if not isinstance(value, str):
        fail('Invalid ' + label + '.')
    try:
        decoded = base64.b64decode(value, validate=True)
    except Exception:
        fail('Invalid ' + label + '.')
    if len(decoded) != length or base64.b64encode(decoded).decode('ascii') != value:
        fail('Invalid canonical ' + label + '.')
    return decoded


def response_digest_status(payload):
    names = {'engine_response', 'engine_response_digest', 'engine_response_included'}
    if not names.intersection(payload):
        return 'not_present'
    if not names.issubset(payload) or not isinstance(payload['engine_response_included'], bool):
        fail('Incomplete engine response binding.')
    if not isinstance(payload['engine_response_digest'], str) or not re.fullmatch(r'[0-9a-f]{64}', payload['engine_response_digest']):
        fail('Invalid engine response digest.')
    if not payload['engine_response_included']:
        if payload['engine_response'] is not None:
            fail('Excluded engine response must be null.')
        return 'not_included'
    response = payload['engine_response']
    if not isinstance(response, dict):
        fail('Included engine response must be an object.')
    stable = {k: v for k, v in response.items() if k != 'elapsed_ms'}
    if sha256_hex(canonical_json(stable)) != payload['engine_response_digest']:
        fail('Engine response digest mismatch.')
    return 'verified'


def verify_receipt(receipt_input, keyset):
    if len(canonical_json(receipt_input).encode('utf-8')) > MAX_RECEIPT_BYTES:
        fail('Receipt exceeds 64 KiB.')
    receipt = to_envelope(receipt_input)
    if len(canonical_json(receipt).encode('utf-8')) > MAX_RECEIPT_BYTES:
        fail('Receipt exceeds 64 KiB.')
    if not isinstance(receipt, dict):
        fail('Receipt must be an object.')
    payload_json = receipt.get('payload_json')
    if not isinstance(payload_json, str):
        fail('payload_json must be a string.')
    payload_sha256 = receipt.get('payload_sha256')
    if not isinstance(payload_sha256, str) or not re.fullmatch(r'[0-9a-f]{64}', payload_sha256):
        fail('payload_sha256 must be 64 hex characters.')
    signature = receipt.get('signature') or {}
    if not isinstance(signature, dict):
        fail('Invalid signature metadata.')
    if signature.get('alg') != 'Ed25519':
        fail('signature.alg must be Ed25519.')
    signature_bytes = strict_base64(signature.get('value_b64'), 64, 'signature')
    parse_iso(receipt.get('signed_at') or '')

    parsed = json.loads(payload_json)
    if not isinstance(parsed, dict):
        fail('Payload must be an object.')
    if canonical_json(parsed) != payload_json:
        fail('Non-canonical payload JSON.')
    if 'payload' in receipt and canonical_json(receipt['payload']) != payload_json:
        fail('Payload and payload_json differ.')
    if sha256_hex(payload_json) != payload_sha256:
        fail('Payload digest mismatch.')
    if parsed.get('v') != RECEIPT_VERSION:
        fail('Unknown receipt version.')
    if parsed.get('tool') != 'verify_claim':
        fail('Unknown receipt tool.')
    if parsed.get('domain') not in ('numbers', 'ephemeris', 'shadow', 'statistics', 'route'):
        fail('Unknown receipt domain.')
    if parsed.get('verdict') not in ('compatible', 'contradicted', 'inconclusive', 'out_of_validation_scope'):
        fail('Unknown receipt verdict.')
    if not isinstance(parsed.get('limits'), list) or not all(isinstance(item, str) for item in parsed['limits']):
        fail('Receipt limits must be an array of strings.')
    if parsed.get('signed_at') != receipt.get('signed_at'):
        fail('Signed envelope time mismatch.')
    signing = parsed.get('signing') or {}
    if not isinstance(signing, dict):
        fail('Invalid signing metadata.')
    if (signing.get('alg') != signature.get('alg')
            or signing.get('key_id') != signature.get('key_id')
            or signing.get('public_key_url') != signature.get('public_key_url')):
        fail('Signed key metadata mismatch.')

    if not isinstance(keyset, dict) or keyset.get('v') != KEYSET_VERSION or not isinstance(keyset.get('keys'), list) or not 1 <= len(keyset['keys']) <= 33:
        fail('Invalid trusted keyset.')
    ids = []
    for key in keyset['keys']:
        if not isinstance(key, dict) or not isinstance(key.get('key_id'), str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,95}', key['key_id']):
            fail('Invalid trusted key identifier.')
        ids.append(key['key_id'])
        parse_iso(key.get('valid_from'))
        if not isinstance(key.get('revoked'), bool) or 'retired_at' not in key:
            fail('Invalid trusted key validity metadata.')
        if key['retired_at'] is not None and parse_iso(key['retired_at']) <= parse_iso(key['valid_from']):
            fail('Invalid key validity interval.')
    if len(ids) != len(set(ids)) or keyset.get('current_key_id') not in ids:
        fail('Invalid trusted keyset identifiers.')
    entry = next((key for key in keyset['keys'] if key.get('key_id') == signature.get('key_id')), None)
    if entry is None:
        fail('Unknown trusted key.')
    if entry.get('revoked'):
        fail('Signing key is revoked.')
    signed_at = parse_iso(receipt['signed_at'])
    if signed_at < parse_iso(entry.get('valid_from') or ''):
        fail('Signing key was not yet valid.')
    retired = entry.get('retired_at')
    if retired and signed_at >= parse_iso(retired):
        fail('Signing key was retired before this receipt.')
    if entry.get('encoding') != 'spki-der' or entry.get('alg') != 'Ed25519':
        fail('Unsupported public key entry.')

    public_key = strict_base64(entry.get('public_key_b64'), 44, 'public key')
    # SPKI DER for Ed25519: fixed 12-byte header then the 32-byte key.
    if len(public_key) != 44 or public_key[:12] != bytes.fromhex('302a300506032b6570032100'):
        fail('Unexpected SPKI encoding for the Ed25519 key.')
    public_key = public_key[12:]
    signing_input = (RECEIPT_VERSION + '\n' + payload_sha256).encode('ascii')
    if not ed25519_verify(public_key, signing_input, signature_bytes):
        fail('Signature mismatch.')
    digest_status = response_digest_status(parsed)
    return {
        'valid': True,
        'verdict': parsed.get('verdict'),
        'domain': parsed.get('domain'),
        'signed_at': receipt['signed_at'],
        'key_id': signature.get('key_id'),
        'limits': parsed.get('limits', []),
        'engine_response_digest': digest_status,
    }


def main():
    if len(sys.argv) != 3:
        print('Usage: python3 verify-receipt.py <receipt.json | link.json> <trusted-keyset.json>')
        return 1
    receipt_path, keyset_path = sys.argv[1], sys.argv[2]
    try:
        with (sys.stdin.buffer if receipt_path == '-' else open(receipt_path, 'rb')) as stream:
            raw_bytes = stream.read(MAX_RECEIPT_BYTES + 1)
        if len(raw_bytes) > MAX_RECEIPT_BYTES:
            fail('Receipt exceeds 64 KiB.')
        receipt = json.loads(raw_bytes.decode('utf-8'))
        with open(keyset_path, 'rb') as stream:
            keys_raw = stream.read(MAX_JSON_BYTES + 1)
        if len(keys_raw) > MAX_JSON_BYTES:
            fail('Keyset exceeds 128 KiB.')
        keyset = json.loads(keys_raw.decode('utf-8'))
        result = verify_receipt(receipt, keyset)
        print(f"VALID  {result['verdict']}  {result['domain']}  {result['signed_at']}  key {result['key_id']}")
        for limitation in result['limits']:
            print('  limit  ' + limitation)
        return 0
    except Exception as error:
        print('INVALID  ' + str(error))
        return 1 if isinstance(error, (json.JSONDecodeError, UnicodeDecodeError, OSError)) else 2


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