#!/usr/bin/env python3 """CC0: bounded native LZ4 prefix-read controls, not a benchmark or security test.""" import argparse import ctypes as C import ctypes.util import datetime import hashlib import json import pathlib import platform TARGETS = (0, 16, 64, 96) CAPACITY = 128 def require(condition, message): if not condition: raise ValueError(message) def sha(data): return hashlib.sha256(data).hexdigest() def unique_object(pairs): result = {} for key, value in pairs: require(key not in result, "duplicate JSON key: " + key) result[key] = value return result def fixtures(): first, last = bytes(range(32, 64)), bytes(range(65, 97)) # 32 literals, a 32-byte match at offset 32, then 32 final literals. clean = b"\xff\x11" + first + b"\x20\x00\x0d\xf0\x11" + last return first + first + last, { "clean": clean, "truncated-literal": clean[:-1], "trailing-byte": clean + b"\x00", "changed-literal": clean[:-1] + bytes([clean[-1] ^ 1]), "out-of-history-offset": clean[:34] + b"\x00\x01" + clean[36:], } def library(): name = ctypes.util.find_library("lz4") require(name is not None, "installed liblz4 required; no automatic install") lib = C.CDLL(name) lib.LZ4_versionString.restype = C.c_char_p require(lib.LZ4_versionString() == b"1.9.4", "record other versions separately") lib.LZ4_decompress_safe.argtypes = [C.c_void_p, C.c_void_p, C.c_int, C.c_int] lib.LZ4_decompress_safe.restype = C.c_int lib.LZ4_decompress_safe_partial.argtypes = [C.c_void_p, C.c_void_p, C.c_int, C.c_int, C.c_int] lib.LZ4_decompress_safe_partial.restype = C.c_int return lib def decode(lib, data, target=None): require(type(data) is bytes and 0 < len(data) <= 128, "bounded byte input required") require(target is None or (type(target) is int and target in TARGETS), "invalid target") source, destination = C.create_string_buffer(data), C.create_string_buffer(CAPACITY) if target is None: count = lib.LZ4_decompress_safe(source, destination, len(data), CAPACITY) else: count = lib.LZ4_decompress_safe_partial(source, destination, len(data), target, CAPACITY) require(count <= (CAPACITY if target is None else target), "output bound violated") output = None if count < 0 else destination.raw[:count] return {"returnCode": count, "outputBytes": None if output is None else len(output), "outputSha256": None if output is None else sha(output)}, output def run(): lib = library() expected, cases = fixtures() rows, full_rows = [], [] for name, data in cases.items(): full, output = decode(lib, data) full["exactExpectedObject"] = output == expected require((full["returnCode"] >= 0) == (name in ("clean", "changed-literal")), "unexpected full-decoder result") require(full["exactExpectedObject"] == (name == "clean"), "full identity control") full_rows.append({"variant": name, **full}) for target in TARGETS: result, output = decode(lib, data, target) row = {"id": f"{name}/{target}", "variant": name, "targetOutputBytes": target, "inputBytes": len(data), "inputSha256": sha(data), **result, "targetReached": result["returnCode"] == target, "exactExpectedPrefix": output == expected[:target], "exactExpectedObject": output == expected} expected_count = (-38 if name == "out-of-history-offset" and target >= 64 else 95 if name == "truncated-literal" and target == 96 else target) require(result["returnCode"] == expected_count, "unexpected partial-decoder result") require(row["exactExpectedPrefix"] == (expected_count == target and not (name == "changed-literal" and target == 96)), "prefix identity control") rows.append(row) return {"schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "classification": "Designed native API observations; not a benchmark, corruption rate or vulnerability.", "environment": {"liblz4": lib.LZ4_versionString().decode(), "python": platform.python_version(), "platform": platform.platform()}, "method": {"targets": list(TARGETS), "destinationCapacity": CAPACITY, "expectedBytes": len(expected), "expectedSha256": sha(expected), "fixtureHex": {name: data.hex() for name, data in cases.items()}, "harnessSha256": sha(pathlib.Path(__file__).read_bytes()), "scope": "Five raw-block variants, five full calls and twenty independent partial calls. No frames, dictionaries, checksums or streaming resume. Negative-return buffers excluded.", "acceptance": "Prefix equality is reported separately from full object identity and full-decoder structural acceptance. No consumed-input count is available from these APIs.", "limits": "One installed liblz4 1.9.4 build. All partial targets <=96, including oversized-input control. Replays on this host are not independent replications."}, "fullObservations": full_rows, "observations": rows} def verify(receipt, replay): require(type(receipt) is dict and set(receipt) == set(replay), "receipt fields differ") require(type(receipt["environment"]) is dict and receipt["environment"].get("liblz4") == replay["environment"]["liblz4"], "library differs") for key in ("schemaVersion", "classification", "method", "fullObservations", "observations"): require(json.dumps(receipt[key], sort_keys=True, allow_nan=False) == json.dumps(replay[key], sort_keys=True, allow_nan=False), key + " differs") def main(): parser = argparse.ArgumentParser(description=__doc__) group = parser.add_mutually_exclusive_group() group.add_argument("--output", type=pathlib.Path) group.add_argument("--verify", type=pathlib.Path) args = parser.parse_args() observed = run() if args.verify: verify(json.loads(args.verify.read_text(), object_pairs_hook=unique_object), observed) print("Exact replay: 20 partial calls and 5 full-decoder controls") elif args.output: args.output.write_text(json.dumps(observed, indent=2) + "\n") print("Recorded 20 partial calls and 5 full-decoder controls") else: print(json.dumps(observed, indent=2)) if __name__ == "__main__": main()