"""Fetch the pinned SingleStepTests 8088 and V20 vector corpora. The corpora are large (hundreds of megabytes of gzipped JSON each) and are hosted as ordinary files in git repositories, so this script fetches them file by file from GitHub at a pinned commit instead of cloning. Every file is verified against the git blob hash recorded in that commit's tree, which is the strongest integrity check the upstream offers (SingleStepTests publishes no archive checksums). The fetch is resumable: a file that is already present with the right hash is skipped. Usage, from the repository root: python scripts/fetch_test_vectors.py # 8088 v2 + v20, all files python scripts/fetch_test_vectors.py --corpus 8088 # one corpus python scripts/fetch_test_vectors.py --opcodes 00,01,F6.6 # a subset python scripts/fetch_test_vectors.py --count # count cases after fetching Destinations are gitignored: tests/8088_test_vectors/, tests/v20_test_vectors/, tests/8086_test_vectors/. Never commit them. """ from __future__ import annotations import argparse import gzip import hashlib import json import sys import time from dataclasses import dataclass from pathlib import Path from urllib.error import URLError from urllib.request import Request, urlopen ROOT = Path(__file__).resolve().parents[1] @dataclass(frozen=True) class Corpus: name: str repository: str # owner/repo revision: str # full commit SHA, the only thing that pins the corpus directory: str # subdirectory holding the vector files destination: Path license: str CORPORA = { # Daniel Balsom's hardware-generated 8088 suite, V2: AMD D8088 in maximum # mode on the Arduino8088 harness. Judge for the 8086 core. "8088": Corpus( name="SingleStepTests/8088 v2", repository="SingleStepTests/8088", revision="aea84484abc79d09639d855b7b0ab32bc9e4dbeb", directory="v2", destination=ROOT / "tests" / "8088_test_vectors", license="MIT", ), # Hardware-generated NEC V20 suite, native mode. Judge for the V30 # milestone (the V20 and V30 share an execution unit). "v20": Corpus( name="SingleStepTests/v20 v1_native", repository="SingleStepTests/v20", revision="9efbd02b8ec1a3aad347c2b59672ad25f3bcdb21", directory="v1_native", destination=ROOT / "tests" / "v20_test_vectors", license="MIT", ), # Hardware-generated 8086 suite: Intel P80C86A-2 (a CMOS part), 2,000 # cases per opcode. Supplemental; see docs/validation.md. "8086": Corpus( name="SingleStepTests/8086 v1", repository="SingleStepTests/8086", revision="e71c68d215a6bb8c356bd4cb3842de3bef345ca9", directory="v1", destination=ROOT / "tests" / "8086_test_vectors", license="MIT", ), } USER_AGENT = "i8086-python-fetch-test-vectors/1" def _get(url: str, timeout: int = 120) -> bytes: request = Request(url, headers={"User-Agent": USER_AGENT}) last_error: Exception | None = None for attempt in range(5): try: with urlopen(request, timeout=timeout) as response: return response.read() except (URLError, OSError) as error: # transient network errors last_error = error time.sleep(2**attempt) raise OSError(f"unable to fetch {url}: {last_error}") def _git_blob_sha1(data: bytes) -> str: digest = hashlib.sha1() digest.update(b"blob %d\0" % len(data)) digest.update(data) return digest.hexdigest() def _tree(corpus: Corpus) -> list[dict]: """Return the blobs under corpus.directory at the pinned revision.""" url = ( f"https://api.github.com/repos/{corpus.repository}" f"/git/trees/{corpus.revision}?recursive=1" ) tree = json.loads(_get(url)) if tree.get("truncated"): raise RuntimeError(f"GitHub truncated the tree listing for {corpus.name}") prefix = corpus.directory + "/" blobs = [ entry for entry in tree["tree"] if entry["type"] == "blob" and entry["path"].startswith(prefix) ] if not blobs: raise RuntimeError(f"no files under {corpus.directory!r} at {corpus.revision}") return blobs def _wanted(blobs: list[dict], corpus: Corpus, opcodes: set[str] | None) -> list[dict]: if opcodes is None: return blobs keep = [] for entry in blobs: name = entry["path"][len(corpus.directory) + 1 :] stem = name.split(".json")[0] if name == "metadata.json" or stem.upper() in opcodes: keep.append(entry) return keep def fetch(corpus: Corpus, opcodes: set[str] | None) -> tuple[int, int, int]: """Fetch the corpus; return (files fetched, files skipped, bytes fetched).""" blobs = _wanted(_tree(corpus), corpus, opcodes) corpus.destination.mkdir(parents=True, exist_ok=True) (corpus.destination / "REVISION").write_text( f"{corpus.repository} {corpus.revision} {corpus.directory}\n" ) fetched = skipped = total_bytes = 0 for index, entry in enumerate(blobs, 1): relative = entry["path"][len(corpus.directory) + 1 :] target = corpus.destination / relative if target.exists() and _git_blob_sha1(target.read_bytes()) == entry["sha"]: skipped += 1 continue url = ( f"https://raw.githubusercontent.com/{corpus.repository}" f"/{corpus.revision}/{entry['path']}" ) data = _get(url) actual = _git_blob_sha1(data) if actual != entry["sha"]: raise RuntimeError( f"{entry['path']}: blob hash mismatch, expected {entry['sha']}, got {actual}" ) target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(data) fetched += 1 total_bytes += len(data) print(f" [{index}/{len(blobs)}] {relative} {len(data):,} bytes", flush=True) return fetched, skipped, total_bytes def count_cases(corpus: Corpus) -> tuple[int, int, int]: """Return (files, cases, cycles) over every vector file present.""" files = cases = cycles = 0 for path in sorted(corpus.destination.glob("*.json.gz")): with gzip.open(path) as handle: records = json.load(handle) files += 1 cases += len(records) cycles += sum(len(record["cycles"]) for record in records) return files, cases, cycles def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument( "--corpus", choices=[*CORPORA, "all"], default="all", help="which corpus to fetch (default: 8088 and v20; 8086 only when named)", ) parser.add_argument( "--opcodes", help="comma-separated opcode file stems to fetch, e.g. 00,01,F6.6 (default: all)", ) parser.add_argument( "--count", action="store_true", help="count files, cases and cycles after fetching" ) args = parser.parse_args(argv) names = ["8088", "v20"] if args.corpus == "all" else [args.corpus] opcodes = None if args.opcodes: opcodes = {stem.strip().upper() for stem in args.opcodes.split(",") if stem.strip()} for name in names: corpus = CORPORA[name] print(f"{corpus.name} @ {corpus.revision} ({corpus.license}) -> {corpus.destination}") try: fetched, skipped, total_bytes = fetch(corpus, opcodes) except (OSError, RuntimeError) as error: print(f"failed: {error}", file=sys.stderr) return 1 print(f" fetched {fetched} files ({total_bytes:,} bytes), {skipped} already present") if args.count: files, cases, cycles = count_cases(corpus) print(f" present: {files} vector files, {cases:,} cases, {cycles:,} cycles") return 0 if __name__ == "__main__": raise SystemExit(main())