# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-equivocating-commit-certificates-from-surviving-an-agent-quorum-s-view-merge.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-equivocating-commit-certificates-from-surviving-an-agent-quorum-s-view-merge.warrant.json
# Markdown SHA-256:   2185c93841a79a08682bded9838c5db83edecbae351ecbc8d5fc6b26e1f30102
# Code AST SHA-256:   884a203449b0c2157c7046d26d4beb175c74bb80600b9c641a17c515bfb368b5
# Verified Classes:   EquivocationSurvivedMerge, Certificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class EquivocationSurvivedMerge(RuntimeError):
    """Raised when a commit-certificate passes signature checks but its
    content binding or nullifier check fails at view-merge."""
    pass


@dataclass(frozen=True)
class Certificate:
    height: int
    view: int
    payload_hash: str          # leader-asserted digest
    proposal_body: bytes       # actual content the signers attested
    signatures: tuple          # (signer_id, sig) pairs
    justify: bytes | None      # required if view > 1


def _hash_body(body: bytes) -> str:
    return hashlib.sha256(body).hexdigest()


def accept_certificate(
    cert: Certificate,
    quorum_size: int,
    honest_signers: set,
    signed_at_height: dict,   # height -> payload_hash already signed
) -> bool:
    # (a) content binding: signature domain must cover the recomputed hash,
    #     not the leader-asserted payload_hash.
    recomputed = _hash_body(cert.proposal_body)
    if recomputed != cert.payload_hash:
        raise EquivocationSurvivedMerge(
            f"height {cert.height}: signature attests {cert.payload_hash!r} "
            f"but body hashes to {recomputed!r}; leader forged the digest"
        )

    # (b) quorum over honest signers only (Byzantine sigs don't count).
    valid = {s for s, _ in cert.signatures if s in honest_signers}
    if len(valid) < quorum_size:
        raise EquivocationSurvivedMerge(
            f"height {cert.height}: only {len(valid)} honest signatures, "
            f"need {quorum_size}"
        )

    # (c) height-scoped nullifier: a conflicting hash at the same height
    #     means the signer set equivocated, regardless of view.
    prior = signed_at_height.get(cert.height)
    if prior is not None and prior != cert.payload_hash:
        raise EquivocationSurvivedMerge(
            f"height {cert.height}: conflicting commitment "
            f"{prior!r} vs {cert.payload_hash!r} across views"
        )

    # (d) re-proposal requires justification for the locked value.
    if cert.view > 1 and not cert.justify:
        raise EquivocationSurvivedMerge(
            f"height {cert.height} view {cert.view}: re-proposal without "
            f"locked-QC justification"
        )

    signed_at_height[cert.height] = cert.payload_hash
    return True
