# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-quorum-certificates-from-masking-a-forked-commitment-log-during-adversarial-peer-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocation-tolerant-quorum-certificates-from-masking-a-forked-commitment-log-during-adversarial-peer-replay.warrant.json
# Markdown SHA-256:   b9ee5da3a48b8037bfcfd79dd14988ff878288d64e3aa5c59169b7d2f0e8fc7b
# Code AST SHA-256:   0d1c9c51f309854bd3cc45d0f70d04f10f1bf01f6664ccd046f6010cd841ee82
# Verified Classes:   EquivocationDetected, AnchorStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class EquivocationDetected(RuntimeError):
    """Raised when a receiver is asked to anchor two conflicting blocks at the same height."""
    pass


class AnchorStore:
    """Durable per-height anchor map. Enforces anchor uniqueness for signing peers."""

    def __init__(self):
        self._anchor: dict[int, str] = {}  # height -> block_hash

    def anchor(self, height: int, block_hash: str, parent_hash: str) -> None:
        # Must chain to the parent we already anchored, if any.
        if height > 0 and self._anchor.get(height - 1) != parent_hash:
            raise EquivocationDetected(
                f"block at height {height} does not chain to anchored parent "
                f"{self._anchor.get(height - 1)!r} (got {parent_hash!r})"
            )
        existing = self._anchor.get(height)
        if existing is not None and existing != block_hash:
            # Two distinct blocks at the same height: equivocation evidence.
            raise EquivocationDetected(
                f"conflicting anchor at height {height}: "
                f"already {existing!r}, refusing {block_hash!r}"
            )
        self._anchor[height] = block_hash

    def may_sign_child_of(self, height: int, block_hash: str) -> bool:
        return self._anchor.get(height) == block_hash


def verify_and_anchor(
    store: AnchorStore,
    height: int,
    block_hash: str,
    parent_hash: str,
    qc_signers: set[str],
    quorum: int,
) -> None:
    # Stateless check: quorum validity.
    if len(qc_signers) < quorum:
        raise EquivocationDetected(
            f"QC at height {height} has {len(qc_signers)} signers, need {quorum}"
        )
    # Stateful check: anchor uniqueness. This is the invariant that closes the fork.
    store.anchor(height, block_hash, parent_hash)


def sign_child(store: AnchorStore, parent_height: int, parent_hash: str) -> str:
    if not store.may_sign_child_of(parent_height, parent_hash):
        raise EquivocationDetected(
            f"refusing to sign child of {parent_hash!r} at height {parent_height}: "
            f"not locally anchored (possible replay-fork)"
        )
    return "signature"
