# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-withhold-quorum-attestation-when-an-adversarial-agent-forges-a-valid-looking-vote-bundle.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-withhold-quorum-attestation-when-an-adversarial-agent-forges-a-valid-looking-vote-bundle.warrant.json
# Markdown SHA-256:   cfa7a75ce81dd1573feaea015e11931b1ff83c96660a78358e833a010006dd50
# Code AST SHA-256:   0b0e365819db7c0fabf26e436b11de1499009434578ff9c68749f651b91ee0a7
# Verified Classes:   QuorumAttestationError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json


class QuorumAttestationError(RuntimeError):
    """Raised when a vote bundle cannot be bound to the proposal it claims."""


DOMAIN = b"corpusfetch.quorum.v1"
REPLAY_WINDOW = 3


def canonical(obj) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()


def proposal_digest(proposal: dict, nonce: bytes, round_no: int) -> bytes:
    h = hashlib.sha256()
    h.update(DOMAIN)
    h.update(canonical(proposal))
    h.update(nonce)
    h.update(round_no.to_bytes(8, "big"))
    return h.digest()


def verify_bundle(bundle: dict, current_round: int, verify_sig) -> bool:
    """
    bundle = {
      "proposal": {...},
      "envelope_hash": <hex>,          # UNTRUSTED
      "round": int,                    # UNTRUSTED
      "votes": [{"signer": id, "nonce": hex, "digest": hex, "sig": bytes}, ...]
    }
    """
    proposal = bundle["proposal"]
    declared_round = bundle["round"]

    if declared_round < current_round - REPLAY_WINDOW:
        raise QuorumAttestationError(
            f"bundle round {declared_round} outside replay window "
            f"(current {current_round})"
        )

    seen = {}
    for vote in bundle["votes"]:
        nonce = bytes.fromhex(vote["nonce"])
        # Verifier recomputes the digest from the bytes it will execute.
        recomputed = proposal_digest(proposal, nonce, declared_round)
        if recomputed.hex() != vote["digest"]:
            raise QuorumAttestationError(
                f"signer {vote['signer']} digest does not bind proposal bytes"
            )
        if recomputed.hex() != bundle["envelope_hash"]:
            raise QuorumAttestationError(
                "envelope hash disagrees with recomputed proposal hash"
            )
        key = (vote["signer"], vote["nonce"])
        if key in seen and seen[key] != vote["digest"]:
            raise QuorumAttestationError(
                f"nonce reuse by {vote['signer']} across distinct proposals"
            )
        seen[key] = vote["digest"]
        if not verify_sig(vote["signer"], recomputed, vote["sig"]):
            raise QuorumAttestationError(
                f"invalid signature from {vote['signer']}"
            )

    if len(seen) < 5:  # 2f+1 for f=2
        raise QuorumAttestationError(
            f"quorum not reached: {len(seen)} distinct signers"
        )
    return True
