# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-commitment-ledger-fork-its-own-vote-when-the-pre-prepare-digest-collides-with-a-stale-checkpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-in-a-byzantine-quorum-commitment-ledger-fork-its-own-vote-when-the-pre-prepare-digest-collides-with-a-stale-checkpoint.warrant.json
# Markdown SHA-256:   fcf76f54a8a9c8a31925ac592280cbd99bcd543ec2f019cdddbaa8c263b0fefe
# Code AST SHA-256:   d6dddd9c9c8ed735cb32a19b67c0769d29a26214cd9c09160b05ee03786c3950
# Verified Classes:   CheckpointIntegrityFault, SelfEquivocationDetected, Vote
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class CheckpointIntegrityFault(RuntimeError):
    """Raised when a recovering replica cannot bind a checkpointed digest to a body."""
    pass


class SelfEquivocationDetected(CheckpointIntegrityFault):
    """Raised when a replica would emit two votes for the same (view, seq) slot."""
    pass


@dataclass(frozen=True)
class Vote:
    replica: str
    view: int
    seq: int
    digest: str
    body_hash: str
    serializer_version: int


def canonical_digest(body: dict, serializer_version: int) -> str:
    if serializer_version != 3:
        raise CheckpointIntegrityFault(
            f"unsupported serializer_version={serializer_version}; "
            f"cannot guarantee byte-stable digest across checkpoint boundary"
        )
    # Frozen canonical form: sorted keys, no whitespace, floats as fixed-precision strings.
    canon = json.dumps(body, sort_keys=True, separators=(",", ":"), default=str)
    return hashlib.sha256(canon.encode("utf-8")).hexdigest()


def recover_vote(
    checkpoint_digest: str,
    checkpoint_serializer_version: int,
    body: Optional[dict],
    current_serializer_version: int,
    peer_confirmations: int,
    f: int,
) -> Vote:
    """
    Reconstruct-or-abstain: a recovering replica may only re-vote if it can
    bind the checkpointed digest to a body it can verify under a serializer
    version it trusts.
    """
    if body is None:
        if peer_confirmations >= f + 1:
            raise CheckpointIntegrityFault(
                f"body absent for digest={checkpoint_digest} but peers confirmed; "
                f"adopt peer body before voting (do not re-vote blind)"
            )
        raise SelfEquivocationDetected(
            f"abstain: cannot reconstruct body for digest={checkpoint_digest}; "
            f"peer_confirmations={peer_confirmations} < f+1={f+1}"
        )

    if checkpoint_serializer_version != current_serializer_version:
        raise SelfEquivocationDetected(
            f"serializer drift: checkpoint_v={checkpoint_serializer_version} "
            f"!= current_v={current_serializer_version}; abstain until peer confirmation"
        )

    recomputed = canonical_digest(body, current_serializer_version)
    if recomputed != checkpoint_digest:
        raise CheckpointIntegrityFault(
            f"checkpoint corrupt or serializer drift: H(body)={recomputed} "
            f"!= checkpoint_digest={checkpoint_digest}"
        )

    return Vote(
        replica="R3",
        view=15,
        seq=882,
        digest=checkpoint_digest,
        body_hash=recomputed,
        serializer_version=current_serializer_version,
    )


def quorum_count(votes: list[Vote], f: int) -> int:
    """Deduplicate by (replica, view, seq); reject votes whose body_hash != digest."""
    seen: dict[tuple[str, int, int], Vote] = {}
    for v in votes:
        if v.body_hash != v.digest:
            raise SelfEquivocationDetected(
                f"replica {v.replica} voted digest={v.digest} but body_hash={v.body_hash}"
            )
        key = (v.replica, v.view, v.seq)
        if key in seen and seen[key].digest != v.digest:
            raise SelfEquivocationDetected(
                f"replica {v.replica} forked vote at {key}: "
                f"{seen[key].digest} vs {v.digest}"
            )
        seen[key] = v
    return len(seen)
