# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-equivocation-when-agents-commit-to-a-shared-plan-under-partial-synchrony.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-equivocation-when-agents-commit-to-a-shared-plan-under-partial-synchrony.warrant.json
# Markdown SHA-256:   dc4b1ef8af062a2b587bea180608e48fb0cf9b7d2d84fe6a5de9dec3779f1133
# Code AST SHA-256:   8e302529852261302a6423e797846bd021f6981f039475e4e2d49decb0c514cd
# Verified Classes:   EquivocationAcrossEpochsError, Commitment, Agent, Validator
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class EquivocationAcrossEpochsError(RuntimeError):
    """Raised when a plan-commitment vote is cast against a history that
    does not chain to the voter's locally-finalized tip, or when a
    validator counts a vote whose claimed predecessor digest differs from
    its own observed tip. This is the silent-equivocation boundary: the
    per-instance quorum may be valid while the cross-epoch intersection
    is dominated by Byzantine members."""


def _digest(payload: bytes) -> str:
    return hashlib.sha256(payload).hexdigest()


@dataclass
class Commitment:
    epoch: int
    plan_digest: str
    prev_digest: str  # digest of the finalized commitment at epoch-1, or GENESIS

    def digest(self) -> str:
        return _digest(f"{self.epoch}:{self.plan_digest}:{self.prev_digest}".encode())


GENESIS = "0" * 64


@dataclass
class Agent:
    agent_id: str
    finalized_tip: Optional[str] = None  # None => state-synced without chain replay
    byzantine: bool = False

    def vote(self, commitment: Commitment) -> Commitment:
        # Byzantine agents sign whatever they like; the invariant is enforced
        # by the *voter's own* self-check and by validators, not by honesty.
        if not self.byzantine:
            if self.finalized_tip is None:
                raise EquivocationAcrossEpochsError(
                    f"{self.agent_id}: no locally-verified finalized tip; "
                    f"cannot validate prev_digest for epoch {commitment.epoch}. "
                    f"State-sync must replay the commitment chain before voting."
                )
            if commitment.prev_digest != self.finalized_tip:
                raise EquivocationAcrossEpochsError(
                    f"{self.agent_id}: vote for epoch {commitment.epoch} claims "
                    f"prev_digest={commitment.prev_digest[:8]}... but local tip is "
                    f"{(self.finalized_tip or 'None')[:8]}...; refusing to vote on "
                    f"a divergent history."
                )
        return commitment


@dataclass
class Validator:
    validator_id: str
    observed_tip: Optional[str] = None
    quorum_size: int = 5
    votes: list = field(default_factory=list)

    def accept_vote(self, voter: Agent, commitment: Commitment) -> None:
        if self.observed_tip is None:
            raise EquivocationAcrossEpochsError(
                f"{self.validator_id}: cannot validate vote from {voter.agent_id} "
                f"without a locally-verified tip; replay the commitment chain first."
            )
        if commitment.prev_digest != self.observed_tip:
            raise EquivocationAcrossEpochsError(
                f"{self.validator_id}: rejecting vote from {voter.agent_id} for "
                f"epoch {commitment.epoch}: claimed prev_digest="
                f"{commitment.prev_digest[:8]}... != observed tip="
                f"{self.observed_tip[:8]}... (potential cross-epoch equivocation)."
            )
        self.votes.append((voter.agent_id, commitment))

    def finalize(self) -> Commitment:
        if len(self.votes) < self.quorum_size:
            raise EquivocationAcrossEpochsError(
                f"{self.validator_id}: only {len(self.votes)} valid votes; "
                f"quorum={self.quorum_size} not met."
            )
        # All accepted votes share the same prev_digest == observed_tip, so the
        # finalized commitment chains correctly.
        return self.votes[0][1]


def demonstrate_silent_equivocation() -> None:
    # Epoch 3: P finalized by quorum {A1,A2,A3,B3,B4} with tip GENESIS.
    p3 = Commitment(epoch=3, plan_digest="plan_P_lock_A1", prev_digest=GENESIS)
    tip3 = p3.digest()

    # Epoch 4: Byzantine B3 signs P' with prev_digest=tip3, but sends it to a
    # disjoint quorum {A4,A5,A6} that state-synced WITHOUT chain replay.
    p4_prime = Commitment(epoch=4, plan_digest="plan_P_prime_lock_A4", prev_digest=tip3)

    a4 = Agent("A4", finalized_tip=None)  # state-synced, no chain replay
    validator = Validator("V4", observed_tip=None)

    # A4 must refuse to vote: it cannot validate prev_digest.
    try:
        a4.vote(p4_prime)
    except EquivocationAcrossEpochsError as e:
        print(f"[bounded] {e}")

    # Validator must refuse to count: it has no observed tip.
    try:
        validator.accept_vote(a4, p4_prime)
    except EquivocationAcrossEpochsError as e:
        print(f"[bounded] {e}")

    # Now the correct path: A4 replays the chain and observes tip3.
    a4.finalized_tip = tip3
    validator.observed_tip = tip3
    # A4 can now vote for a *valid* epoch-4 commitment that chains to tip3.
    p4 = Commitment(epoch=4, plan_digest="plan_P_prime_preserve_lock_A1", prev_digest=tip3)
    a4.vote(p4)
    for aid in ("A5", "A6", "B3", "B4"):
        validator.accept_vote(Agent(aid, finalized_tip=tip3), p4)
    finalized = validator.finalize()
    print(f"[finalized] epoch={finalized.epoch} digest={finalized.digest()[:8]}...")


if __name__ == "__main__":
    demonstrate_silent_equivocation()
