#!/usr/bin/env python3
"""Offline Elysium launch address verifier. Requires Python 3 and Foundry cast."""
import argparse
import hashlib
import json
import subprocess
from pathlib import Path

DOMAIN = hashlib.sha256(b"ElysiumMontraQuantumAddress/v1").digest()
ARCHIVE_SHA = "0x70f278b95b555fc6b6ea2637169228b81c47fa861afa5c4f3f0938658f802668"
JOB_ID = "db3vkeclf4us73c206fg"


def hex_bytes(value, size):
    result = bytes.fromhex(value.removeprefix("0x"))
    if len(result) != size:
        raise ValueError(f"Expected {size} bytes")
    return result


def keccak(data):
    output = subprocess.check_output(["cast", "keccak", "0x" + data.hex()], text=True)
    return hex_bytes(output.strip(), 32)


def verify(proof, raw):
    record = json.loads(raw)
    shots = record["bitstrings"]
    archive_hash = hashlib.sha256(raw).digest()
    if "0x" + archive_hash.hex() != ARCHIVE_SHA or archive_hash != hex_bytes(proof["archiveHash"], 32):
        raise ValueError("Archive digest mismatch")
    if (
        record["job_id"] != JOB_ID or record["backend"] != "ibm_marrakesh"
        or record["dry_run"] is not False or len(shots) != 16
        or any(len(shot) != 16 or set(shot) - {"0", "1"} for shot in shots)
    ):
        raise ValueError("Invalid measurement record")
    if proof["chainId"] != 99901:
        raise ValueError("Unexpected chain ID")
    measurement = int("".join(shots), 2).to_bytes(32, "big")
    factory = hex_bytes(proof["factory"], 20)
    creator = hex_bytes(proof["creator"], 20).rjust(32, b"\0")
    implementation = hex_bytes(proof["implementation"], 20)
    metadata_hash = hashlib.sha256(proof["metadataURI"].encode()).digest()
    inputs = DOMAIN + proof["chainId"].to_bytes(32, "big") + factory.rjust(32, b"\0")
    inputs += creator + metadata_hash + archive_hash + hashlib.sha256(measurement).digest()
    salt = hashlib.sha256(inputs).digest()
    if salt != hex_bytes(proof["salt"], 32):
        raise ValueError("Launch salt mismatch")
    factory_salt = keccak(creator + salt)
    initcode = bytes.fromhex("3d602d80600a3d3981f3363d3d373d3d3d363d73") + implementation
    initcode += bytes.fromhex("5af43d82803e903d91602b57fd5bf3")
    address = keccak(b"\xff" + factory + factory_salt + keccak(initcode))[-20:]
    if address != hex_bytes(proof["token"], 20):
        raise ValueError("Coin address mismatch")
    return address


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("proof", type=Path)
    parser.add_argument("measurements", type=Path)
    options = parser.parse_args()
    exported = json.loads(options.proof.read_bytes())
    proof = exported.get("proof", exported)
    address = verify(proof, options.measurements.read_bytes())
    print("MATCH 0x" + address.hex())
    receipt = exported.get("receipt")
    if receipt:
        print("Recorded Elysium receipt " + receipt["hash"])
        print("Inspect the receipt with cast receipt HASH --rpc-url YOUR_ELYSIUM_RPC.")


if __name__ == "__main__":
    main()
