# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-membership-churn-as-a-byzantine-equivocation-vector-rather-than-benign-reconfiguration-in-multi-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-quorum-membership-churn-as-a-byzantine-equivocation-vector-rather-than-benign-reconfiguration-in-multi-agent.warrant.json
# Markdown SHA-256:   05b7cc5265f33ca22a68340af2537160ede6040e07956275e8404441f40bd63c
# Code AST SHA-256:   843664527229fdaa0cbae29b616952954404564de4fba59a4c618e37332aba22
# Verified Classes:   QuorumEquivocationError, StaleEpochError, Vote, VoteLog, QuorumCollector
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import hmac
import time
from dataclasses import dataclass, field


class QuorumEquivocationError(RuntimeError):
    """Raised when a vote would cause a logical identity to equivocate within a round."""
    pass


class StaleEpochError(RuntimeError):
    """Raised when a vote arrives carrying an epoch older than the round's current epoch."""
    pass


@dataclass
class Vote:
    identity: str
    epoch: int
    round_id: str
    decision: str
    vote_hash: str
    signature: str


@dataclass
class VoteLog:
    """Append-only, fsync'd before broadcast. The precondition of quorum safety."""
    entries: list = field(default_factory=list)

    def commit(self, vote: Vote) -> None:
        # In production: open with O_APPEND, write, os.fsync before returning.
        self.entries.append(vote)

    def lookup(self, identity: str, round_id: str) -> Vote | None:
        for v in reversed(self.entries):
            if v.identity == identity and v.round_id == round_id:
                return v
        return None


class QuorumCollector:
    def __init__(self, secret: bytes, threshold: int):
        self._secret = secret
        self._threshold = threshold
        self._votes: dict[tuple[str, str], Vote] = {}
        self._current_epoch: dict[str, int] = {}

    def _sign(self, identity: str, epoch: int, round_id: str, decision: str) -> str:
        msg = f"{identity}|{epoch}|{round_id}|{decision}".encode()
        return hmac.new(self._secret, msg, hashlib.sha256).hexdigest()

    def admit(self, vote: Vote) -> None:
        expected = self._sign(vote.identity, vote.epoch, vote.round_id, vote.decision)
        if not hmac.compare_digest(expected, vote.signature):
            raise QuorumEquivocationError(
                f"forged signature for {vote.identity} epoch {vote.epoch}"
            )

        key = (vote.identity, vote.round_id)
        prior = self._votes.get(key)

        if prior is not None:
            # Same identity, same round: this is the equivocation boundary.
            if prior.vote_hash != vote.vote_hash:
                raise QuorumEquivocationError(
                    f"{vote.identity} equivocated in round {vote.round_id}: "
                    f"{prior.decision!r} (epoch {prior.epoch}) vs "
                    f"{vote.decision!r} (epoch {vote.epoch}); "
                    f"respawn must be a new epoch, not an overwrite"
                )
            # Identical replay from a committed log: safe, idempotent.
            return

        current = self._current_epoch.get(vote.identity, 0)
        if vote.epoch < current:
            raise StaleEpochError(
                f"{vote.identity} vote epoch {vote.epoch} < current {current}; "
                f"round must restart under new epoch"
            )
        self._current_epoch[vote.identity] = vote.epoch
        self._votes[key] = vote

    def respawn(self, identity: str) -> int:
        """A crash-and-respawn MUST bump the epoch; prior votes become stale."""
        new_epoch = self._current_epoch.get(identity, 0) + 1
        self._current_epoch[identity] = new_epoch
        return new_epoch

    def quorum_reached(self, round_id: str) -> bool:
        return sum(1 for (i, r) in self._votes if r == round_id) >= self._threshold


def cast_vote_after_respawn(
    collector: QuorumCollector,
    log: VoteLog,
    identity: str,
    round_id: str,
    decision: str,
) -> Vote:
    # The invariant: check the durable log BEFORE reasoning again.
    prior = log.lookup(identity, round_id)
    if prior is not None:
        # Replay the committed vote; do not re-reason.
        return prior

    # No prior vote: this is a genuine new epoch. Bump and sign.
    epoch = collector.respawn(identity)
    vote_hash = hashlib.sha256(f"{identity}|{epoch}|{round_id}|{decision}".encode()).hexdigest()
    vote = Vote(
        identity=identity,
        epoch=epoch,
        round_id=round_id,
        decision=decision,
        vote_hash=vote_hash,
        signature=collector._sign(identity, epoch, round_id, decision),
    )
    # Persist BEFORE broadcast. If we crash here, the log is the source of truth.
    log.commit(vote)
    return vote


def demonstrate_equivocation_is_blocked() -> None:
    secret = b"quorum-secret"
    collector = QuorumCollector(secret, threshold=4)
    log = VoteLog()

    # auditor-3 reasons, commits approve, then "crashes" before broadcast.
    v1 = cast_vote_after_respawn(collector, log, "auditor-3", "round-7", "approve")
    collector.admit(v1)

    # Respawn: log replay must return the committed vote, not a fresh reason.
    v2 = cast_vote_after_respawn(collector, log, "auditor-3", "round-7", "reject")
    assert v2.vote_hash == v1.vote_hash, "respawn must replay, not re-reason"
    collector.admit(v2)  # idempotent, no equivocation

    # Now simulate the buggy path: a respawn that ignores the log.
    forged_epoch = collector.respawn("auditor-3")
    bad = Vote(
        identity="auditor-3",
        epoch=forged_epoch,
        round_id="round-7",
        decision="reject",
        vote_hash="deadbeef",
        signature=collector._sign("auditor-3", forged_epoch, "round-7", "reject"),
    )
    try:
        collector.admit(bad)
    except QuorumEquivocationError as e:
        print(f"BLOCKED: {e}")
        return
    raise QuorumEquivocationError("collector accepted an equivocating vote; invariant broken")


if __name__ == "__main__":
    demonstrate_equivocation_is_blocked()
