SPB Git

Repository Public

fetch.py 14.2 KB 315 lines python

1#!/usr/bin/env python32# =============================================================================3#                  SP BOUCHER | SOFTWARE & RESEARCH4#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project          : QYVORA8# File             : security/vectors/fetch.py9# Module           : Security10# 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"""Fetches (or verifies) the third-party test vectors of the audit at pinned revisions.4344    python3 security/vectors/fetch.py            # download pinned revisions, rewrite files + MANIFEST.json45    python3 security/vectors/fetch.py --verify   # check the committed files against MANIFEST.json (offline)46    python3 security/vectors/fetch.py --only=ed25519   # fetch one group and merge it into the manifest4748Only public test-vector files are downloaded; nothing is uploaded. Downloaded Python sources are49never executed: lists are extracted with `ast.literal_eval`. Files are stored gzip-compressed with50a zero timestamp so that the result is reproducible; MANIFEST.json records the source URL, the51pinned commit, the licence and the SHA-256 of both the raw content and the stored file.52"""5354from __future__ import annotations5556import ast57import gzip58import hashlib59import io60import json61import re62import sys63import urllib.request64from pathlib import Path6566HERE = Path(__file__).resolve().parent67MANIFEST = HERE / "MANIFEST.json"6869WYCHEPROOF_COMMIT = "c0cfeee0654850a5f407628a00381e6e685227cd"  # C2SP/wycheproof main, 2026-11-2970BIPS_COMMIT = "c597d68e983096f623817c9feb1692d46722eb89"  # bitcoin/bips71MNEMONIC_COMMIT = "b57a5ad77a981e743f4167ab2f7927a55c1e82a8"  # trezor/python-mnemonic72BECH32_COMMIT = "7a7d7ab158db7078a333384e0e918c90dbc42917"  # sipa/bech3273SPECCHECK_COMMIT = "65519336fda78a3d016e947df6d82848aca0c9da"  # novifinancial/ed25519-speccheck74SLIPS_COMMIT = "5daa374367ef57ba9a880ff2b3819720fdbab9ab"  # satoshilabs/slips75RFC8032_SHA256 = "ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3"  # rfc-editor.org/rfc/rfc8032.txt7677WYCHEPROOF_FILES = [78    "aes_gcm_test.json", "chacha20_poly1305_test.json",79    "ecdsa_secp256k1_sha256_test.json", "ecdsa_secp256k1_sha256_bitcoin_test.json",80    "ecdsa_secp256k1_sha256_p1363_test.json",81    "hkdf_sha256_test.json", "hkdf_sha512_test.json", "hmac_sha256_test.json", "hmac_sha512_test.json",82    "pbkdf2_hmacsha256_test.json", "pbkdf2_hmacsha512_test.json", "x25519_test.json", "ed25519_test.json",83] + [f"mlkem_{n}_{k}.json" for n in (512, 768, 1024)84     for k in ("test", "encaps_test", "keygen_seed_test", "semi_expanded_decaps_test")] \85  + [f"mldsa_{n}_{k}.json" for n in (44, 65, 87) for k in ("sign_seed_test", "sign_noseed_test", "verify_test")]8687RAW = "https://raw.githubusercontent.com"888990def get(url: str) -> bytes:91    req = urllib.request.Request(url, headers={"User-Agent": "vector-fetch"})92    with urllib.request.urlopen(req, timeout=120) as r:93        return r.read()949596def sha(b: bytes) -> str:97    return hashlib.sha256(b).hexdigest()9899100def gz(b: bytes) -> bytes:101    buf = io.BytesIO()102    with gzip.GzipFile(fileobj=buf, mode="wb", mtime=0, filename="") as f:103        f.write(b)104    return buf.getvalue()105106107def store(entries: list, rel: str, raw: bytes, url: str, commit: str, licence: str, compress: bool, note: str = ""):108    data = gz(raw) if compress else raw109    path = HERE / rel110    path.parent.mkdir(parents=True, exist_ok=True)111    path.write_bytes(data)112    entries.append({"path": rel, "source_url": url, "commit": commit, "licence": licence,113                    "sha256_raw": sha(raw), "sha256_file": sha(data), "bytes": len(data), "note": note})114    print(f"  {rel}  {len(data)} bytes")115116117def python_lists(source: str) -> dict:118    """Top-level `NAME = [literal list]` assignments of a Python source, without executing it."""119    out = {}120    for node in ast.parse(source).body:121        if isinstance(node, ast.Assign) and len(node.targets) == 1 and isinstance(node.targets[0], ast.Name):122            try:123                out[node.targets[0].id] = ast.literal_eval(node.value)124            except (ValueError, SyntaxError):125                pass126    return out127128129def bip32_vectors(wiki: str) -> dict:130    """Extracts the test vectors of bip-0032.mediawiki (chains with their extended keys, invalid keys)."""131    vectors, invalid = [], []132    current = None133    chain = None134    for line in wiki.splitlines():135        line = line.strip().replace("<sub>H</sub>", "'")136        m = re.match(r"===Test vector (\d+)===", line)137        if m:138            current = {"vector": int(m.group(1)), "seed": "", "chains": []}139            vectors.append(current)140            continue141        if current is None:142            continue143        m = re.match(r"Seed \(hex\): ([0-9a-f]+)", line)144        if m:145            current["seed"] = m.group(1)146        m = re.match(r"\* Chain (m[0-9/H'h]*)", line)147        if m:148            chain = {"path": m.group(1).replace("H", "'").replace("h", "'"), "xpub": "", "xprv": ""}149            current["chains"].append(chain)150        m = re.match(r"\*\* ext pub: (\w+)", line)151        if m and chain is not None:152            chain["xpub"] = m.group(1)153        m = re.match(r"\*\* ext prv: (\w+)", line)154        if m and chain is not None:155            chain["xprv"] = m.group(1)156        m = re.match(r"\* (x(?:pub|prv)\w+|D\w{100,}) \((.+)\)", line)157        if m:158            invalid.append({"key": m.group(1), "reason": m.group(2)})159    vectors = [v for v in vectors if v["chains"]]160    return {"vectors": vectors, "invalid": invalid}161162163def rfc8032_vectors(text: str) -> dict:164    """The Ed25519 test vectors of RFC 8032 section 7.1 (pure Ed25519 only), read from the RFC text."""165    start = text.index("7.1.  Test Vectors for Ed25519\n\n")166    end = text.index("7.2.  Test Vectors for Ed25519ctx\n\n")167    vectors, current, field = [], None, None168    labels = {"SECRET KEY:": "secret_key", "PUBLIC KEY:": "public_key", "SIGNATURE:": "signature"}169    for line in text[start:end].splitlines():170        t = line.strip()171        m = re.match(r"-----TEST (.+)$", t)172        if m:173            current = {"name": m.group(1), "secret_key": "", "public_key": "", "message": "", "signature": ""}174            vectors.append(current)175            field = None176            continue177        if current is None:178            continue179        if t in labels:180            field = labels[t]181        elif t.startswith("MESSAGE (length"):182            field = "message"183            current["message_length"] = int(re.search(r"length (\d+) byte", t).group(1))184        elif t == "ALGORITHM:":185            field = None186        elif field and re.fullmatch(r"(?:[0-9a-f]{2})+", t):187            current[field] += t188    for v in vectors:189        assert len(v["secret_key"]) == 64 and len(v["public_key"]) == 64 and len(v["signature"]) == 128, v["name"]190        assert len(v["message"]) == 2 * v["message_length"], v["name"]191    return {"source": "RFC 8032 section 7.1", "vectors": vectors}192193194def slip10_ed25519_vectors(md: str) -> dict:195    """The ed25519 test vectors of slip-0010.md (seed, chains with chain code, private and public key)."""196    vectors, current, chain = [], None, None197    for line in md.splitlines():198        t = line.strip().replace("<sub>H</sub>", "'")199        m = re.match(r"#+ Test vector (\d+) for (\S+)", t)200        if m:201            current = {"vector": int(m.group(1)), "seed": "", "chains": []} if m.group(2) == "ed25519" else None202            if current is not None:203                vectors.append(current)204            chain = None205            continue206        if t.startswith("#"):207            current = None208            continue209        if current is None:210            continue211        m = re.match(r"Seed \(hex\): ([0-9a-f]+)", t)212        if m:213            current["seed"] = m.group(1)214        m = re.match(r"\* Chain (m[0-9/']*)$", t)215        if m:216            chain = {"path": m.group(1)}217            current["chains"].append(chain)218        m = re.match(r"\* (fingerprint|chain code|private|public): ([0-9a-f]+)$", t)219        if m and chain is not None:220            chain[m.group(1).replace(" ", "_")] = m.group(2)221    vectors = [v for v in vectors if v["chains"]]222    return {"source": "SLIP-0010, test vectors for ed25519", "vectors": vectors}223224225def fetch_ed25519(entries: list) -> None:226    print("Ed25519: speccheck cases, RFC 8032 section 7.1, SLIP-0010")227    url = f"{RAW}/novifinancial/ed25519-speccheck/{SPECCHECK_COMMIT}/cases.json"228    store(entries, "ed25519/speccheck-cases.json", get(url), url, SPECCHECK_COMMIT, "Apache-2.0 (novifinancial/ed25519-speccheck)", False,229          "the 12 edge cases of 'Taming the many EdDSAs' (small-order A and R, mixed orders, non-canonical S, A and R)")230    url = f"{RAW}/novifinancial/ed25519-speccheck/{SPECCHECK_COMMIT}/LICENSE"231    store(entries, "ed25519/speccheck-LICENSE", get(url), url, SPECCHECK_COMMIT, "Apache-2.0", False)232    url = "https://www.rfc-editor.org/rfc/rfc8032.txt"233    text = get(url)234    if sha(text) != RFC8032_SHA256:235        raise SystemExit("rfc8032.txt: unexpected content (SHA-256 differs from the pinned value)")236    parsed = rfc8032_vectors(text.decode())237    store(entries, "ed25519/rfc8032-ed25519-vectors.json", (json.dumps(parsed, indent=1) + "\n").encode(), url, "sha256:" + RFC8032_SHA256,238          "IETF Trust (RFC 8032, code components under the Revised BSD licence)", False,239          "section 7.1 extracted from the RFC text by fetch.py (rfc8032_vectors)")240    url = f"{RAW}/satoshilabs/slips/{SLIPS_COMMIT}/slip-0010.md"241    parsed = slip10_ed25519_vectors(get(url).decode())242    store(entries, "ed25519/slip-0010-ed25519-vectors.json", (json.dumps(parsed, indent=1) + "\n").encode(), url, SLIPS_COMMIT,243          "CC0 / MIT (satoshilabs/slips)", False, "ed25519 vectors extracted from slip-0010.md by fetch.py (slip10_ed25519_vectors)")244245246def write_manifest(entries: list) -> None:247    """Writes the manifest: the entries just fetched, plus the existing entries this run did not produce248    (files added by hand with their own entry, or groups that were not fetched)."""249    fetched = {e["path"] for e in entries}250    kept = []251    if MANIFEST.exists():252        kept = [e for e in json.loads(MANIFEST.read_text())["files"] if e["path"] not in fetched]253    MANIFEST.write_text(json.dumps({"files": kept + entries, }, indent=2) + "\n")254    print(f"MANIFEST.json: {len(kept) + len(entries)} files ({len(entries)} fetched now)")255256257def fetch(only: str = "") -> None:258    entries: list = []259    if only == "ed25519":260        url = f"{RAW}/C2SP/wycheproof/{WYCHEPROOF_COMMIT}/testvectors_v1/ed25519_test.json"261        store(entries, "wycheproof/ed25519_test.json.gz", get(url), url, WYCHEPROOF_COMMIT, "Apache-2.0", True)262        fetch_ed25519(entries)263        write_manifest(entries)264        return265    print("Wycheproof", WYCHEPROOF_COMMIT)266    for name in WYCHEPROOF_FILES:267        url = f"{RAW}/C2SP/wycheproof/{WYCHEPROOF_COMMIT}/testvectors_v1/{name}"268        store(entries, f"wycheproof/{name}.gz", get(url), url, WYCHEPROOF_COMMIT, "Apache-2.0", True)269    url = f"{RAW}/C2SP/wycheproof/{WYCHEPROOF_COMMIT}/LICENSE"270    store(entries, "wycheproof/LICENSE", get(url), url, WYCHEPROOF_COMMIT, "Apache-2.0", False)271272    print("BIP vectors")273    url = f"{RAW}/bitcoin/bips/{BIPS_COMMIT}/bip-0340/test-vectors.csv"274    store(entries, "bip/bip-0340-test-vectors.csv", get(url), url, BIPS_COMMIT, "BSD-2-Clause (BIP-340)", False)275    url = f"{RAW}/bitcoin/bips/{BIPS_COMMIT}/bip-0032.mediawiki"276    parsed = bip32_vectors(get(url).decode())277    store(entries, "bip/bip-0032-vectors.json", (json.dumps(parsed, indent=1) + "\n").encode(), url, BIPS_COMMIT,278          "BSD-2-Clause / OPL (BIP-32 text)", False, "extracted from the BIP text by fetch.py (bip32_vectors)")279    url = f"{RAW}/trezor/python-mnemonic/{MNEMONIC_COMMIT}/vectors.json"280    store(entries, "bip/bip-0039-vectors.json", get(url), url, MNEMONIC_COMMIT, "MIT (trezor/python-mnemonic)", False,281          "passphrase TREZOR, as referenced by BIP-39")282    url = f"{RAW}/sipa/bech32/{BECH32_COMMIT}/ref/python/tests.py"283    lists = python_lists(get(url).decode())284    keep = {k: v for k, v in lists.items() if k.isupper()}285    store(entries, "bip/bip-0173-0350-vectors.json", (json.dumps(keep, indent=1) + "\n").encode(), url, BECH32_COMMIT,286          "MIT (sipa/bech32 reference tests)", False, "lists extracted with ast.literal_eval from ref/python/tests.py")287288    fetch_ed25519(entries)289    write_manifest(entries)290291292def verify() -> int:293    manifest = json.loads(MANIFEST.read_text())294    bad = 0295    for e in manifest["files"]:296        p = HERE / e["path"]297        if not p.exists():298            print("MISSING", e["path"])299            bad += 1300            continue301        data = p.read_bytes()302        raw = gzip.decompress(data) if e["path"].endswith(".gz") else data303        if sha(data) != e["sha256_file"] or sha(raw) != e["sha256_raw"]:304            print("CHECKSUM MISMATCH", e["path"])305            bad += 1306    print(json.dumps({"files": len(manifest["files"]), "mismatches": bad}))307    return 1 if bad else 0308309310if __name__ == "__main__":311    if "--verify" in sys.argv:312        sys.exit(verify())313    only = [a.split("=", 1)[1] for a in sys.argv[1:] if a.startswith("--only=")]314    fetch(only[0] if only else "")315
Files main
Menu

Theme