#!/usr/bin/env python3 """Independent CRC-16/CCITT-FALSE reference, written bit by bit. This file exists to cross-check the generated golden vectors. It is a fresh implementation: it uses no lookup table, no nibble table and shares no code with ``tools/generate_6400_manual.py``, ``tools/generate_mrdimm_params.py`` or ``tools/crc16_ccitt_table.py`` (the generator path). An encoder that decodes its own output is not end-to-end evidence; these frames are computed twice by two structurally different implementations. Parameters: poly 0x1021, init 0xFFFF, refin/refout false, xorout 0. Coverage: TYPE, LENGTH and PAYLOAD; the ``A5 5A`` header is not covered. Wire order: low CRC byte first. """ from __future__ import annotations from typing import Iterable PREAMBLE = b"\xA5\x5A" POLYNOMIAL = 0x1021 INITIAL = 0xFFFF def crc16_ccitt_false_bitwise(data: bytes | bytearray | Iterable[int]) -> int: """MSB-first bit-at-a-time CRC-16/CCITT-FALSE.""" crc = INITIAL for raw in data: crc ^= (int(raw) & 0xFF) << 8 for _ in range(8): if crc & 0x8000: crc = ((crc << 1) ^ POLYNOMIAL) & 0xFFFF else: crc = (crc << 1) & 0xFFFF return crc def frame_bytes(frame_type: int, payload: bytes | bytearray = b"") -> bytes: """Build ``A5 5A | TYPE | LENGTH:u8 | PAYLOAD | CRC_L | CRC_H``.""" body = bytes((frame_type & 0xFF, len(payload) & 0xFF)) + bytes(payload) crc = crc16_ccitt_false_bitwise(body) return PREAMBLE + body + crc.to_bytes(2, "little") def frame_hex(frame_type: int, payload: bytes | bytearray = b"") -> str: return frame_bytes(frame_type, payload).hex().upper() def verify_frame(frame: bytes | bytearray) -> bool: """True when a complete frame has the correct header, length and CRC.""" data = bytes(frame) if len(data) < 6 or data[:2] != PREAMBLE: return False declared = data[3] if len(data) != declared + 6: return False expected = crc16_ccitt_false_bitwise(data[2:-2]) return data[-2:] == expected.to_bytes(2, "little")