SPB Git

Repository Public

reduce_vectors.py 5.2 KB 138 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : QYVORA8# File             : Tests/QyvoraSLHDSATests/Vectors/reduce_vectors.py9# Module           : Tests10# Repository       : https://git.spboucher.ai/qyvora11# Project Website  : Not specified12# Created          : 2026-12-0413# Last Modified    : 2026-12-0414#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: contact@spboucher.ai23# Development      : dev@spboucher.ai24# Support          : support@spboucher.ai25# Security/Admin   : admin@spboucher.ai26#27# Copyright (c) 202628# Simon-Pierre Boucher29# All rights reserved where applicable. This file is governed by the30# applicable project license, copyright notices and relevant law.31# Existing third-party rights and notices remain unaffected.32#33# License          : None specified (no license file in this repository)34#35# Do not embed credentials, private keys, access tokens,36# certificates or confidential personal information.37#38# =============================================================================39# END OF SP BOUCHER SOURCE HEADER40# =============================================================================4142"""Builds the committed SLH-DSA known-answer files from the complete NIST ACVP files.4344Usage:45    python3 -I reduce_vectors.py <acvp-dir> <output-dir>4647<acvp-dir> holds the NIST files, gzip-compressed and otherwise unmodified:48    SLH-DSA-keyGen-FIPS205/internalProjection.json.gz49    SLH-DSA-sigGen-FIPS205/internalProjection.json.gz50    SLH-DSA-sigVer-FIPS205/internalProjection.json.gz5152Output (<output-dir>):53    keyGen.json.gz   byte-for-byte copy of the NIST gzip file (all 120 cases)54    sigGen.json.gz   every test group kept, 1 test case per group55    sigVer.json.gz   every test group kept, 2 test cases per group5657Selection rule (deterministic, groups and cases visited in file order):58  sigGen  - group without pre-hash (internal interface, external pure): the first case;59          - pre-hash group: the first case whose hashAlg has been kept the fewest times so far60            in the file, so that the 12 pre-hash functions are all covered.61  sigVer  - the first case with testPassed = true, then the first case with testPassed = false62            whose "reason" has been kept the fewest times so far in the file, so that the63            6 rejection reasons are all covered.6465Kept test cases and group/file metadata are not altered; only the "tests" lists are shortened.66The JSON is re-serialized compactly and gzip-compressed with a zero timestamp, so the output is67reproducible bit for bit.68"""69import collections70import gzip71import io72import json73import shutil74import sys757677def load(acvp_dir, mode):78    path = f"{acvp_dir}/SLH-DSA-{mode}-FIPS205/internalProjection.json.gz"79    with gzip.open(path) as f:80        return json.load(f)818283def write(doc, path):84    raw = json.dumps(doc, separators=(",", ":")).encode()85    buf = io.BytesIO()86    with gzip.GzipFile(filename="", mode="wb", fileobj=buf, compresslevel=9, mtime=0) as f:87        f.write(raw)88    with open(path, "wb") as f:89        f.write(buf.getvalue())909192def least_kept(tests, key, kept):93    best = min(tests, key=lambda t: kept[t[key]])  # min() returns the first minimum: file order94    kept[best[key]] += 195    return best969798def reduce_siggen(doc):99    kept = collections.Counter()100    for group in doc["testGroups"]:101        tests = group["tests"]102        if group["preHash"] == "preHash":103            group["tests"] = [least_kept(tests, "hashAlg", kept)]104        else:105            group["tests"] = [tests[0]]106    return doc107108109def reduce_sigver(doc):110    kept = collections.Counter()111    for group in doc["testGroups"]:112        tests = group["tests"]113        valid = next(t for t in tests if t["testPassed"])114        invalid = least_kept([t for t in tests if not t["testPassed"]], "reason", kept)115        group["tests"] = sorted([valid, invalid], key=lambda t: t["tcId"])116    return doc117118119def main():120    if len(sys.argv) != 3:121        sys.exit(__doc__)122    acvp_dir, out_dir = sys.argv[1], sys.argv[2]123    shutil.copyfile(f"{acvp_dir}/SLH-DSA-keyGen-FIPS205/internalProjection.json.gz", f"{out_dir}/keyGen.json.gz")124    sig_gen = reduce_siggen(load(acvp_dir, "sigGen"))125    sig_ver = reduce_sigver(load(acvp_dir, "sigVer"))126    write(sig_gen, f"{out_dir}/sigGen.json.gz")127    write(sig_ver, f"{out_dir}/sigVer.json.gz")128    for name, doc in (("sigGen", sig_gen), ("sigVer", sig_ver)):129        cases = [t for g in doc["testGroups"] for t in g["tests"]]130        algs = collections.Counter(t["hashAlg"] for t in cases)131        print(f"{name}: {len(doc['testGroups'])} groups, {len(cases)} cases, hashAlg {dict(sorted(algs.items()))}")132        if name == "sigVer":133            print("  reasons", dict(sorted(collections.Counter(t["reason"] for t in cases).items())))134135136if __name__ == "__main__":137    main()138
Files main
Menu

Theme