# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-signature-transparent-tool-substitution-in-a-byzantine-resilient-skill-registry-when-quorum-attestation-and-content-hash.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-signature-transparent-tool-substitution-in-a-byzantine-resilient-skill-registry-when-quorum-attestation-and-content-hash.warrant.json
# Markdown SHA-256:   002554bb05b33ec78fcd1febd3de0b5f26cbe22f8ebea941813c5f8d246e3d0a
# Code AST SHA-256:   40a1824df0f3d3bfdcdd144bebd92bb7ee6bb7183ce5fa0720323cd10947a6c5
# Verified Classes:   SignatureTransparentSubstitution, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SignatureTransparentSubstitution(RuntimeError):
    """Raised when a dispatched payload's recomputed digest is not bound
    inside the quorum-attested region of the manifest, or when attestation
    epoch monotonicity is violated on the resolution path."""
    pass


@dataclass
class Manifest:
    skill_name: str
    contract: dict
    declared_payload_digest: str   # attacker-controllable free variable
    attestation_epoch: int
    quorum_signatures: list        # signatures over sig_region(manifest)


def recompute_digest(payload_bytes: bytes) -> str:
    return "sha256:" + hashlib.sha256(payload_bytes).hexdigest()


def sig_region(manifest: Manifest, recomputed_digest: str) -> bytes:
    # The signed region MUST bind the recomputed digest, not the declared one.
    return json.dumps({
        "skill_name": manifest.skill_name,
        "contract": manifest.contract,
        "payload_digest": recomputed_digest,
        "epoch": manifest.attestation_epoch,
    }, sort_keys=True).encode()


def verify_quorum(manifest: Manifest, recomputed_digest: str, quorum: int) -> bool:
    # Placeholder: real impl verifies each signature over sig_region bytes.
    signed_region = sig_region(manifest, recomputed_digest)
    valid = sum(1 for s in manifest.quorum_signatures if s.verify(signed_region))
    return valid >= quorum


def dispatch(
    manifest: Manifest,
    payload_bytes: bytes,
    quorum: int,
    last_seen_epoch: dict,
) -> str:
    recomputed = recompute_digest(payload_bytes)

    # Guardrail 1: declared digest must equal recomputed digest. A mismatch
    # means the manifest describes bytes we are not executing.
    if manifest.declared_payload_digest != recomputed:
        raise SignatureTransparentSubstitution(
            f"declared digest {manifest.declared_payload_digest} != "
            f"recomputed {recomputed} for {manifest.skill_name}"
        )

    # Guardrail 2: quorum must attest the region that binds the recomputed
    # digest. A quorum over a declared-but-unbound digest does not count.
    if not verify_quorum(manifest, recomputed, quorum):
        raise SignatureTransparentSubstitution(
            f"quorum does not bind recomputed digest for {manifest.skill_name}"
        )

    # Guardrail 3: monotonic attestation epoch per skill name, persisted.
    prior = last_seen_epoch.get(manifest.skill_name, -1)
    if manifest.attestation_epoch <= prior:
        raise SignatureTransparentSubstitution(
            f"epoch regression for {manifest.skill_name}: "
            f"{manifest.attestation_epoch} <= {prior} (partition replay)"
        )

    last_seen_epoch[manifest.skill_name] = manifest.attestation_epoch
    return recomputed
