# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-plan-commitment-as-a-quorum-of-commitments-problem-rather-than-a-quorum-of-votes-problem.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-plan-commitment-as-a-quorum-of-commitments-problem-rather-than-a-quorum-of-votes-problem.warrant.json
# Markdown SHA-256:   141fbd0d000fd17e1cb4d2fd2be94cf05a3144885541a0dfed7210c741759815
# Code AST SHA-256:   89adcc3a96a442eb36ced3e153ca22e8a2f6f1fedaca0dc0c69a660cc10be1f2
# Verified Classes:   EquivocationForkError, CommitmentQuorumError, CommitmentRecord, Endorsement, PlanRound
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import hmac
from dataclasses import dataclass, field
from typing import Dict, List, Optional


class EquivocationForkError(RuntimeError):
    """Raised when a quorum of endorsements is reached on two distinct plan bodies."""
    pass


class CommitmentQuorumError(RuntimeError):
    """Raised when endorsements exist but lack replayable commitment records."""
    pass


@dataclass
class CommitmentRecord:
    instance_id: str
    body_hash: str
    log_index: int
    signature: bytes


@dataclass
class Endorsement:
    instance_id: str
    claimed_body_hash: str
    commitment: Optional[CommitmentRecord] = None


@dataclass
class PlanRound:
    plan_body: bytes
    quorum_threshold: int
    endorsements: List[Endorsement] = field(default_factory=list)

    def body_hash(self) -> str:
        return hashlib.sha256(self.plan_body).hexdigest()


def commit_plan_step(round_: PlanRound, shared_key: bytes) -> str:
    """
    Commit a plan step only if a quorum of endorsers hold signed commitment
    records for the identical body hash. Demotes bare votes to preferences.
    """
    expected = round_.body_hash()
    committed: Dict[str, CommitmentRecord] = {}

    for end in round_.endorsements:
        if end.commitment is None:
            # Vote without commitment record: a preference, not a commitment.
            continue
        rec = end.commitment
        mac = hmac.new(shared_key, f"{rec.instance_id}:{rec.body_hash}:{rec.log_index}".encode(), hashlib.sha256).digest()
        if not hmac.compare_digest(mac, rec.signature):
            continue  # forged or corrupted commitment record
        if rec.body_hash != expected:
            # Endorser committed to a different body than the one under vote.
            # This is the equivocation signal; do not count, but record it.
            raise EquivocationForkError(
                f"peer {rec.instance_id} committed to {rec.body_hash[:12]} "
                f"but round body is {expected[:12]}"
            )
        committed[rec.instance_id] = rec

    if len(committed) < round_.quorum_threshold:
        raise CommitmentQuorumError(
            f"only {len(committed)} signed commitments for {expected[:12]}, "
            f"need {round_.quorum_threshold}"
        )
    return expected
