#!/usr/bin/env python3 """Native zlib CRC-32 concatenation replay; no storage benchmark.""" import argparse import ctypes import ctypes.util import json from pathlib import Path ALGORITHM = "CRC-32/ISO-HDLC (zlib)" MAX_LENGTH = (1 << 63) - 1 def integer(value, maximum, name): if type(value) is not int or not 0 <= value <= maximum: raise ValueError(name + " must be an integer in range") class NativeCRC: def __init__(self): library = ctypes.util.find_library("z") if not library: raise RuntimeError("A system zlib with crc32_combine64 is required") self.library = library self.lib = ctypes.CDLL(library) self.lib.zlibVersion.restype = ctypes.c_char_p self.version = self.lib.zlibVersion().decode("ascii") self.lib.crc32.argtypes = [ctypes.c_ulong, ctypes.c_void_p, ctypes.c_uint] self.lib.crc32.restype = ctypes.c_ulong self.lib.crc32_combine64.argtypes = [ ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int64 ] self.lib.crc32_combine64.restype = ctypes.c_ulong def crc(self, data): if type(data) is not bytes or len(data) > 0xFFFFFFFF: raise ValueError("data must be bytes of at most 2^32-1 bytes") return int(self.lib.crc32(0, ctypes.c_char_p(data), len(data))) def combine(self, left, right, right_bytes): integer(left, 0xFFFFFFFF, "left CRC") integer(right, 0xFFFFFFFF, "right CRC") integer(right_bytes, MAX_LENGTH, "right byte length") if right_bytes == 0 and right != 0: raise ValueError("an empty right segment must have CRC zero") return int(self.lib.crc32_combine64(left, right, right_bytes)) def bitwise_crc(data): """Independent, reflected bit-at-a-time oracle, not zlib's combine code.""" state = 0xFFFFFFFF for byte in data: state ^= byte for _ in range(8): state = (state >> 1) ^ (0xEDB88320 if state & 1 else 0) return state ^ 0xFFFFFFFF def probe(native): payload = b"123456789" expected = native.crc(payload) if expected != 0xCBF43926 or bitwise_crc(payload) != expected: raise RuntimeError("CRC-32 known-answer check failed") rows = [] for first in range(len(payload) + 1): for second in range(first, len(payload) + 1): a, b, c = payload[:first], payload[first:second], payload[second:] ca, cb, cc = (native.crc(part) for part in (a, b, c)) left = native.combine(native.combine(ca, cb, len(b)), cc, len(c)) right = native.combine(ca, native.combine(cb, cc, len(c)), len(b) + len(c)) if left != expected or right != expected: raise RuntimeError("segmentation or grouping changed CRC") rows.append({"lengthsBytes": [len(a), len(b), len(c)], "leftGrouped": f"{left:08x}", "rightGrouped": f"{right:08x}"}) a, b = b"1234", b"56789" ca, cb = native.crc(a), native.crc(b) controls = { "xorPartChecksums": ca ^ cb, "wrongRightLength4": native.combine(ca, cb, 4), "reversedParts": native.combine(cb, ca, len(a)), "crcOfBigEndianDigestBytes": native.crc(ca.to_bytes(4, "big") + cb.to_bytes(4, "big")), "runningInsteadOfIndependentRight": native.combine(ca, expected, len(b)), } if any(value == expected for value in controls.values()): raise RuntimeError("a selected negative control no longer differs") return { "schemaVersion": 1, "kind": "deterministic native-library replay", "algorithm": ALGORITHM, "payloadAscii": payload.decode("ascii"), "payloadHex": payload.hex(), "fullCRC32Hex": f"{expected:08x}", "partExample": {"leftAscii": a.decode(), "rightAscii": b.decode(), "leftCRC32Hex": f"{ca:08x}", "rightCRC32Hex": f"{cb:08x}", "rightLengthBytes": len(b)}, "layouts": rows, "layoutCount": len(rows), "negativeControls": {key: f"{value:08x}" for key, value in controls.items()}, "limits": [ "No throughput, storage-device, cloud-service or collision-frequency measurement.", "The checksum family is IEEE CRC-32, not CRC-32C.", "Agreement requires accurate segment lengths, order and checksums from one byte sequence.", "The finite replay is not a proof that every changed message has a different CRC." ] } def main(): parser = argparse.ArgumentParser() parser.add_argument("--write", action="store_true") parser.add_argument("--check", action="store_true") args = parser.parse_args() if args.write and args.check: parser.error("choose --write or --check") native = NativeCRC() result = probe(native) path = Path(__file__).with_name("results.json") if args.write: path.write_text(json.dumps(result, indent=2) + "\n") elif args.check and json.loads(path.read_text()) != result: raise RuntimeError("published results differ from native replay") print(json.dumps({"passed": True, "zlibVersion": native.version, "library": native.library, "layouts": result["layoutCount"], "resultsChecked": args.check})) if __name__ == "__main__": main()