#!/usr/bin/env python3
"""MOON-MINT-v1 independent cross-check (PyNaCl + hand-rolled HKDF, RFC 5869).
Usage: python3 derive.py --test              throwaway vector
       python3 derive.py --entropy <hex>     recompute the pubkey after the reveal
pip install pynacl base58"""
import hashlib, hmac, sys, json, base58, nacl.signing
FILE="M175124932RE.IMG"; INFO=b"M175124932RE"+b"2011-11-05T09:34:24.703"; SALT=b"MOON-MINT-v1"
EXPECT="e8bfd20afe385af1f600c1fb3fb4bc7ef842aab26f4d9d46bc2520f0b5885a15"
def hkdf(ikm,salt,info,L=32):
    prk=hmac.new(salt,ikm,hashlib.sha256).digest(); t=b""; okm=b""; i=1
    while len(okm)<L: t=hmac.new(prk,t+info+bytes([i]),hashlib.sha256).digest(); okm+=t; i+=1
    return okm[:L]
h=hashlib.sha256()
with open(FILE,"rb") as f:
    for c in iter(lambda:f.read(1<<20),b""): h.update(c)
mh=h.digest(); assert mh.hex()==EXPECT, "image hash mismatch"
ent=bytes(range(32)) if "--test" in sys.argv else bytes.fromhex(sys.argv[sys.argv.index("--entropy")+1])
seed=hkdf(ent+mh,SALT,INFO)
print(json.dumps({"TEST_ONLY":"--test" in sys.argv,"moon_hash":mh.hex(),"commitment":hashlib.sha256(ent).hexdigest(),
  "seed":seed.hex(),"pubkey":base58.b58encode(bytes(nacl.signing.SigningKey(seed).verify_key)).decode()},indent=1))
