SPB Git

spb/wp34_uqo

Public
2.4 KB · 86 lines python
1"""Shared helpers for the reduced-round SHA-256 experiments (Axis C of WP34).23Nothing here modifies the reference implementation `wp34.sha256`; it is imported as ground truth.4"""5from __future__ import annotations6import hashlib, os, pathlib, resource, struct, sys, time78ROOT = pathlib.Path(__file__).resolve().parents[2]9SRC = ROOT / "src"10if str(SRC) not in sys.path:11    sys.path.insert(0, str(SRC))1213from wp34 import sha256 as S  # noqa: E40214from wp34 import provenance  # noqa: E4021516MASK = 0xFFFFFFFF171819def peak_rss_mb(children: bool = False) -> float:20    """Peak resident set size in MiB (macOS reports bytes, Linux kilobytes)."""21    who = resource.RUSAGE_CHILDREN if children else resource.RUSAGE_SELF22    v = resource.getrusage(who).ru_maxrss23    if sys.platform == "darwin":24        return round(v / 2**20, 1)25    return round(v / 2**10, 1)262728def random_block(rng) -> bytes:29    return bytes(rng.getrandbits(8) for _ in range(64))303132def state_to_int(state) -> int:33    v = 034    for w in state:35        v = (v << 32) | (w & MASK)36    return v373839def int_to_bits(v: int, n: int) -> list[int]:40    """Bit list, index 0 = most significant bit of the n-bit integer (so index 0 = bit 31 of word a)."""41    return [(v >> (n - 1 - i)) & 1 for i in range(n)]424344def random_oracle(salt: bytes, msg: bytes) -> int:45    """256-bit 'random oracle' negative control: SHA-256 (hashlib) over a secret salt and the input."""46    return int.from_bytes(hashlib.sha256(salt + msg).digest(), "big")474849def hamming(v: int) -> int:50    return bin(v).count("1")515253def words_hex(words) -> str:54    return "".join("%08x" % (w & MASK) for w in words)555657def block_hex(block: bytes) -> str:58    return block.hex()596061def bootstrap_ci(values, rng, n_boot: int = 2000, alpha: float = 0.05):62    """Bootstrap percentile CI of the mean (floats are fine: statistics only)."""63    import statistics64    vals = list(values)65    if len(vals) < 2:66        return [None, None]67    means = []68    n = len(vals)69    for _ in range(n_boot):70        means.append(sum(vals[rng.randrange(n)] for _ in range(n)) / n)71    means.sort()72    lo = means[int(alpha / 2 * n_boot)]73    hi = means[min(n_boot - 1, int((1 - alpha / 2) * n_boot))]74    return [lo, hi]757677def mean_sd(values):78    vals = list(values)79    if not vals:80        return None, None81    m = sum(vals) / len(vals)82    if len(vals) < 2:83        return m, 0.084    var = sum((x - m) ** 2 for x in vals) / (len(vals) - 1)85    return m, var ** 0.586
Files · 838777af38d0770ebe997649ab0bf1629f7324d5
Menu

Theme