# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-agreement-on-a-task-result-as-invalid-despite-f-1-matching-signatures.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-byzantine-quorum-agreement-on-a-task-result-as-invalid-despite-f-1-matching-signatures.warrant.json
# Markdown SHA-256:   c96e9d2f62bb22c6de8cb978dd02ac9e3a6db0253101941f87fb652eca65281b
# Code AST SHA-256:   06d5e94227d7e9fb0e2c074f044a2cb7d45e7fb01d6fbaf199d1e55618fa797c
# Verified Classes:   QuorumBindingError, Commitment, SignedEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumBindingError(RuntimeError):
    """Raised when an f+1 quorum is cryptographically valid but not bound to the current commitment."""
    pass


@dataclass(frozen=True)
class Commitment:
    task_id: str
    epoch: int
    input_digest: str
    roster_digest: str
    round_nonce: str


@dataclass(frozen=True)
class SignedEnvelope:
    signer_id: str
    signed_payload: bytes      # bytes the signature actually covers
    signature: bytes
    envelope_header: dict      # unsigned; attacker-controlled


def _reconstruct(commitment: Commitment, result_digest: str) -> bytes:
    return (
        f"{commitment.task_id}|{commitment.epoch}|{commitment.input_digest}|"
        f"{commitment.roster_digest}|{commitment.round_nonce}|{result_digest}"
    ).encode()


def accept_quorum(
    commitment: Commitment,
    result_digest: str,
    envelopes: list[SignedEnvelope],
    f: int,
    verify,
) -> str:
    expected = _reconstruct(commitment, result_digest)
    seen_signers: set[str] = set()
    valid: list[str] = []

    for env in envelopes:
        if env.signer_id in seen_signers:
            # Same signer, second envelope: check for equivocation before dedup.
            raise QuorumBindingError(
                f"equivocation: signer {env.signer_id} submitted multiple envelopes "
                f"for round {commitment.round_nonce}"
            )
        if env.signed_payload != expected:
            # Signature may be valid, but it is not bound to this epoch/input/roster/round.
            raise QuorumBindingError(
                f"signer {env.signer_id} signed payload not bound to commitment "
                f"{commitment.task_id}@{commitment.epoch}"
            )
        if not verify(env.signer_id, env.signed_payload, env.signature):
            continue
        seen_signers.add(env.signer_id)
        valid.append(env.signer_id)

    if len(valid) < f + 1:
        raise QuorumBindingError(
            f"insufficient bound signatures: {len(valid)} < f+1={f + 1}"
        )
    return hashlib.sha256(expected + b"|" + "|".join(sorted(valid)).encode()).hexdigest()
