# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-sign-a-delegated-warrant-after-a-peer-s-task-receipt-has-been-countersigned-the-nonce-collapse-bou.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-to-re-sign-a-delegated-warrant-after-a-peer-s-task-receipt-has-been-countersigned-the-nonce-collapse-bou.warrant.json
# Markdown SHA-256:   7d23c7adf844bd020c92508a3c7951ece9a6ac80eead309c110a3626c71319ec
# Code AST SHA-256:   10776c3bbe50bb416d37174de6dd46fc843f51cda5928c36f2434494a64ff196
# Verified Classes:   WarrantResigningViolation, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WarrantResigningViolation(RuntimeError):
    """Raised when an instance attempts to re-sign an upstream warrant body
    inside a task receipt, forging a delegation edge it was never granted."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scope: str
    nonce: int
    expiry: int

    def body_hash(self) -> str:
        raw = f"{self.issuer}|{self.subject}|{self.scope}|{self.nonce}|{self.expiry}"
        return hashlib.sha256(raw.encode()).hexdigest()


def build_receipt(
    executor_id: str,
    presented_warrant: Warrant,
    outcome_hash: str,
    own_nonce: int,
    *,
    include_enclosure: bool,
) -> dict:
    """Construct a task receipt. The enclosure path is the defect: it re-signs
    the presented warrant under the executor's key, creating a forged edge."""
    if presented_warrant.subject != executor_id:
        raise WarrantResigningViolation(
            f"executor {executor_id} presented warrant for subject "
            f"{presented_warrant.subject}; refusing to attest"
        )

    receipt = {
        "executor": executor_id,
        "outcome_hash": outcome_hash,
        "parent_warrant_hash": presented_warrant.body_hash(),
        "executor_nonce": own_nonce,
    }

    if include_enclosure:
        # Re-signing the parent body under the executor's key with a fresh
        # nonce. This is the exact operation that evades hash-keyed revocation
        # and manufactures an unauthorized A->C delegation edge.
        resigned = Warrant(
            issuer=presented_warrant.issuer,
            subject=presented_warrant.subject,
            scope=presented_warrant.scope,
            nonce=own_nonce,  # nonce refresh: the revocation-evasion amplifier
            expiry=presented_warrant.expiry,
        )
        receipt["parent_warrant_enclosure"] = resigned
        raise WarrantResigningViolation(
            "receipt would contain a re-signed parent warrant body; "
            "chain by hash only, never by enclosure"
        )

    return receipt


def verify_chain(receipts: list[dict], revoked_hashes: set[str]) -> bool:
    for r in receipts:
        if "parent_warrant_enclosure" in r:
            raise WarrantResigningViolation(
                "receipt carries a re-signed enclosure; chain integrity "
                "cannot be established by hash alone"
            )
        if r["parent_warrant_hash"] in revoked_hashes:
            return False
    return True
