# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR84
# Experiment: challenge response and mutual authentication
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR84 | Challenge-response and mutual authentication
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import hmac
import json



DEFAULT={'tamper': False}
ALTERNATE={'tamper': True}

def run(overrides=None):
    # Merge only explicitly supplied inputs with the lecture baseline.
    params={**DEFAULT, **(overrides or {})}
    tamper=params['tamper']
    if type(tamper) is not bool:
        raise ValueError('Invalid classroom input')
    k=b'synthetic shared key';client_nonce=b'nonce-client';server_nonce=b'nonce-server';mac=lambda label:hmac.new(k,label+b'|'+client_nonce+b'|'+server_nonce,hashlib.sha256).digest();server=mac(b'server');client=mac(b'client');received=client[:-1]+bytes([client[-1]^1]) if tamper else client;steps=[{'message':'client nonce','hex':client_nonce.hex()},{'message':'server proof','tag':server.hex(),'accepted':hmac.compare_digest(server,mac(b'server'))},{'message':'client proof','expected_tag':client.hex(),'received_tag':received.hex(),'accepted':hmac.compare_digest(received,mac(b'client'))}];result={'mutual':steps[1]['accepted'] and steps[2]['accepted']}
    # Independently check the stated mathematical or protocol invariant.
    assert result["mutual"]== (not tamper), "verification failed"
    return {"steps":steps,"result":result}

if __name__ == "__main__":
    import argparse
    parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
    if args.test:
        for case in [{},ALTERNATE]:run(case)
        print("PASS")
    else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
