#!/usr/bin/env python3 # SPDX-License-Identifier: CC0-1.0 """Finite binary equations, not an LT/DNA Fountain or RaptorQ implementation.""" import argparse from datetime import datetime, timezone from functools import reduce import hashlib from itertools import combinations import json import operator from pathlib import Path import platform def validate(k, rows, rhs): if type(k) is not int or not 1 <= k <= 8: raise ValueError("k must be an integer from 1 through 8") if len(rows) != len(rhs): raise ValueError("one payload is required per equation") if any(type(r) is not int or not 0 <= r < 1 << k for r in rows): raise ValueError("coefficient masks must fit k bits") if any(type(y) is not int or not 0 <= y <= 255 for y in rhs): raise ValueError("payload symbols must be bytes") def encode(rows, source): validate(len(source), rows, [0] * len(rows)) if any(type(y) is not int or not 0 <= y <= 255 for y in source): raise ValueError("source symbols must be bytes") return [reduce(operator.xor, (v for j, v in enumerate(source) if r >> j & 1), 0) for r in rows] def eliminate(k, rows, rhs): """Exact GF(2) row operations, with byte payloads as eight parallel RHSs.""" validate(k, rows, rhs) work = [list(pair) for pair in zip(rows, rhs)] pivots = [] for column in range(k): p = next((i for i in range(len(pivots), len(work)) if work[i][0] >> column & 1), None) if p is None: continue target = len(pivots) work[target], work[p] = work[p], work[target] for i in range(len(work)): if i != target and work[i][0] >> column & 1: work[i][0] ^= work[target][0] work[i][1] ^= work[target][1] pivots.append(column) inconsistent = any(mask == 0 and value != 0 for mask, value in work) status = "inconsistent" if inconsistent else "unique" if len(pivots) == k else "underdetermined" solution = None if status == "unique": solution = [0] * k for i, column in enumerate(pivots): solution[column] = work[i][1] return {"rank": len(pivots), "status": status, "solution": solution} def peel(k, rows, rhs): """Singleton-only substitution; report contradiction separately from a stall.""" validate(k, rows, rhs) work = [list(pair) for pair in zip(rows, rhs)] known = {} while True: if any(mask == 0 and value for mask, value in work): return {"status": "inconsistent", "resolved": len(known), "solution": None} singleton = next(((mask, value) for mask, value in work if mask and mask & (mask - 1) == 0), None) if singleton is None: break mask, value = singleton known[mask.bit_length() - 1] = value for row in work: if row[0] & mask: row[0] ^= mask row[1] ^= value complete = len(known) == k return {"status": "complete" if complete else "stalled", "resolved": len(known), "solution": [known[j] for j in range(k)] if complete else None} def oracle_outputs(k, rows): """Enumerate every binary source using scalar arithmetic, not elimination.""" validate(k, rows, [0] * len(rows)) outputs = set() for source in range(1 << k): outputs.add(tuple(sum(((source // (2 ** j)) % 2) * ((row // (2 ** j)) % 2) for j in range(k)) % 2 for row in rows)) return outputs def case(name, rows, source, received=None): encoded = encode(rows, source) rhs = encoded if received is None else received solved = eliminate(len(source), rows, rhs) peeled = peel(len(source), rows, rhs) solution = solved["solution"] return {"id": name, "k": len(source), "rows": rows, "coefficientConvention": "bit j selects source byte j", "sourceHex": bytes(source).hex(), "encoded": encoded, "received": rhs, "coveredSourceSymbols": reduce(operator.or_, rows, 0).bit_count(), "equationCount": len(rows), "distinctRows": len(set(rows)), "elimination": solved, "peeling": peeled, "allReceivedEquationsSatisfied": None if solution is None else encode(rows, solution) == rhs, "matchesOriginal": None if solution is None else solution == source, "expectedSha256": hashlib.sha256(bytes(source)).hexdigest(), "recoveredSha256": None if solution is None else hashlib.sha256(bytes(solution)).hexdigest()} def scenarios(): source = [0x12, 0x34, 0x56] full = [3, 5, 7] redundant = full + [1] bad_square = encode(full, source) bad_square[0] ^= 1 bad_redundant = encode(redundant, source) bad_redundant[0] ^= 1 alternate = [source[0] ^ 1, *source[1:]] return [ case("covered-but-dependent", [3, 5, 6], source), case("duplicate-equations", [3, 5, 6, 3, 5, 6], source), case("full-rank-peeling-stall", full, source), case("singleton-unlocks", redundant, source), case("corrupted-square", full, source, bad_square), case("redundancy-detects-error", redundant, source, bad_redundant), case("coherent-error-passes-equations", redundant, source, encode(redundant, alternate)), ] def census(): records, summaries = [], [] for k in range(1, 5): counts = {"k": k, "matrices": 0, "covered": 0, "fullRank": 0, "peelingComplete": 0, "fullRankPeelingStalled": 0} for rows_tuple in combinations(range(1, 1 << k), k): rows = list(rows_tuple) solved = eliminate(k, rows, [0] * k) outputs = oracle_outputs(k, rows) if len(outputs) != 1 << solved["rank"]: raise RuntimeError("Independent image-count oracle disagrees") peeled = peel(k, rows, [0] * k) covered = reduce(operator.or_, rows, 0) == (1 << k) - 1 full = solved["rank"] == k complete = peeled["status"] == "complete" if complete and not full: raise RuntimeError("Peeling cannot complete a deficient system") row = {"k": k, "rows": rows, "covered": covered, "rank": solved["rank"], "distinctOutputs": len(outputs), "peelingResolved": peeled["resolved"]} records.append(row) counts["matrices"] += 1 counts["covered"] += int(covered) counts["fullRank"] += int(full) counts["peelingComplete"] += int(complete) counts["fullRankPeelingStalled"] += int(full and not complete) summaries.append(counts) return {"population": "Every unordered k-element subset of the nonzero k-bit coefficient rows, k=1..4; no repeated rows.", "probabilityWarning": "Enumeration counts are not DNA dropout rates or LT decoding probabilities; no soliton sampling, sequence screening or biological channel.", "summaries": summaries, "matrices": records} def results(): return {"cases": scenarios(), "census": census()} def receipt(): return {"schemaVersion": 1, "kind": "constructed finite algebra demonstration", "license": "CC0-1.0", "generatedAt": datetime.now(timezone.utc).isoformat(), "python": platform.python_version(), "sourceSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), "field": "GF(2); byte-wise XOR payloads; not real-number matrix rank", "seed": None, "results": results(), "limits": ["Not DNA Fountain, LT, RaptorQ or BFA execution or replication.", "No sequencing reads, measured abundance distribution or empirical failure rate.", "Seven deliberate cases show possibilities, not their frequency.", "The saved expected hash is an external reference in this demonstration, not authentication by itself."]} def verify(path): document = json.loads(Path(path).read_text()) expected_hash = hashlib.sha256(Path(__file__).read_bytes()).hexdigest() if document.get("sourceSha256") != expected_hash: raise ValueError("receipt source hash does not match") if document.get("results") != results(): raise ValueError("receipt results differ from a fresh calculation") if document.get("kind") != "constructed finite algebra demonstration" or document.get("schemaVersion") != 1: raise ValueError("unsupported receipt") return True def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) parser.add_argument("--verify", type=Path) args = parser.parse_args() if args.output and args.verify: parser.error("select output or verify, not both") if args.verify: verify(args.verify) print("PASS: source hash and all numerical results replay exactly") return serialized = json.dumps(receipt(), indent=2) + "\n" if args.output: args.output.write_text(serialized) else: print(serialized, end="") if __name__ == "__main__": main()