# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-during-bft-commitment-the-vote-set-divergence-that-survives-quorum.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-equivocates-during-bft-commitment-the-vote-set-divergence-that-survives-quorum.warrant.json
# Markdown SHA-256:   6ac81ec2ba69008a3b15d9ddd7441ddfaa45833cd4d9861e5526ef24fb1b1f1f
# Code AST SHA-256:   7b0ea046ffbbce3bd3ac6146ff839c5037293d95d5113697cf369df7c3b40843
# Verified Classes:   EquivocationDetected, VoteLog
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class EquivocationDetected(RuntimeError):
    """Raised when an instance attempts to sign a conflicting value for a slot/view."""
    pass


@dataclass
class VoteLog:
    # Durable, out-of-context store: (slot, view) -> (value_hash, signature)
    _log: dict = field(default_factory=dict)

    @staticmethod
    def _key(slot: str, view: int) -> tuple:
        return (slot, view)

    @staticmethod
    def _hash(value: dict) -> str:
        return hashlib.sha256(
            json.dumps(value, sort_keys=True).encode()
        ).hexdigest()

    def sign_commit(self, slot: str, view: int, value: dict) -> str:
        """Sign a commit for (slot, view, value). Refuses to contradict a prior signature."""
        key = self._key(slot, view)
        vhash = self._hash(value)
        prior = self._log.get(key)
        if prior is not None and prior != vhash:
            raise EquivocationDetected(
                f"slot={slot} view={view}: already signed {prior[:12]}, "
                f"refusing to sign conflicting {vhash[:12]}"
            )
        sig = hashlib.sha256(f"{slot}:{view}:{vhash}".encode()).hexdigest()
        self._log[key] = vhash
        return sig

    def verify_certificate(self, slot: str, view: int,
                           value: dict, cert: list) -> bool:
        """A certificate is valid only if self-consistent AND view-bound."""
        vhash = self._hash(value)
        expected = hashlib.sha256(f"{slot}:{view}:{vhash}".encode()).hexdigest()
        if len(cert) < 3:  # 2f+1 with n=4, f=1
            return False
        if any(sig != expected for sig in cert):
            return False
        prior = self._log.get(self._key(slot, view))
        if prior is not None and prior != vhash:
            raise EquivocationDetected(
                f"certificate for slot={slot} view={view} conflicts with "
                f"locally signed value {prior[:12]}"
            )
        return True


def commit_task(log: VoteLog, slot: str, view: int,
                value: dict, cert: list) -> None:
    if not log.verify_certificate(slot, view, value, cert):
        raise EquivocationDetected(
            f"rejecting malformed or conflicting certificate for slot={slot}"
        )
    log.sign_commit(slot, view, value)
