# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-credential-whose-subject-key-was-rotated-mid-chain-verification.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-credential-whose-subject-key-was-rotated-mid-chain-verification.warrant.json
# Markdown SHA-256:   b732be90ba1b91dc6c6dc8a8ae0055729932dff3ea67342753d03214028b665e
# Code AST SHA-256:   8166f3d0cd62fdba89766c8f0263ad51709365c91cf6a80edaa478710c07c4fa
# Verified Classes:   KeyRotatedDuringVerification
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class KeyRotatedDuringVerification(RuntimeError):
    """Raised when a subject key epoch advances between VC issuance and PoP completion."""
    pass


def verify_vc_with_pop(vc, subject_doc_resolver, pop_signer, nonce):
    # 1. Resolve subject's current epoch BEFORE PoP.
    current = subject_doc_resolver(vc.subject_id)
    if current.key_epoch != vc.key_epoch:
        raise KeyRotatedDuringVerification(
            f"VC bound to epoch {vc.key_epoch}, subject now at {current.key_epoch}"
        )

    # 2. Verify issuer signature over the (subject, key, epoch) triple.
    if not verify_signature(vc.issuer_pubkey, vc.payload, vc.signature):
        raise ValueError("issuer signature invalid")

    # 3. Proof-of-possession against the key the VC actually binds.
    if not verify_pop(current.public_key, nonce, pop_signer(nonce)):
        raise KeyRotatedDuringVerification(
            "PoP failed against bound key; subject does not control it"
        )

    # 4. Re-check epoch AFTER PoP to close the TOCTOU window.
    after = subject_doc_resolver(vc.subject_id)
    if after.key_epoch != vc.key_epoch:
        raise KeyRotatedDuringVerification(
            f"epoch advanced {vc.key_epoch}->{after.key_epoch} during PoP"
        )
    return True
