#!/usr/bin/env python3
"""
ONE BIG BACKEND — SHIELD 3: INFORMATION-THEORETIC DARK-FIBER CHANNEL (v2 HARDENED)
(`obb_info_theoretic_channel.py`)
License: GNU AGPLv3
External Dependencies: 0 (100% Python Standard Library + local `obb_primitives` & `obb_epistemic_lattice`)

Zero computational hardness assumptions on wire confidentiality and bilateral integrity.
Designed for fixed-topology regional municipal dark-fiber meshes (e.g., Roanoke Valley
Broadband Authority / RVBA anchor hubs).

v2 Security & Protocol Fixes (vs. v1):
  1. FIXES 1-PACKET PRE-MAC PAD-WIPE DoS:
     - Partitions each directional pad into strictly disjoint OTP and MAC-key sub-tapes.
     - Enforces `32 <= mac_pad_len <= 64` (multiple of 16), `otp_len <= max_msg_bytes`,
       and sliding receive-window bounds BEFORE touching the pad.
     - Uses peek-then-verify MAC before burning pad material, with a bounded retry budget
       (`max_failed_mac_attempts = 3`) before quarantining a 32-byte MAC slot and firing a
       link-tamper alert (limits forgery risk to <= 3k/(p-1) while stopping 1-packet DoS).
  2. CRASH-SAFE WRITE-AHEAD BURN-BEFORE-SEND (WABBS):
     - Optional `FileBackedPadStore` persists monotonic cursors + consumed intervals via
       atomic temp-file + `os.fsync()` BEFORE returning pad material for transmission,
       preventing catastrophic two-time pad reuse across server crashes/reboots.
  3. NON-ZERO UNIVERSAL HASH KEY:
     - Draws `r in F_p*` (strictly `1 <= r < 2^127 - 1`) and `s in F_p` via rejection sampling.
  4. ACTIVE-CHEATER DETECTION IN `ShamirQuorum`:
     - When > t shares are presented, verifies EVERY share lies on the unique degree-(t-1)
       polynomial (Reed-Solomon consistency check), raising `QuorumCorruptionError` instead
       of silently discarding extra shares.
  5. HONEST NON-REPUDIATION SCOPE:
     - Wegman-Carter MAC is symmetric (bilateral authenticity, not third-party non-repudiation).
       For legal non-repudiation in Algorithmica, see Unconditionally Secure Signatures
       (Chaum-Roijakkers 1990; Hanaoka-Shikata-Zheng-Imai 2000).
"""

from __future__ import annotations

import hmac
import json
import math
import os
import secrets
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple

from obb_epistemic_lattice import (
    EpistemicBoundaryError,
    EpistemicClaim,
    EpistemicTruth,
    SourceKind,
    SweetbrierEpistemicGate,
)
from obb_primitives import ObbSafetyFloor, StateSnapshot

MERSENNE_P: int = (1 << 127) - 1
FIELD_MASK_127: int = (1 << 127) - 1
BLOCK_BYTES: int = 15
BLOCK_SENTINEL: int = 1 << 120
MAX_MAC_PAD_BYTES: int = 64
DEFAULT_MAX_MSG_BYTES: int = 65536
DEFAULT_WINDOW_BYTES: int = 262144  # 256 KiB sliding window
DEFAULT_MAX_MAC_FAILURES: int = 3


class PadExhaustedError(RuntimeError):
    """Raised when a pre-shared One-Time Pad book does not have enough unused bytes left."""


class PadReuseError(PermissionError):
    """Raised immediately if an envelope attempts to reuse or replay an already-burned OTP slice."""


class InfoTheoreticSecurityError(PermissionError):
    """Raised when a Wegman-Carter MAC, window bound, or envelope length fails verification."""


class QuorumThresholdError(ValueError):
    """Raised when fewer than `t` valid distinct Shamir witness shares are presented."""


class QuorumCorruptionError(PermissionError):
    """Raised when extra Shamir shares fail degree-(t-1) polynomial consistency (corrupted share)."""


# =============================================================================
# 1. CRASH-SAFE PERSISTENT CURSOR STORE & DISJOINT ONE-TIME PAD BOOK
# =============================================================================


class FileBackedPadStore:
    """
    Crash-safe atomic JSON state persistence (write-ahead fsync BEFORE transmission).
    Guarantees a process crash or reboot cannot reset pad cursors to 0 (no two-time pad).
    """

    def __init__(self, state_path: str) -> None:
        self.state_path = state_path

    def load(self) -> Optional[Dict[str, Any]]:
        if not os.path.exists(self.state_path):
            return None
        with open(self.state_path, "r", encoding="utf-8") as fh:
            return json.load(fh)

    def save_atomic(self, state: Mapping[str, Any]) -> None:
        tmp_path = f"{self.state_path}.tmp.{os.getpid()}"
        payload = json.dumps(state, sort_keys=True)
        with open(tmp_path, "w", encoding="utf-8") as fh:
            fh.write(payload)
            fh.flush()
            os.fsync(fh.fileno())
        os.replace(tmp_path, self.state_path)


class OneTimePadBook:
    """
    Single-direction pre-shared One-Time Pad book partitioned into two strictly disjoint
    sub-tapes:
      - OTP ciphertext tape : [0, otp_limit)
      - MAC key tape        : [otp_limit, total_len)

    Enforces non-overlapping burn-after-read zeroization, bounded sliding receive windows,
    peek-then-burn MAC verification, and optional crash-safe fsync persistence.
    """

    def __init__(
        self,
        pad_id: str,
        raw_pad_bytes: bytes,
        mac_tape_fraction: float = 0.125,
        state_store: Optional[FileBackedPadStore] = None,
        window_bytes: int = DEFAULT_WINDOW_BYTES,
        max_msg_bytes: int = DEFAULT_MAX_MSG_BYTES,
        max_mac_failures: int = DEFAULT_MAX_MAC_FAILURES,
    ) -> None:
        if len(raw_pad_bytes) < 512:
            raise ValueError("OneTimePadBook requires at least 512 bytes of random pad material.")
        if not (0.05 <= mac_tape_fraction <= 0.5):
            raise ValueError("mac_tape_fraction must lie in [0.05, 0.5].")

        self.pad_id = pad_id
        self._tape = bytearray(raw_pad_bytes)
        self._total_len = len(raw_pad_bytes)
        # Align MAC tape boundary to 16-byte blocks
        mac_len = max(128, (int(self._total_len * mac_tape_fraction) // 16) * 16)
        self._otp_limit = self._total_len - mac_len
        self._mac_start = self._otp_limit

        self._otp_cursor: int = 0
        self._mac_cursor: int = self._mac_start
        self._consumed_otp: List[Tuple[int, int]] = []
        self._consumed_mac: List[Tuple[int, int]] = []
        self._mac_fail_counts: Dict[Tuple[int, int], int] = {}

        self._window_bytes = window_bytes
        self._max_msg_bytes = max_msg_bytes
        self._max_mac_failures = max_mac_failures
        self._state_store = state_store

        if self._state_store is not None:
            saved = self._state_store.load()
            if saved is not None:
                if saved.get("pad_id") != self.pad_id:
                    raise ValueError("State store pad_id mismatch.")
                self._otp_cursor = int(saved["otp_cursor"])
                self._mac_cursor = int(saved["mac_cursor"])
                self._consumed_otp = [tuple(x) for x in saved["consumed_otp"]]
                self._consumed_mac = [tuple(x) for x in saved["consumed_mac"]]
                for s, e in self._consumed_otp + self._consumed_mac:
                    self._zeroize(s, e)

    @classmethod
    def create_paired_books(
        cls,
        pad_id: str,
        size_bytes: int = 65536,
        trng_bytes: Optional[bytes] = None,
        sender_store: Optional[FileBackedPadStore] = None,
        receiver_store: Optional[FileBackedPadStore] = None,
    ) -> Tuple["OneTimePadBook", "OneTimePadBook"]:
        raw = trng_bytes if trng_bytes is not None else secrets.token_bytes(size_bytes)
        return (
            cls(pad_id, raw, state_store=sender_store),
            cls(pad_id, raw, state_store=receiver_store),
        )

    @property
    def total_bytes(self) -> int:
        return self._total_len

    @property
    def otp_limit(self) -> int:
        return self._otp_limit

    @property
    def mac_start(self) -> int:
        return self._mac_start

    @property
    def remaining_bytes(self) -> int:
        used = sum(e - s for s, e in self._consumed_otp) + sum(e - s for s, e in self._consumed_mac)
        return self._total_len - used

    def _zeroize(self, start: int, end: int) -> None:
        for idx in range(start, end):
            self._tape[idx] = 0

    def _persist(self) -> None:
        if self._state_store is not None:
            self._state_store.save_atomic(
                {
                    "pad_id": self.pad_id,
                    "otp_cursor": self._otp_cursor,
                    "mac_cursor": self._mac_cursor,
                    "consumed_otp": self._consumed_otp,
                    "consumed_mac": self._consumed_mac,
                }
            )

    @staticmethod
    def _assert_no_overlap(
        intervals: Sequence[Tuple[int, int]], start: int, end: int, pad_id: str
    ) -> None:
        for c_start, c_end in intervals:
            if start < c_end and c_start < end:
                raise PadReuseError(
                    f"OTP/MAC REUSE BLOCKED on pad '{pad_id}': slice [{start}, {end}) "
                    f"overlaps already-burned slice [{c_start}, {c_end})."
                )

    def consume_next_otp(self, n_bytes: int) -> Tuple[int, bytes]:
        if n_bytes <= 0 or n_bytes > self._max_msg_bytes:
            raise ValueError(f"OTP request length {n_bytes} outside (0, {self._max_msg_bytes}].")
        start = self._otp_cursor
        end = start + n_bytes
        if end > self._otp_limit:
            raise PadExhaustedError(f"OTP sub-tape exhausted on '{self.pad_id}'.")
        self._assert_no_overlap(self._consumed_otp, start, end, self.pad_id)
        out = bytes(self._tape[start:end])
        self._consumed_otp.append((start, end))
        self._otp_cursor = end
        # Write-Ahead Burn-Before-Send: persist & zeroize BEFORE returning key bytes
        self._persist()
        self._zeroize(start, end)
        return start, out

    def draw_uniform_field_pair(self) -> Tuple[int, int, int, int]:
        """
        Draw strictly uniform (r, s) in F_p* x F_p (r != 0) from the disjoint MAC-key sub-tape.
        Caps slice consumption at MAX_MAC_PAD_BYTES (64 B).
        """
        start = self._mac_cursor
        cursor = start
        vals: List[int] = []
        while len(vals) < 2:
            if cursor + 16 > self._total_len:
                raise PadExhaustedError(f"MAC sub-tape exhausted on '{self.pad_id}'.")
            if (cursor + 16) - start > MAX_MAC_PAD_BYTES:
                raise PadExhaustedError("MAC rejection sampling exceeded MAX_MAC_PAD_BYTES.")
            chunk = bytes(self._tape[cursor : cursor + 16])
            cursor += 16
            candidate = int.from_bytes(chunk, "big") & FIELD_MASK_127
            if len(vals) == 0:
                if 1 <= candidate < MERSENNE_P:  # r in F_p* (strictly non-zero)
                    vals.append(candidate)
            else:
                if candidate < MERSENNE_P:  # s in F_p
                    vals.append(candidate)
        end = cursor
        self._assert_no_overlap(self._consumed_mac, start, end, self.pad_id)
        self._consumed_mac.append((start, end))
        self._mac_cursor = end
        self._persist()
        self._zeroize(start, end)
        return vals[0], vals[1], start, end - start

    def peek_mac_pair(self, mac_offset: int, mac_len: int) -> Tuple[int, int]:
        """
        Validate bounds and peek (r, s) WITHOUT burning the pad yet (prevents 1-packet wipe DoS).
        """
        if mac_len < 32 or mac_len > MAX_MAC_PAD_BYTES or (mac_len % 16) != 0:
            raise InfoTheoreticSecurityError(
                f"Rejected invalid mac_pad_len={mac_len} (must be multiple of 16 in [32, {MAX_MAC_PAD_BYTES}])."
            )
        end = mac_offset + mac_len
        if mac_offset < self._mac_start or end > self._total_len:
            raise InfoTheoreticSecurityError("mac_pad_offset outside disjoint MAC sub-tape.")
        if mac_offset > self._mac_cursor + self._window_bytes:
            raise InfoTheoreticSecurityError("mac_pad_offset exceeds sliding receive window.")
        self._assert_no_overlap(self._consumed_mac, mac_offset, end, self.pad_id)

        pad_slice = bytes(self._tape[mac_offset:end])
        vals: List[int] = []
        for idx in range(0, len(pad_slice), 16):
            candidate = int.from_bytes(pad_slice[idx : idx + 16], "big") & FIELD_MASK_127
            if len(vals) == 0:
                if 1 <= candidate < MERSENNE_P:
                    vals.append(candidate)
            elif candidate < MERSENNE_P:
                vals.append(candidate)
                return vals[0], vals[1]
        raise InfoTheoreticSecurityError("MAC pad slice did not contain valid (r, s) in F_p* x F_p.")

    def record_mac_failure(self, mac_offset: int, mac_len: int) -> bool:
        """
        Track failed MAC attempts against a specific MAC slot; permanently quarantine/burn
        ONLY after `max_mac_failures` attempts (default 3). Returns True if slot was quarantined.
        """
        slot = (mac_offset, mac_offset + mac_len)
        count = self._mac_fail_counts.get(slot, 0) + 1
        self._mac_fail_counts[slot] = count
        if count >= self._max_mac_failures:
            self._consumed_mac.append(slot)
            if slot[1] > self._mac_cursor:
                self._mac_cursor = slot[1]
            self._persist()
            self._zeroize(slot[0], slot[1])
            self._mac_fail_counts.pop(slot, None)
            return True
        return False

    def commit_receive_burn(
        self, mac_offset: int, mac_len: int, otp_offset: int, otp_len: int
    ) -> bytes:
        """
        Called ONLY AFTER Wegman-Carter MAC verification succeeds.
        Validates OTP slice bounds, atomically burns BOTH MAC and OTP slices, and returns OTP key.
        """
        if otp_len <= 0 or otp_len > self._max_msg_bytes:
            raise InfoTheoreticSecurityError(f"otp_len={otp_len} outside (0, {self._max_msg_bytes}].")
        otp_end = otp_offset + otp_len
        mac_end = mac_offset + mac_len
        if otp_offset < 0 or otp_end > self._otp_limit:
            raise InfoTheoreticSecurityError("otp_offset outside disjoint OTP sub-tape.")
        if otp_offset > self._otp_cursor + self._window_bytes:
            raise InfoTheoreticSecurityError("otp_offset exceeds sliding receive window.")
        self._assert_no_overlap(self._consumed_mac, mac_offset, mac_end, self.pad_id)
        self._assert_no_overlap(self._consumed_otp, otp_offset, otp_end, self.pad_id)

        otp_key = bytes(self._tape[otp_offset:otp_end])
        self._consumed_mac.append((mac_offset, mac_end))
        self._consumed_otp.append((otp_offset, otp_end))
        if mac_end > self._mac_cursor:
            self._mac_cursor = mac_end
        if otp_end > self._otp_cursor:
            self._otp_cursor = otp_end
        self._mac_fail_counts.pop((mac_offset, mac_end), None)
        self._persist()
        self._zeroize(mac_offset, mac_end)
        self._zeroize(otp_offset, otp_end)
        return otp_key

    @staticmethod
    def xor_bytes(data: bytes, key: bytes) -> bytes:
        if len(data) != len(key):
            raise ValueError(f"OTP length mismatch: data={len(data)} B vs key={len(key)} B.")
        return bytes(a ^ b for a, b in zip(data, key))

    @staticmethod
    def estimate_drive_longevity_years(
        drive_terabytes: float = 1.0,
        messages_per_day: int = 500,
        avg_message_bytes: int = 512,
        mac_key_bytes_per_msg: int = 32,
    ) -> float:
        total_bytes = drive_terabytes * 1e12
        bytes_per_day = messages_per_day * (avg_message_bytes + mac_key_bytes_per_msg)
        return round(total_bytes / (bytes_per_day * 365.25), 1)


# =============================================================================
# 2. WEGMAN-CARTER UNIVERSAL-HASH MAC OVER F_(2^127 - 1)
# =============================================================================


class WegmanCarterMac:
    """Polynomial universal-hash authenticator over F_p (p = 2^127 - 1) with one-time mask s."""

    @staticmethod
    def encode_message_blocks(message: bytes) -> List[int]:
        blocks: List[int] = []
        for idx in range(0, len(message), BLOCK_BYTES):
            chunk = message[idx : idx + BLOCK_BYTES]
            blocks.append(int.from_bytes(chunk, "big") | BLOCK_SENTINEL)
        blocks.append(len(message) % MERSENNE_P)
        return blocks

    @classmethod
    def forgery_probability_bound(cls, message_len_bytes: int) -> float:
        k = max(1, math.ceil(message_len_bytes / BLOCK_BYTES)) + 1
        return k / float(MERSENNE_P - 1)

    @classmethod
    def compute_tag(cls, message: bytes, r: int, s: int) -> bytes:
        if not (1 <= r < MERSENNE_P and 0 <= s < MERSENNE_P):
            raise ValueError("Wegman-Carter key must satisfy r in F_p* and s in F_p.")
        blocks = cls.encode_message_blocks(message)
        acc = 0
        for coeff in reversed(blocks):
            acc = ((acc + coeff) * r) % MERSENNE_P
        tag_int = (acc + s) % MERSENNE_P
        return tag_int.to_bytes(16, "big")

    @classmethod
    def verify_tag(cls, message: bytes, r: int, s: int, observed_tag: bytes) -> bool:
        expected = cls.compute_tag(message, r, s)
        return hmac.compare_digest(expected, observed_tag)


# =============================================================================
# 3. SHAMIR t-OF-n QUORUM WITH REED-SOLOMON ACTIVE-CHEATER DETECTION
# =============================================================================


@dataclass(frozen=True)
class WitnessShare:
    quorum_id: str
    anchor_name: str
    x_index: int
    threshold_t: int
    total_n: int
    secret_byte_len: int
    y_blocks: Tuple[int, ...]


class ShamirQuorum:
    """
    Shamir t-of-n Secret Sharing over F_(2^127 - 1) with automatic Reed-Solomon consistency
    checking whenever > t shares are submitted (catches corrupted/malicious shares).
    """

    @staticmethod
    def _eval_poly(coeffs: Sequence[int], x: int) -> int:
        acc = 0
        for c in reversed(coeffs):
            acc = (acc * x + c) % MERSENNE_P
        return acc

    @staticmethod
    def _lagrange_eval_at(points: Sequence[Tuple[int, int]], x_target: int) -> int:
        acc = 0
        k = len(points)
        for i in range(k):
            xi, yi = points[i]
            num = 1
            den = 1
            for j in range(k):
                if i == j:
                    continue
                xj = points[j][0]
                num = (num * ((x_target - xj) % MERSENNE_P)) % MERSENNE_P
                den = (den * ((xi - xj) % MERSENNE_P)) % MERSENNE_P
            acc = (acc + yi * num * pow(den, -1, MERSENNE_P)) % MERSENNE_P
        return acc

    @classmethod
    def split_secret(
        cls,
        quorum_id: str,
        secret_bytes: bytes,
        anchor_names: Sequence[str],
        threshold_t: int,
    ) -> List[WitnessShare]:
        n = len(anchor_names)
        if threshold_t < 2 or threshold_t > n:
            raise ValueError(f"Threshold t must satisfy 2 <= t <= n (got t={threshold_t}, n={n}).")
        if len(set(anchor_names)) != n:
            raise ValueError("All civic anchor names must be unique.")
        if not secret_bytes:
            raise ValueError("secret_bytes must be non-empty.")

        secret_blocks = [
            int.from_bytes(secret_bytes[i : i + BLOCK_BYTES], "big")
            for i in range(0, len(secret_bytes), BLOCK_BYTES)
        ]
        polys = [
            [blk] + [secrets.randbelow(MERSENNE_P) for _ in range(threshold_t - 1)]
            for blk in secret_blocks
        ]
        shares: List[WitnessShare] = []
        for idx, anchor in enumerate(anchor_names, start=1):
            y_vals = tuple(cls._eval_poly(poly, idx) for poly in polys)
            shares.append(
                WitnessShare(
                    quorum_id=quorum_id,
                    anchor_name=anchor,
                    x_index=idx,
                    threshold_t=threshold_t,
                    total_n=n,
                    secret_byte_len=len(secret_bytes),
                    y_blocks=y_vals,
                )
            )
        return shares

    @classmethod
    def reconstruct_secret(cls, shares: Sequence[WitnessShare]) -> bytes:
        if not shares:
            raise QuorumThresholdError("No witness shares provided.")
        first = shares[0]
        if len(shares) < first.threshold_t:
            raise QuorumThresholdError(
                f"Insufficient quorum: need at least {first.threshold_t} of {first.total_n} anchors."
            )

        seen_x = set()
        for sh in shares:
            if (
                sh.quorum_id != first.quorum_id
                or sh.threshold_t != first.threshold_t
                or sh.secret_byte_len != first.secret_byte_len
                or len(sh.y_blocks) != len(first.y_blocks)
            ):
                raise QuorumThresholdError("Mismatched metadata across witness shares.")
            if sh.x_index in seen_x:
                raise QuorumThresholdError(f"Duplicate witness share x_index={sh.x_index}.")
            seen_x.add(sh.x_index)

        basis = list(shares[: first.threshold_t])
        extras = list(shares[first.threshold_t :])
        out = bytearray()
        remaining = first.secret_byte_len

        for blk_idx in range(len(first.y_blocks)):
            pts = [(sh.x_index, sh.y_blocks[blk_idx]) for sh in basis]
            # Active-cheater consistency check against all extra shares (Reed-Solomon degree check)
            for extra in extras:
                expected_y = cls._lagrange_eval_at(pts, extra.x_index)
                if expected_y != extra.y_blocks[blk_idx]:
                    raise QuorumCorruptionError(
                        f"Shamir share inconsistency detected at block {blk_idx} "
                        f"(extra share '{extra.anchor_name}' x={extra.x_index} does not lie on degree-{first.threshold_t - 1} curve)."
                    )
            val = cls._lagrange_eval_at(pts, 0)
            chunk_len = min(BLOCK_BYTES, remaining)
            out.extend(val.to_bytes(chunk_len, "big"))
            remaining -= chunk_len

        return bytes(out)


# =============================================================================
# 4. ALGORITHMICA CIVIC NODE (ZERO HARDNESS ASSUMPTIONS ON THE WIRE)
# =============================================================================


@dataclass(frozen=True)
class InfoTheoreticEnvelope:
    pad_id: str
    sender_id: str
    receiver_id: str
    service_code: str
    lane: str
    otp_offset: int
    otp_len: int
    ciphertext_hex: str
    mac_pad_offset: int
    mac_pad_len: int
    wc_tag_hex: str
    max_forgery_prob_bound: float
    attestation: str = "information_theoretic_bilateral_mac"


class AlgorithmicaCivicNode:
    VALID_LANES = frozenset({"FINALIZED", "STAGED_UNCONFIRMED"})

    def __init__(
        self,
        node_id: str,
        on_tamper_alert: Optional[Callable[[str, InfoTheoreticEnvelope], None]] = None,
    ) -> None:
        self.node_id = node_id
        self.safety_floor = ObbSafetyFloor()
        self.epistemic_gate = SweetbrierEpistemicGate(node_id=node_id, safety_floor=self.safety_floor)
        self._outbound_pads: Dict[str, OneTimePadBook] = {}
        self._inbound_pads: Dict[str, OneTimePadBook] = {}
        self.received_envelopes: List[InfoTheoreticEnvelope] = []
        self.tamper_alerts: List[str] = []
        self._on_tamper_alert = on_tamper_alert

    def install_peer_pads(
        self,
        peer_node_id: str,
        outbound_pad: OneTimePadBook,
        inbound_pad: OneTimePadBook,
    ) -> None:
        self._outbound_pads[peer_node_id] = outbound_pad
        self._inbound_pads[peer_node_id] = inbound_pad

    @staticmethod
    def _auth_bytes(
        pad_id: str,
        sender_id: str,
        receiver_id: str,
        service_code: str,
        lane: str,
        otp_offset: int,
        otp_len: int,
        mac_pad_offset: int,
        mac_pad_len: int,
        ciphertext: bytes,
    ) -> bytes:
        header = json.dumps(
            {
                "pad_id": pad_id,
                "sender_id": sender_id,
                "receiver_id": receiver_id,
                "service_code": service_code,
                "lane": lane,
                "otp_offset": otp_offset,
                "otp_len": otp_len,
                "mac_pad_offset": mac_pad_offset,
                "mac_pad_len": mac_pad_len,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return header + b"\x00" + ciphertext

    def send_claim(
        self,
        peer: "AlgorithmicaCivicNode",
        service_code: str,
        claim: EpistemicClaim,
        lane: str = "FINALIZED",
    ) -> Tuple[InfoTheoreticEnvelope, StateSnapshot]:
        if lane not in self.VALID_LANES:
            raise ValueError(f"Unsupported lane '{lane}'.")
        if peer.node_id not in self._outbound_pads:
            raise KeyError(f"No pre-shared outbound OTP book installed for peer '{peer.node_id}'.")

        self.safety_floor.assert_clean(claim.payload)
        if lane == "FINALIZED":
            SweetbrierEpistemicGate.assert_commit_ready(claim)
        elif claim.truth_value is not EpistemicTruth.UNKNOWN:
            raise EpistemicBoundaryError("STAGED_UNCONFIRMED lane accepts UNKNOWN claims only.")

        pad = self._outbound_pads[peer.node_id]
        plaintext = json.dumps(claim.to_wire_dict(), sort_keys=True, separators=(",", ":")).encode("utf-8")

        otp_offset, otp_key = pad.consume_next_otp(len(plaintext))
        ciphertext = OneTimePadBook.xor_bytes(plaintext, otp_key)
        r, s, mac_offset, mac_len = pad.draw_uniform_field_pair()
        auth_blob = self._auth_bytes(
            pad.pad_id,
            self.node_id,
            peer.node_id,
            service_code,
            lane,
            otp_offset,
            len(ciphertext),
            mac_offset,
            mac_len,
            ciphertext,
        )
        tag = WegmanCarterMac.compute_tag(auth_blob, r, s)
        env = InfoTheoreticEnvelope(
            pad_id=pad.pad_id,
            sender_id=self.node_id,
            receiver_id=peer.node_id,
            service_code=service_code,
            lane=lane,
            otp_offset=otp_offset,
            otp_len=len(ciphertext),
            ciphertext_hex=ciphertext.hex(),
            mac_pad_offset=mac_offset,
            mac_pad_len=mac_len,
            wc_tag_hex=tag.hex(),
            max_forgery_prob_bound=WegmanCarterMac.forgery_probability_bound(len(auth_blob)),
        )
        snap = peer.receive_envelope(env)
        return env, snap

    def receive_envelope(self, env: InfoTheoreticEnvelope) -> StateSnapshot:
        if env.receiver_id != self.node_id:
            raise InfoTheoreticSecurityError(f"Misrouted envelope for '{env.receiver_id}'.")
        if env.sender_id not in self._inbound_pads:
            raise InfoTheoreticSecurityError(f"No pre-shared inbound OTP book for '{env.sender_id}'.")

        pad = self._inbound_pads[env.sender_id]
        if pad.pad_id != env.pad_id:
            raise InfoTheoreticSecurityError(f"Pad ID mismatch: expected '{pad.pad_id}', got '{env.pad_id}'.")

        ciphertext = bytes.fromhex(env.ciphertext_hex)
        if len(ciphertext) != env.otp_len:
            raise InfoTheoreticSecurityError("Ciphertext length mismatch.")

        # 1. Peek MAC key WITHOUT burning pad (blocks 1-packet pad-wipe & offset-desync DoS)
        r, s = pad.peek_mac_pair(env.mac_pad_offset, env.mac_pad_len)
        auth_blob = self._auth_bytes(
            env.pad_id,
            env.sender_id,
            env.receiver_id,
            env.service_code,
            env.lane,
            env.otp_offset,
            env.otp_len,
            env.mac_pad_offset,
            env.mac_pad_len,
            ciphertext,
        )
        observed_tag = bytes.fromhex(env.wc_tag_hex)
        if not WegmanCarterMac.verify_tag(auth_blob, r, s, observed_tag):
            quarantined = pad.record_mac_failure(env.mac_pad_offset, env.mac_pad_len)
            alert = (
                f"MAC failure on pad={env.pad_id} offset={env.mac_pad_offset} "
                f"(slot_quarantined={quarantined})"
            )
            self.tamper_alerts.append(alert)
            if self._on_tamper_alert is not None:
                self._on_tamper_alert(alert, env)
            raise InfoTheoreticSecurityError(
                "Wegman-Carter F_(2^127-1) MAC verification FAILED: mid-flight tampering or forgery detected."
            )

        # 2. MAC verified -> atomically burn BOTH MAC & OTP slices and decrypt
        otp_key = pad.commit_receive_burn(env.mac_pad_offset, env.mac_pad_len, env.otp_offset, env.otp_len)
        plaintext = OneTimePadBook.xor_bytes(ciphertext, otp_key)
        raw_claim = json.loads(plaintext.decode("utf-8"))

        # 3. Layer 0 epistemic & Zero-PII verification on receiver side
        inbound_claim = self.epistemic_gate.ingest(
            claim_id=raw_claim["claim_id"],
            subject=raw_claim["subject"],
            payload=raw_claim["payload"],
            proposed_truth=EpistemicTruth(raw_claim["truth_value"]),
            source_kind=SourceKind(raw_claim["source_kind"]),
            source_id=env.sender_id,
            note=f"Received over Algorithmica IT-channel ({env.service_code}, pad={env.pad_id}).",
        )
        self.received_envelopes.append(env)
        if env.lane == "FINALIZED":
            return self.epistemic_gate.commit_verified(f"IT:{env.service_code}", inbound_claim)
        return self.epistemic_gate.stage_unconfirmed(f"IT_STAGED:{env.service_code}", inbound_claim)
