"""Identical I/O and hashing primitives shared by the attack engines.""" from __future__ import annotations import hashlib import json import os from pathlib import Path import tempfile import time from typing import Any def atomic_json(path: Path, value: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as handle: json.dump(value, handle, ensure_ascii=False, indent=2) handle.write("\n") temporary = Path(handle.name) os.replace(temporary, path) def atomic_bytes(path: Path, value: bytes, mode: int | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile("wb", dir=path.parent, delete=False) as handle: handle.write(value) temporary = Path(handle.name) if mode is not None: os.chmod(temporary, mode) os.replace(temporary, path) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def sha256_json(value: Any) -> str: return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()).hexdigest() def utc_stamp() -> str: return time.strftime("%Y%m%d-%H%M%S", time.gmtime())