# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-attestation-chain-collapse-when-an-intermediate-agent-re-signs-a-downstream-warrant-under-a-rotated-key.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-attestation-chain-collapse-when-an-intermediate-agent-re-signs-a-downstream-warrant-under-a-rotated-key.warrant.json
# Markdown SHA-256:   4f22b9599d63b6390424cb55dbe3cbaa649c87d4d0425787fc80c8d0769ad7fd
# Code AST SHA-256:   8d8b7a20d90490a9d69ba905b13a22bd87f2d13c148287de16e0a31222cb7311
# Verified Classes:   AttestationContinuityError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AttestationContinuityError(RuntimeError):
    """Raised when a warrant's signing key cannot be bound to the parent warrant's subject identity."""
    pass


def verify_warrant_chain(warrant, parent, rotation_log, trusted_root_keys):
    # Branch 1: direct key binding
    if warrant.signing_key in parent.subject_keys:
        if not _sig_valid(warrant, warrant.signing_key):
            raise AttestationContinuityError(
                f"signature invalid under bound key {warrant.signing_key}"
            )
        return True

    # Branch 2: rotation-continuity chain rooted in parent.subject_keys
    chain = _resolve_rotation_chain(
        start_key=warrant.signing_key,
        target_keys=parent.subject_keys,
        log=rotation_log,
    )
    if chain is None:
        # Branch 3: signature may be valid, but identity is unbound -> reject
        raise AttestationContinuityError(
            f"key {warrant.signing_key} chains to parent {parent.id} "
            f"but is not bound to subject {parent.subject}; "
            f"no valid Rotate statement links it to {parent.subject_keys}"
        )

    prev_epoch = parent.epoch
    for step in chain:
        if step.epoch <= prev_epoch:
            raise AttestationContinuityError(
                f"non-monotonic rotation epoch {step.epoch} <= {prev_epoch} "
                f"at key {step.new_key}; possible pre-rotation replay"
            )
        if not _sig_valid(step, step.old_key):
            raise AttestationContinuityError(
                f"rotation statement {step.old_key}->{step.new_key} "
                f"not signed by superseded key"
            )
        prev_epoch = step.epoch

    return True
