# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-signed-vote-is-replayed-across-a-quorum-epoch-boundary-in-byzantine-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-signed-vote-is-replayed-across-a-quorum-epoch-boundary-in-byzantine-agent-consensus.warrant.json
# Markdown SHA-256:   58112c4062bd4da7c67927753a3be1f4e41aab993d5d86470ced329d6eb8ede4
# Code AST SHA-256:   9ed3fcc5867ffe399345d0076d42e1aaa26e7b40464d94ac42d10cfa2900d634
# Verified Classes:   StaleVoteReplay, VoteEnvelope, QuorumVerifier
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class StaleVoteReplay(RuntimeError):
    """Raised when a signature-valid vote is provably from a prior epoch."""
    pass


@dataclass
class VoteEnvelope:
    instance_id: str
    epoch: int
    vote_seq: int
    proposal_hash: str
    vote: str
    signature: bytes  # opaque; assumed valid over (epoch, vote_seq, hash, vote)


@dataclass
class QuorumVerifier:
    current_epoch: int
    n: int
    f: int
    last_seen: dict = field(default_factory=dict)  # instance_id -> (epoch, seq)
    counted: dict = field(default_factory=dict)     # epoch -> set(instance_id)

    def _verify_signature(self, env: VoteEnvelope) -> bool:
        # Placeholder: real impl checks sig over the full tuple.
        return bool(env.signature)

    def accept(self, env: VoteEnvelope) -> bool:
        if not self._verify_signature(env):
            return False
        if env.epoch != self.current_epoch:
            # Signature is valid but minted in another epoch: replay vector.
            raise StaleVoteReplay(
                f"vote from {env.instance_id} minted in epoch {env.epoch}, "
                f"current epoch {self.current_epoch}"
            )
        prev = self.last_seen.get(env.instance_id)
        if prev is not None and (env.epoch, env.vote_seq) <= prev:
            raise StaleVoteReplay(
                f"non-monotonic vote_seq for {env.instance_id}: "
                f"{env.vote_seq} <= {prev[1]}"
            )
        self.last_seen[env.instance_id] = (env.epoch, env.vote_seq)
        self.counted.setdefault(env.epoch, set()).add(env.instance_id)
        return True

    def has_quorum(self) -> bool:
        # Honest-majority invariant: 2f+1 distinct fresh instances.
        return len(self.counted.get(self.current_epoch, set())) >= 2 * self.f + 1
