File size: 2,381 Bytes
c8beaf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env python3
"""Reassemble the nine immutable S4 transport parts after verifying each part."""

from __future__ import annotations

import argparse
import csv
import hashlib
from pathlib import Path


LOGICAL_BYTES = 66_637_933_197
LOGICAL_SHA256 = "44086cd8c71bfe5469b2d9f76a3270fc2b1fe1bf72c49c581633a9142e04a6fb"


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main() -> int:
    root = Path(__file__).resolve().parents[1]
    parser = argparse.ArgumentParser()
    parser.add_argument("--parts-dir", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--dependencies", type=Path, default=root / "dependencies" / "DEPENDENCIES.tsv")
    args = parser.parse_args()
    with args.dependencies.open("r", encoding="utf-8", newline="") as handle:
        rows = [row for row in csv.DictReader(handle, delimiter="\t") if row["component"] == "S4"]
    rows.sort(key=lambda row: row["repository_path"])
    if len(rows) != 9 or any(row["assembly_method"] != "concat_s4_v1" for row in rows):
        raise ValueError("S4 dependency lock is not the approved nine-part concat_s4_v1 layout")
    digest = hashlib.sha256()
    size = 0
    partial = args.output.with_suffix(args.output.suffix + ".partial")
    with partial.open("wb") as out:
        for row in rows:
            part = args.parts_dir / Path(row["repository_path"]).name
            if part.stat().st_size != int(row["bytes"]) or sha256_file(part) != row["sha256"]:
                raise ValueError(f"part verification failed: {part}")
            with part.open("rb") as source:
                for chunk in iter(lambda: source.read(8 * 1024 * 1024), b""):
                    out.write(chunk)
                    digest.update(chunk)
                    size += len(chunk)
    actual = digest.hexdigest()
    if size != LOGICAL_BYTES or actual != LOGICAL_SHA256:
        partial.unlink(missing_ok=True)
        raise ValueError(f"logical S4 mismatch: bytes={size}, sha256={actual}")
    partial.replace(args.output)
    print(f"PASS: {args.output} ({size:,} bytes; SHA-256 {actual})")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())