#!/usr/bin/env python3 """CC0: successful-call output before LZ4 verification, not a production reader.""" import argparse import ctypes as C import datetime import importlib.util import json import pathlib import platform BASE = pathlib.Path(__file__).parent SPEC = importlib.util.spec_from_file_location("checksum_policy", BASE / "lz4-checksum-policy.py") P = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(P) lib, checked, require, sha = P.lib, P.checked, P.require, P.sha def decode(data, expected, block_check_offset, input_policy, capacity): require(input_policy in ("whole", "split-before-block-check"), "invalid input policy") require(type(capacity) is int and 0 < capacity <= 65536, "invalid output capacity") require(type(block_check_offset) is int and 0 < block_check_offset < len(data), "invalid checksum boundary") context = C.c_void_p() checked(lib.LZ4F_createDecompressionContext(C.byref(context), 100)) offset, output, trace, error, hint = 0, bytearray(), [], None, 1 try: for call in range(20000): end = (block_check_offset if input_policy == "split-before-block-check" and offset < block_check_offset else len(data)) incoming = data[offset:end] source = C.create_string_buffer(incoming) count = C.c_size_t(len(incoming)) target = C.create_string_buffer(capacity) size = C.c_size_t(capacity) hint = lib.LZ4F_decompress(context, target, C.byref(size), source, C.byref(count), None) if lib.LZ4F_isError(hint): error = lib.LZ4F_getErrorName(hint).decode() # Error-call buffers and counts are not usable output evidence. trace.append({"call": call + 1, "error": error}) break require(count.value <= len(incoming) and size.value <= capacity, "invalid native sizes") offset += count.value output.extend(target.raw[:size.value]) trace.append({"call": call + 1, "inputOffered": len(incoming), "inputConsumed": count.value, "outputBytes": size.value, "cumulativeInput": offset, "cumulativeOutput": len(output), "nextInputHint": hint}) if hint == 0: break require(count.value or size.value, "decoder stalled before completion") else: raise ValueError("native call budget exhausted") finally: checked(lib.LZ4F_freeDecompressionContext(context)) complete = error is None and hint == 0 prefix_exact = bytes(output) == expected[:len(output)] before_check = max((t["cumulativeOutput"] for t in trace if "error" not in t and t["cumulativeInput"] <= block_check_offset), default=0) return {"error": error, "frameComplete": complete, "successfulConsumedBytes": offset, "inputFullyConsumed": offset == len(data), "successfulCallOutputBytes": len(output), "successfulOutputSha256": sha(output), "outputPrefixExact": prefix_exact, "wholeOutputExact": bytes(output) == expected, "bytesReturnedBeforeBlockChecksum": before_check, "accepted": complete and offset == len(data) and bytes(output) == expected, "trace": trace} def run(): version = lib.LZ4_versionString().decode() require(version == "1.9.4", "this experiment targets liblz4 1.9.4 only") observations = [] for storage in ("compressed", "stored"): original, payload, offsets = P.fixture(storage) for mutation in ("clean", "payload", "block", "content"): data = bytearray(original) changed_offset = None if mutation == "clean" else (11 if mutation == "payload" else offsets[mutation]) if changed_offset is not None: data[changed_offset] ^= 1 for policy in ("whole", "split-before-block-check"): for capacity in (1024, 65536): result = decode(bytes(data), payload, offsets["block"], policy, capacity) expected_error = (None if mutation == "clean" else "ERROR_contentChecksum_invalid" if mutation == "content" else "ERROR_blockChecksum_invalid") require(result["error"] == expected_error, "unexpected verification outcome") require(result["accepted"] == (mutation == "clean"), "unexpected object acceptance") observations.append({"id": f"{storage}/{mutation}/{policy}/{capacity}", "storage": storage, "mutation": mutation, "inputPolicy": policy, "outputCapacity": capacity, "frameBytes": len(data), "frameSha256": sha(data), "payloadSha256": sha(payload), "blockChecksumOffset": offsets["block"], "changedByteOffset": changed_offset, **result}) return {"schemaVersion": 1, "generatedAt": datetime.datetime.now(datetime.timezone.utc).isoformat(), "classification": "Designed native streaming controls, not field corruption rates or a security flaw.", "environment": {"liblz4": version, "python": platform.python_version(), "platform": platform.platform()}, "method": {"payloadBytes": 8192, "outputCapacities": [1024, 65536], "verification": "Default options, block and content checks enabled; fresh context per case.", "inputPolicies": ["whole", "split-before-block-check"], "mutation": "Flip one bit in first stored/compressed payload byte or block/content checksum; clean control.", "errorAccounting": "Count successful calls only; discard all sizes/buffers on an error return.", "sourceHashes": {name: sha((BASE / name).read_bytes()) for name in ("lz4-streaming-verification.py", "lz4-checksum-policy.py", "lz4-frame-contract.py")}}, "observations": observations} def verify(receipt, replay): require(set(receipt) == set(replay), "receipt fields differ") require(receipt["environment"]["liblz4"] == replay["environment"]["liblz4"], "library differs") for key in ("schemaVersion", "classification", "method", "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__) parser.add_argument("--output", type=pathlib.Path) parser.add_argument("--verify", type=pathlib.Path) args = parser.parse_args() result = run() if args.verify: verify(json.loads(args.verify.read_text(), object_pairs_hook=P.unique_object), result) print("Exact replay: 32 native streaming-verification cases") elif args.output: args.output.write_text(json.dumps(result, indent=2) + "\n") print("Recorded 32 native streaming-verification cases") else: print(json.dumps(result, indent=2)) if __name__ == "__main__": main()