# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-quorum-laundering-in-cross-org-federation-policy-engines-when-byzantine-result-acceptance-is-gated-on-signed-attestations.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-quorum-laundering-in-cross-org-federation-policy-engines-when-byzantine-result-acceptance-is-gated-on-signed-attestations.warrant.json
# Markdown SHA-256:   89cc0e04b13ab9cdb8a796f05ea54d1411befd0cbbadf13a5e97e1db71d6e169
# Code AST SHA-256:   c76164f180eeefcbc750fb9330806d6cfa52d6de384efb6feaf46ae046a5ee25
# Verified Classes:   QuorumLaunderingError, SignedAttestation, QuorumEnvelope
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumLaunderingError(RuntimeError):
    """Raised when a quorum certificate's signatures attest divergent
    (input_digest, result_digest) pairs despite meeting the signature count."""


@dataclass(frozen=True)
class SignedAttestation:
    signer_id: str
    input_digest: str      # digest of the input the signer ACTUALLY observed
    result_digest: str     # digest of the result the signer computed
    signature: bytes       # signature over (req_id, input_digest, result_digest)


@dataclass(frozen=True)
class QuorumEnvelope:
    req_id: str
    claimed_input_digest: str   # UNTRUSTED: assembler-supplied
    claimed_result_digest: str  # UNTRUSTED: assembler-supplied
    attestations: list[SignedAttestation]


def verify_quorum(
    envelope: QuorumEnvelope,
    canonical_input: bytes,
    local_result_digest: str,
    k: int,
    verify_sig,
) -> bool:
    # 1. Cryptographic validity per signer (necessary, not sufficient).
    valid = [a for a in envelope.attestations
             if verify_sig(a.signer_id, envelope.req_id, a.input_digest,
                           a.result_digest, a.signature)]
    if len(valid) < k:
        return False

    # 2. Recompute the canonical input digest ourselves; never trust the envelope.
    expected_input = hashlib.sha256(canonical_input).hexdigest()

    # 3. Reconstruct the agreement set from SIGNED payloads, not envelope fields.
    agreement = {(a.input_digest, a.result_digest) for a in valid}

    if len(agreement) != 1:
        raise QuorumLaunderingError(
            f"req={envelope.req_id}: {len(valid)} valid signatures span "
            f"{len(agreement)} distinct (input,result) pairs — quorum laundered"
        )

    (signed_input, signed_result), = agreement

    # 4. The single agreed pair must match our own recomputation.
    if signed_input != expected_input:
        raise QuorumLaunderingError(
            f"req={envelope.req_id}: signers agreed on input {signed_input[:12]} "
            f"but local canonical input is {expected_input[:12]} (stale/mutated ref)"
        )
    if signed_result != local_result_digest:
        raise QuorumLaunderingError(
            f"req={envelope.req_id}: signers agreed on result {signed_result[:12]} "
            f"but local recomputation is {local_result_digest[:12]}"
        )

    # 5. Envelope claims are now redundant; assert they don't contradict.
    if envelope.claimed_input_digest != signed_input:
        raise QuorumLaunderingError(
            f"req={envelope.req_id}: envelope input claim contradicts signed input"
        )

    return True
