# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-forgery-from-surviving-a-byzantine-agent-s-view-merge-in-bft-task-commitment-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-certificate-forgery-from-surviving-a-byzantine-agent-s-view-merge-in-bft-task-commitment-consensus.warrant.json
# Markdown SHA-256:   cdd6a621e10f5277e84005d4663f4ff9309ba4518d4115a607477d89c5959c14
# Code AST SHA-256:   c67c3c0954374dbe8dd5692961c5c4de4a3c6e6baa6097e5f883d251c83218fd
# Verified Classes:   QCSoundnessError, QC
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QCSoundnessError(RuntimeError):
    """Raised when a quorum certificate fails payload-binding or monotonicity checks."""
    pass


@dataclass(frozen=True)
class QC:
    protocol_id: str
    phase: str
    view: int
    seq: int
    value_digest: str
    signatures: tuple  # (signer_pubkey, sig_bytes) pairs


def canonical_bytes(protocol_id: str, phase: str, view: int, seq: int, value_digest: str) -> bytes:
    # Complete domain separation: every field that scopes the commitment is signed.
    return f"{protocol_id}|{phase}|{view}|{seq}|{value_digest}".encode("utf-8")


def verify_qc(
    qc: QC,
    verify_sig,
    committed_slot: dict,
    f: int,
) -> bool:
    # Rule 1: phase must match the phase the QC claims to be.
    if qc.phase not in ("PREPARE", "COMMIT", "NEW_VIEW"):
        raise QCSoundnessError(f"unknown phase {qc.phase!r}")

    # Rule 2: monotonic view-merge — a lower (view, seq) cannot override a committed slot.
    prior = committed_slot.get(qc.seq)
    if prior is not None and (qc.view, qc.seq) < (prior["view"], prior["seq"]):
        raise QCSoundnessError(
            f"non-monotonic override: QC claims (view={qc.view}, seq={qc.seq}) "
            f"but slot already committed at (view={prior['view']}, seq={prior['seq']})"
        )

    # Rule 3: payload binding — each signature must verify over the FULL canonical string.
    canon = canonical_bytes(
        qc.protocol_id, qc.phase, qc.view, qc.seq, qc.value_digest
    )
    valid = 0
    for pubkey, sig in qc.signatures:
        if verify_sig(pubkey, sig, canon):
            valid += 1

    quorum = 2 * f + 1
    if valid < quorum:
        raise QCSoundnessError(
            f"insufficient bound signatures: {valid} < quorum {quorum} "
            f"for (view={qc.view}, seq={qc.seq}, phase={qc.phase})"
        )
    return True


def merge_view(new_view_qc: QC, committed_slot: dict, verify_sig, f: int) -> dict:
    # Re-derive committed value from the signed payload; never trust QC metadata alone.
    try:
        verify_qc(new_view_qc, verify_sig, committed_slot, f)
    except QCSoundnessError as exc:
        # Byzantine replay detected: refuse the view-merge and stay in current view.
        raise QCSoundnessError(
            f"view-merge rejected: {exc}; agent must not execute {new_view_qc.value_digest!r}"
        ) from exc
    committed_slot[new_view_qc.seq] = {
        "view": new_view_qc.view,
        "seq": new_view_qc.seq,
        "value_digest": new_view_qc.value_digest,
    }
    return committed_slot
