# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-forgery-when-colluding-agents-exploit-hallucinated-vote-provenance-in-bft-plan-commitment.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-forgery-when-colluding-agents-exploit-hallucinated-vote-provenance-in-bft-plan-commitment.warrant.json
# Markdown SHA-256:   e480f41a71dca79f5a3a59d21a36424819372e2934d1cdca264bb37a7adbc0b6
# Code AST SHA-256:   937ad771725d652e29399861e6ae5a20c637e4e6e23f896db3f357413520ee1d
# Verified Classes:   ProvenanceForgeryError, Vote, TransportLog
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceForgeryError(RuntimeError):
    """Raised when a vote cites support that the collector cannot resolve
    to a message actually received by the voter before the vote timestamp."""


@dataclass
class Vote:
    voter_id: str
    plan_digest: str
    cited_support: list[tuple[str, str]]  # (peer_id, msg_hash)
    timestamp: float
    signature: bytes = b""


@dataclass
class TransportLog:
    # (recipient_id, sender_id, msg_hash) -> receipt_timestamp
    receipts: dict[tuple[str, str, str], float] = field(default_factory=dict)

    def record(self, recipient: str, sender: str, payload: bytes, ts: float) -> str:
        h = hashlib.sha256(payload).hexdigest()
        self.receipts[(recipient, sender, h)] = ts
        return h

    def received_before(self, recipient: str, sender: str, h: str, ts: float) -> bool:
        key = (recipient, sender, h)
        return key in self.receipts and self.receipts[key] < ts


def validate_vote(vote: Vote, log: TransportLog, f: int) -> None:
    if not vote.signature:
        raise ProvenanceForgeryError(f"vote from {vote.voter_id} unsigned")
    for peer_id, msg_hash in vote.cited_support:
        if not log.received_before(vote.voter_id, peer_id, msg_hash, vote.timestamp):
            raise ProvenanceForgeryError(
                f"vote from {vote.voter_id} cites support from {peer_id} "
                f"({msg_hash[:12]}) that was never received before t={vote.timestamp}; "
                f"rationale is ungrounded — likely hallucinated or injected"
            )


def commit_plan(votes: list[Vote], log: TransportLog, n: int, plan_digest: str) -> bool:
    f = (n - 1) // 3
    threshold = 2 * f + 1
    valid: list[Vote] = []
    for v in votes:
        if v.plan_digest != plan_digest:
            continue
        try:
            validate_vote(v, log, f)
            valid.append(v)
        except ProvenanceForgeryError:
            continue  # reject vote, do not count toward quorum
    if len(valid) < threshold:
        raise ProvenanceForgeryError(
            f"quorum failed: {len(valid)} provenance-valid votes < threshold {threshold}; "
            f"raw signature count was {len(votes)} — do not commit on unresolvable provenance"
        )
    # transitive closure check on citation graph
    cited = {p for v in valid for p, _ in v.cited_support}
    voter_ids = {v.voter_id for v in valid}
    if cited - voter_ids:
        raise ProvenanceForgeryError(
            f"citation graph references non-voting peers {cited - voter_ids}; "
            f"possible citation-lattice inflation"
        )
    return True
