# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-certificate-for-a-state-root-it-never-executed-cross-view-equivocation-of-the-execution-proof-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-certificate-for-a-state-root-it-never-executed-cross-view-equivocation-of-the-execution-proof-binding.warrant.json
# Markdown SHA-256:   6d712524a1f766de6b3b7a8133971cac628048a02af4b1ac3cf3b09564a92caa
# Code AST SHA-256:   1db803d01937afe90f36a36f74b95042c5e50dc4c242d7a44aefb6d43b8a66a9
# Verified Classes:   ExecutionProofEquivocationError, ExecutionProof, Vote
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ExecutionProofEquivocationError(RuntimeError):
    """Raised when a vote's declared root diverges from the root derivable
    from its execution proof, i.e. the proof and the certified value are
    not bound by a verifier-recomputable relation."""


@dataclass(frozen=True)
class ExecutionProof:
    transition_id: str
    output_commitment: bytes  # terminal state commitment, proof-derived


@dataclass(frozen=True)
class Vote:
    view: int
    transition_id: str
    declared_root: bytes  # proposer-supplied; MUST be redundant
    proof: ExecutionProof


def derive_root(proof: ExecutionProof) -> bytes:
    # Root is a pure function of the proof's terminal commitment.
    return hashlib.sha256(b"root|" + proof.output_commitment).digest()


def verify_vote(vote: Vote) -> bytes:
    """Verify a pre-vote. Returns the certified root.

    Structural invariant: the certified root is ALWAYS derived from the
    proof, never read from vote.declared_root. If the declared root is
    present and disagrees, we fail closed -- a Byzantine proposer must not
    be able to get a signature over a root no honest replica executed.
    """
    proof = vote.proof
    if proof.transition_id != vote.transition_id:
        raise ExecutionProofEquivocationError(
            f"proof transition {proof.transition_id!r} does not match "
            f"vote transition {vote.transition_id!r}"
        )

    certified_root = derive_root(proof)

    # The declared root is redundant. If it is present, it MUST equal the
    # derived root. A warning-and-proceed path here is the exact bug:
    # it lets one proof back two distinct certified roots.
    if vote.declared_root != certified_root:
        raise ExecutionProofEquivocationError(
            f"vote declares root {vote.declared_root.hex()[:12]} but proof "
            f"derives {certified_root.hex()[:12]}; refusing to sign "
            f"(view={vote.view}, transition={vote.transition_id})"
        )

    return certified_root


def sign_pre_vote(vote: Vote, signing_key: bytes) -> bytes:
    root = verify_vote(vote)  # derive first, sign the derived value
    return hashlib.sha256(signing_key + root + vote.transition_id.encode()).digest()


# --- Adversarial demonstration -------------------------------------------
if __name__ == "__main__":
    import os

    # Byzantine proposer: one genuine proof, two declared roots.
    proof = ExecutionProof(
        transition_id="T_a",
        output_commitment=os.urandom(32),
    )
    honest_root = derive_root(proof)
    forged_root = os.urandom(32)

    # Honest vote: declared root matches proof.
    ok = Vote(view=1, transition_id="T_a", declared_root=honest_root, proof=proof)
    assert sign_pre_vote(ok, b"key")  # signs fine

    # Equivocating vote: same proof, different declared root.
    bad = Vote(view=1, transition_id="T_a", declared_root=forged_root, proof=proof)
    try:
        sign_pre_vote(bad, b"key")
    except ExecutionProofEquivocationError as exc:
        print(f"rejected equivocating vote: {exc}")
    else:
        raise AssertionError("equivocating vote was signed -- invariant broken")
