# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-peer-s-committed-plan-as-unverifiable-rather-than-merely-wrong-quorum-certificate-equivocation-under-partial-s.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-byzantine-peer-s-committed-plan-as-unverifiable-rather-than-merely-wrong-quorum-certificate-equivocation-under-partial-s.warrant.json
# Markdown SHA-256:   7c629816fba492b46cce6f043b4eb0a591f4b545a689e954dda46ec9d9298bbf
# Code AST SHA-256:   df3c552250688b9b020c109cb7679fcc09fd5e70bbeefc0db417734b2f1951df
# Verified Classes:   EquivocationDetected, StateUnverifiable, QuorumCertificate, CommitLog, ConsensusGuard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EquivocationDetected(RuntimeError):
    """Raised when two distinct roots are certified at the same view."""
    pass


class StateUnverifiable(RuntimeError):
    """Raised when the instance lacks the commit-log evidence to adjudicate."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    root: str
    shares: frozenset  # canonicalized signer ids

    def canonical_hash(self) -> str:
        payload = f"{self.view}:{self.root}:{','.join(sorted(self.shares))}"
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class CommitLog:
    # view -> root committed at that view
    entries: dict = field(default_factory=dict)

    def root_at(self, view: int) -> Optional[str]:
        return self.entries.get(view)


class ConsensusGuard:
    """Enforces: commit requires validity + non-equivocation evidence."""

    def __init__(self, f: int, retention_views: int = 64):
        self.f = f
        self.quorum = 2 * f + 1
        self.retention_views = retention_views
        self.log = CommitLog()
        self.last_committed_view = -1
        self.quarantined = set()

    def _verify_threshold(self, cert: QuorumCertificate) -> bool:
        return len(cert.shares) >= self.quorum

    def commit(self, cert: QuorumCertificate) -> str:
        if not self._verify_threshold(cert):
            raise EquivocationDetected(
                f"certificate at view {cert.view} has {len(cert.shares)} "
                f"shares, below quorum {self.quorum}"
            )

        if cert.view <= self.last_committed_view:
            logged = self.log.root_at(cert.view)
            if logged is None:
                # Cold-start or truncated log: cannot adjudicate.
                raise StateUnverifiable(
                    f"view {cert.view} at or below committed view "
                    f"{self.last_committed_view} but no log entry retained; "
                    f"require state-transfer proof before committing"
                )
            if logged != cert.root:
                # Equivocation: two roots at the same view.
                self._quarantine_overlap(cert)
                raise EquivocationDetected(
                    f"view {cert.view}: logged root {logged} conflicts with "
                    f"presented root {cert.root}; quarantined "
                    f"{sorted(self.quarantined)}"
                )
            return logged  # idempotent re-commit

        # New view: commit only if no conflicting root already logged.
        logged = self.log.root_at(cert.view)
        if logged is not None and logged != cert.root:
            self._quarantine_overlap(cert)
            raise EquivocationDetected(
                f"view {cert.view}: conflicting roots {logged} vs {cert.root}"
            )

        self.log.entries[cert.view] = cert.root
        self.last_committed_view = cert.view
        self._evict_old_views()
        return cert.root

    def _quarantine_overlap(self, cert: QuorumCertificate) -> None:
        # The signer set of the conflicting certificate is recoverable from
        # the log only if we stored it; here we conservatively quarantine
        # every signer of the presented cert that also appears in the log's
        # recorded shares for that view (stored separately in production).
        self.quarantined.update(cert.shares)

    def _evict_old_views(self) -> None:
        cutoff = self.last_committed_view - self.retention_views
        for v in [v for v in self.log.entries if v < cutoff]:
            del self.log.entries[v]
