#!/usr/bin/env python3
"""Independent stdlib Discord proof mathematics. BLS/prior publication unverified."""
import hashlib
import hmac
import json
import re
import struct
import sys

VERSION = 'hmac-draw/discord-v1'
CHAIN = '52db9ba70e0cc0f6eaf7803dd07447a1f5477735fd3f661792ba94600c84e971'

def require(ok, message):
    if not ok:
        raise ValueError(message)

def keys(value, required, optional=()):
    require(type(value) is dict and set(required) <= value.keys() and value.keys() <= set(required) | set(optional), 'Invalid object fields')

def pairs(items):
    result = {}
    for key, value in items:
        require(key not in result, 'Duplicate JSON key')
        result[key] = value
    return result

def bad_number(value):
    raise ValueError('Only safe integers supported')

def canonical(value, depth=0):
    require(depth <= 64, 'JSON nesting too deep')
    if value is None or type(value) is bool:
        return json.dumps(value)
    if type(value) is int:
        require(abs(value) <= 9007199254740991, 'Unsafe integer')
        return str(value)
    if type(value) is str:
        value.encode('utf-8', errors='strict')
        return json.dumps(value, ensure_ascii=False, separators=(',', ':'))
    if type(value) is list:
        return '[' + ','.join(canonical(x, depth+1) for x in value) + ']'
    require(type(value) is dict, 'Invalid JSON value')
    require(not {'__proto__', 'constructor', 'prototype'} & value.keys(), 'Forbidden key')
    return '{' + ','.join(canonical(k)+':'+canonical(value[k], depth+1) for k in sorted(value, key=lambda k: k.encode('utf-16-be'))) + '}'

def digest(value):
    return hashlib.sha256(canonical(value).encode()).hexdigest()

def frame(domain, *fields):
    return domain.encode()+b'\0'+b''.join(struct.pack('>I', len(f))+f for f in fields)

def hex32(value):
    require(type(value) is str and re.fullmatch('[0-9a-f]{64}', value), 'Invalid hash')
    return bytes.fromhex(value)

def uuid_bytes(value):
    require(type(value) is str and re.fullmatch('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', value), 'Invalid UUID')
    return bytes.fromhex(value.replace('-', ''))

def snowflake(value):
    require(type(value) is str and re.fullmatch('[1-9][0-9]{16,19}', value) and int(value) <= 18446744073709551615, 'Invalid Discord ID')

def count(value, minimum, maximum=20000):
    require(type(value) is int and minimum <= value <= maximum, 'Invalid count')

def text(value, maximum):
    require(type(value) is str and 0 < len(value.encode('utf-16-le'))//2 <= maximum and not any(c in value for c in '\r\n\0'), 'Invalid text')

def verify(proof):
    canonical(proof)
    keys(proof, ['protocol_version','manifest','rules','lock','beacon','results','assignments','verification'])
    require(proof['protocol_version'] == VERSION, 'Unsupported protocol')
    manifest, rules, lock, beacon = (proof[k] for k in ['manifest','rules','lock','beacon'])
    keys(manifest, ['protocol_version','draw_id','entries'])
    keys(rules, ['protocol_version','event_mode','entry_source','winner_count','reserve_count','input_schema_hash','prizes','prize_order','discord_policy','beacon'])
    keys(lock, ['drawId','seedHex','commitment','manifestHash','rulesHash'])
    keys(beacon, ['round','chainHash','randomness'], ['signature'])
    keys(proof['verification'], ['beaconSignature','externalRegistry'])
    require(proof['verification'] == dict(beaconSignature='unverified', externalRegistry='unverified'), 'Invalid provenance claim')
    require(manifest['protocol_version'] == rules['protocol_version'] == VERSION and rules['event_mode'] == 'discord', 'Wrong version/mode')
    require(rules['entry_source'] in ('discord_button','discord_reaction'), 'Wrong source')
    draw = uuid_bytes(lock['drawId'])
    require(lock['drawId'] == manifest['draw_id'], 'Draw mismatch')
    entries = manifest['entries']
    count(len(entries), 1)
    for e in entries:
        keys(e, ['receipt_id'])
        hex32(e['receipt_id'])
    hashes = [e['receipt_id'] for e in entries]
    require(hashes == sorted(set(hashes)), 'Participants unordered/duplicated')
    count(rules['winner_count'], 1, 10000)
    count(rules['reserve_count'], 0)
    require(rules['winner_count']+rules['reserve_count'] <= len(entries), 'Insufficient participants')
    policy = rules['discord_policy']
    keys(policy, ['guild_id','channel_id','message_id','emojis','participant_hash','cutoff','creator_excluded','membership'])
    for key in ['guild_id','channel_id','message_id']:
        snowflake(policy[key])
    require(policy['participant_hash'] == 'sha256-discord-id-lf-first-username/v1' and policy['cutoff'] == 'accepted-while-open' and policy['creator_excluded'] is True and policy['membership'] == 'member-at-freeze', 'Invalid policy')
    require(type(policy['emojis']) is list and len(policy['emojis']) <= 20, 'Invalid emojis')
    require(bool(policy['emojis']) == (rules['entry_source'] == 'discord_reaction'), 'Invalid emoji mode')
    emoji_labels = []
    for e in policy['emojis']:
        keys(e, ['kind','id'])
        require(e['kind'] in ('unicode','custom'), 'Invalid emoji kind')
        snowflake(e['id']) if e['kind'] == 'custom' else text(e['id'], 64)
        emoji_labels.append(e['kind']+':'+e['id'])
    require(emoji_labels == sorted(set(emoji_labels), key=lambda s:s.encode()), 'Emoji order/duplicate')
    require(rules['input_schema_hash'] == digest(policy), 'Policy hash mismatch')
    keys(rules['beacon'], ['chain_hash','round'])
    count(beacon['round'], 1, 9007199254740991)
    count(rules['beacon']['round'], 1, 9007199254740991)
    require(beacon['chainHash'] == rules['beacon']['chain_hash'] == CHAIN and beacon['round'] == rules['beacon']['round'], 'Beacon mismatch')
    if 'signature' in beacon:
        require(type(beacon['signature']) is str and re.fullmatch('[0-9a-f]{96}', beacon['signature']), 'Invalid signature encoding')
    prizes = rules['prizes']
    require(type(prizes) is list and 1 <= len(prizes) <= 1000, 'Invalid prizes')
    ids = set()
    for p in prizes:
        keys(p, ['prize_id','provider_name','product_name','quantity'])
        uuid_bytes(p['prize_id']); text(p['provider_name'], 80); text(p['product_name'], 120); count(p['quantity'], 1, 10000)
        require(p['prize_id'] not in ids, 'Duplicate prize')
        ids.add(p['prize_id'])
    require(prizes == sorted(prizes, key=lambda p:(p['provider_name'].encode(),p['product_name'].encode(),p['prize_id'].encode())), 'Prize order')
    require(sum(p['quantity'] for p in prizes) == rules['winner_count'], 'Prize count')
    units, donors = [], {}
    for p in prizes:
        for unit in range(1, p['quantity']+1):
            donors[p['provider_name']] = donors.get(p['provider_name'],0)+1
            units.append(dict(prizeId=p['prize_id'],unit=unit,providerIndex=donors[p['provider_name']]))
    require(rules['prize_order'] == [p['prizeId']+':'+str(p['unit']) for p in units], 'Prize assignment order')
    seed, randomness = hex32(lock['seedHex']), hex32(beacon['randomness'])
    require(lock['commitment'] == hashlib.sha256(frame(VERSION+'/commit',draw,seed)).hexdigest(), 'Commitment mismatch')
    mh, rh = digest(manifest), digest(rules)
    require(lock['manifestHash'] == mh and lock['rulesHash'] == rh, 'Manifest/rules hash mismatch')
    key = hashlib.sha256(frame(VERSION+'/key',seed,randomness)).digest()
    ranked = sorted((hmac.new(key,frame(VERSION+'/score',draw,bytes.fromhex(mh),bytes.fromhex(rh),bytes.fromhex(h)),hashlib.sha256).hexdigest(),h) for h in hashes)
    results = [dict(receiptId=h,score=score,rank=i+1) for i,(score,h) in enumerate(ranked)]
    assignments = [dict(receiptId=results[i]['receiptId'],**p) for i,p in enumerate(units)]
    require(canonical(proof['results']) == canonical(results) and canonical(proof['assignments']) == canonical(assignments), 'Ranking/assignment mismatch')

def main():
    try:
        require(len(sys.argv) == 2, 'Usage: verify_discord.py proof.json | -')
        if sys.argv[1] == '-':
            sys.stdin.reconfigure(encoding='utf-8', errors='strict')
        with (open(sys.argv[1], encoding='utf-8') if sys.argv[1] != '-' else sys.stdin) as stream:
            data = stream.read(12000001)
        require(len(data) <= 12000000, 'Proof too large')
        verify(json.loads(data, object_pairs_hook=pairs, parse_float=bad_number, parse_constant=bad_number))
        report = dict(mathematical=True,beaconSignature='unverified',externalRegistry='unverified',errors=[])
        print(json.dumps(report)); return 0
    except (ValueError,TypeError,KeyError,OSError,RecursionError) as error:
        print(json.dumps(dict(mathematical=False,errors=[str(error)],beaconSignature='unverified',externalRegistry='unverified'))); return 1

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