import_6400_contract.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env python3
  2. """Import generated CPLD contracts and derive Go/Python constants."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. from pathlib import Path
  8. import subprocess
  9. import sys
  10. from typing import Any
  11. ROOT = Path(__file__).resolve().parents[1]
  12. DEFAULT_SOURCE = ROOT.parent / "cpld-temperature-control/generated/6400/host-contract.json"
  13. CPLD_CLOSURE = Path("products/6400-control/source-closure.json")
  14. CPLD_COSIM_WRAPPER = Path("tests/cocotb/prod2u_6400_v1_cocotb_top.v")
  15. def json_bytes(value: Any) -> bytes:
  16. return (json.dumps(value, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode()
  17. def camel(name: str) -> str:
  18. return "".join(item.upper() if item in {"bmc", "ct", "ptc"} else item.title() for item in name.split("_"))
  19. def _validate_commit(value: str, label: str) -> str:
  20. value = value.strip().lower()
  21. if len(value) not in {40, 64} or any(ch not in "0123456789abcdef" for ch in value):
  22. raise ValueError(f"{label} must be a full hexadecimal Git object id")
  23. return value
  24. def _git_text(repo: Path, *args: str) -> str:
  25. return subprocess.run(
  26. ["git", "-C", str(repo), *args],
  27. check=True,
  28. capture_output=True,
  29. text=True,
  30. ).stdout.strip()
  31. def _source_input_paths(source: Path) -> tuple[Path, list[Path]]:
  32. source_root = source.resolve().parents[2]
  33. source_rel = source.resolve().relative_to(source_root)
  34. closure = json.loads((source_root / CPLD_CLOSURE).read_text(encoding="utf-8"))
  35. paths = [source_rel, CPLD_CLOSURE, CPLD_COSIM_WRAPPER]
  36. for value in closure["sources"]:
  37. path = Path(value)
  38. if path.is_absolute() or ".." in path.parts:
  39. raise ValueError(f"unsafe CPLD source path {value!r}")
  40. paths.append(path)
  41. unique = sorted(set(paths), key=lambda item: item.as_posix())
  42. missing = [item.as_posix() for item in unique if not (source_root / item).is_file()]
  43. if missing:
  44. raise FileNotFoundError("missing CPLD source inputs: " + ", ".join(missing))
  45. return source_root, unique
  46. def _source_input_hashes(source_root: Path, paths: list[Path]) -> dict[str, str]:
  47. return {
  48. path.as_posix(): hashlib.sha256((source_root / path).read_bytes()).hexdigest()
  49. for path in paths
  50. }
  51. def _source_input_bundle_sha256(file_hashes: dict[str, str]) -> str:
  52. return hashlib.sha256(json_bytes(file_hashes)).hexdigest()
  53. def resolve_provenance(
  54. source: Path, explicit_source_commit: str | None
  55. ) -> tuple[str, str, dict[str, str], str]:
  56. source_root, input_paths = _source_input_paths(source)
  57. package_commit = _validate_commit(_git_text(source_root, "rev-parse", "HEAD"), "package commit")
  58. source_commit = _validate_commit(
  59. explicit_source_commit or package_commit, "functional source commit"
  60. )
  61. subprocess.run(
  62. ["git", "-C", str(source_root), "cat-file", "-e", f"{source_commit}^{{commit}}"],
  63. check=True,
  64. capture_output=True,
  65. )
  66. if source_commit != package_commit:
  67. ancestor = subprocess.run(
  68. [
  69. "git",
  70. "-C",
  71. str(source_root),
  72. "merge-base",
  73. "--is-ancestor",
  74. source_commit,
  75. package_commit,
  76. ],
  77. capture_output=True,
  78. )
  79. if ancestor.returncode != 0:
  80. raise ValueError(
  81. f"functional source commit {source_commit} is not an ancestor of package commit {package_commit}"
  82. )
  83. file_hashes = _source_input_hashes(source_root, input_paths)
  84. for path in input_paths:
  85. try:
  86. committed = subprocess.run(
  87. ["git", "-C", str(source_root), "show", f"{source_commit}:{path.as_posix()}"],
  88. check=True,
  89. capture_output=True,
  90. ).stdout
  91. except subprocess.CalledProcessError as exc:
  92. raise ValueError(
  93. f"functional source commit {source_commit} does not contain {path.as_posix()}"
  94. ) from exc
  95. committed_sha = hashlib.sha256(committed).hexdigest()
  96. if committed_sha != file_hashes[path.as_posix()]:
  97. raise ValueError(
  98. f"package commit changes functional source input {path.as_posix()}: "
  99. f"source={committed_sha} package={file_hashes[path.as_posix()]}"
  100. )
  101. return (
  102. source_commit,
  103. package_commit,
  104. file_hashes,
  105. _source_input_bundle_sha256(file_hashes),
  106. )
  107. def outputs(source: Path, source_commit: str | None = None) -> dict[Path, bytes]:
  108. raw = source.read_bytes()
  109. contract = json.loads(raw)
  110. contract_sha = contract["contract_sha256"]
  111. wire = contract["wire"]
  112. snapshot = contract["snapshot"]
  113. golden_contract = contract["golden_vectors"]
  114. golden = golden_contract["frames"]
  115. source_file_sha = hashlib.sha256(raw).hexdigest()
  116. golden_raw = json_bytes(golden_contract)
  117. golden_file_sha = hashlib.sha256(golden_raw).hexdigest()
  118. (
  119. resolved_source_commit,
  120. resolved_package_commit,
  121. source_input_file_sha256,
  122. source_input_bundle_sha256,
  123. ) = resolve_provenance(source, source_commit)
  124. go_lines = [
  125. "// Code generated by tools/import_6400_contract.py; DO NOT EDIT.",
  126. "package protocol6400",
  127. "",
  128. f'const ContractSHA256 = "{contract_sha}"',
  129. f'const SourceContractFileSHA256 = "{source_file_sha}"',
  130. f'const SourceCommit = "{resolved_source_commit}"',
  131. f'const PackageCommit = "{resolved_package_commit}"',
  132. f"const SnapshotPayloadLen = {snapshot['payload_length']}",
  133. f"const CmdSetTarget byte = 0x{wire['commands']['SET_TARGET']['type']:02X}",
  134. f"const CmdGetSnapshot byte = 0x{wire['commands']['GET_SNAPSHOT']['type']:02X}",
  135. f"const CmdSetStimulus byte = 0x{wire['commands']['SET_STIMULUS']['type']:02X}",
  136. f"const RspSetTargetAck byte = 0x{wire['responses']['SET_TARGET_ACK']['type']:02X}",
  137. f"const RspGetSnapshotAck byte = 0x{wire['responses']['GET_SNAPSHOT_ACK']['type']:02X}",
  138. f"const RspSnapshotData byte = 0x{wire['responses']['SNAPSHOT_DATA']['type']:02X}",
  139. f"const RspStimulusAck byte = 0x{wire['responses']['SET_STIMULUS_ACK']['type']:02X}",
  140. f"const HostBaud = {wire['host_uart']['baud']}",
  141. f'const ProfileControl = "6400-control"',
  142. f'const ProfileIdentification = "6400-identification"',
  143. f'const ProfileSimDebug = "6400-sim-debug"',
  144. "",
  145. ]
  146. for field in snapshot["fields"]:
  147. go_lines.append(f"const Snapshot{camel(field['name'])}Offset = {field['offset']}")
  148. go_lines.extend([
  149. "",
  150. f'const GoldenSetTargetStop = "{golden["set_target_stop"].lower()}"',
  151. f'const GoldenSetTarget20 = "{golden["set_target_20"].lower()}"',
  152. f'const GoldenSetTarget70 = "{golden["set_target_70"].lower()}"',
  153. f'const GoldenGetSnapshot = "{golden["get_snapshot"].lower()}"',
  154. f'const GoldenSetTargetAck = "{golden["set_target_ack"].lower()}"',
  155. f'const GoldenGetSnapshotAck = "{golden["get_snapshot_ack"].lower()}"',
  156. f'const GoldenStimulusAck = "{golden["stimulus_ack"].lower()}"',
  157. f'const GoldenStimulusAllZeroOneSecond = "{golden["stimulus_all_zero_one_second"].lower()}"',
  158. "",
  159. ])
  160. py_lines = [
  161. '"""Generated 6400 wire and snapshot constants."""',
  162. f'CONTRACT_SHA256 = "{contract_sha}"',
  163. f'SOURCE_CONTRACT_FILE_SHA256 = "{source_file_sha}"',
  164. f'SOURCE_COMMIT = "{resolved_source_commit}"',
  165. f'PACKAGE_COMMIT = "{resolved_package_commit}"',
  166. f"SNAPSHOT_PAYLOAD_LENGTH = {snapshot['payload_length']}",
  167. f"HOST_BAUD = {wire['host_uart']['baud']}",
  168. "COMMANDS = " + repr({name: value["type"] for name, value in wire["commands"].items()}),
  169. "RESPONSES = " + repr({name: value["type"] for name, value in wire["responses"].items()}),
  170. "CANONICAL_PROFILES = " + repr(tuple(contract["canonical_profiles"])),
  171. "PROFILE_CAPABILITIES = " + repr(contract["canonical_profiles"]),
  172. "SNAPSHOT_FIELDS = " + repr({field["name"]: field for field in snapshot["fields"]}),
  173. "CHANNEL_MAP = " + repr(contract["channel_map"]["channels"]),
  174. "",
  175. ]
  176. profile_common = {
  177. "schema": "hth-6400-profile-v1",
  178. "contract_sha256": contract_sha,
  179. "source_commit": resolved_source_commit,
  180. "source_contract_file_sha256": source_file_sha,
  181. "golden_vectors_file_sha256": golden_file_sha,
  182. "serial": {"baud": wire["host_uart"]["baud"], "data_bits": 8, "parity": "N", "stop_bits": 1},
  183. "snapshot_payload_length": snapshot["payload_length"],
  184. "single_serial_owner": True,
  185. "one_outstanding_transaction": True,
  186. }
  187. production = {**profile_common, "profile_id": "6400-control", **contract["canonical_profiles"]["6400-control"]}
  188. identification = {**profile_common, "profile_id": "6400-identification", **contract["canonical_profiles"]["6400-identification"]}
  189. sim_debug = {**profile_common, "profile_id": "6400-sim-debug", **contract["canonical_profiles"]["6400-sim-debug"]}
  190. import_meta = {
  191. "schema": "hth-cpld-contract-import-v2",
  192. "source_repository": "cpld-temperature-control",
  193. "source_commit": resolved_source_commit,
  194. "package_commit": resolved_package_commit,
  195. "source_contract_file_sha256": source_file_sha,
  196. "contract_sha256": contract_sha,
  197. "golden_vectors_file_sha256": golden_file_sha,
  198. "source_input_bundle_sha256": source_input_bundle_sha256,
  199. "source_input_file_sha256": source_input_file_sha256,
  200. }
  201. return {
  202. ROOT / "contracts/6400/host-contract.json": raw,
  203. ROOT / "contracts/6400/SHA256SUMS": f"{source_file_sha} host-contract.json\n".encode(),
  204. ROOT / "generated/6400/host-contract.json": raw,
  205. ROOT / "generated/6400/golden-vectors.json": golden_raw,
  206. ROOT / "generated/6400/import-source.json": json_bytes(import_meta),
  207. ROOT / "internal/protocol6400/generated_contract.go": ("\n".join(go_lines)).encode(),
  208. ROOT / "sdk/python/hth_sdk/generated/thermal/contract.py": ("\n".join(py_lines)).encode(),
  209. ROOT / "sdk/python/hth_sdk/generated/thermal/__init__.py": b"from .contract import * # noqa: F401,F403\n",
  210. ROOT / "profiles/6400-control/profile.json": json_bytes(production),
  211. ROOT / "profiles/6400-identification/profile.json": json_bytes(identification),
  212. ROOT / "profiles/6400-sim-debug/profile.json": json_bytes(sim_debug),
  213. }
  214. def main() -> int:
  215. parser = argparse.ArgumentParser()
  216. parser.add_argument("--source", type=Path, default=DEFAULT_SOURCE)
  217. parser.add_argument(
  218. "--source-commit",
  219. help=(
  220. "Functional contract/RTL commit. It may precede the current CPLD package HEAD "
  221. "only when every bound source input is byte-identical."
  222. ),
  223. )
  224. parser.add_argument("--check", action="store_true")
  225. args = parser.parse_args()
  226. expected = outputs(args.source, args.source_commit)
  227. drift = []
  228. for path, content in expected.items():
  229. if args.check:
  230. if not path.exists() or path.read_bytes() != content:
  231. drift.append(str(path.relative_to(ROOT)))
  232. else:
  233. path.parent.mkdir(parents=True, exist_ok=True)
  234. if not path.exists() or path.read_bytes() != content:
  235. path.write_bytes(content)
  236. if drift:
  237. print("generated drift: " + ", ".join(drift), file=sys.stderr)
  238. return 1
  239. print(f"PASS: {len(expected)} imported files")
  240. return 0
  241. if __name__ == "__main__":
  242. sys.exit(main())