Skip to main content

hyprstream_discovery/
did_op.rs

1//! Canonical append-only operation log for hybrid-rooted `did:plc` identities.
2//!
3//! This module is deliberately only the operation format and verifier. It does
4//! not resolve DID documents, consult a directory, or apply anchored-identity
5//! policy.
6//!
7//! # Format
8//!
9//! Every operation is a canonical DAG-CBOR map:
10//!
11//! ```text
12//! {
13//!   "type": "plc_operation",
14//!   "sequence": uint,
15//!   "prev": null | "<CIDv1 dag-cbor sha2-256>",
16//!   "rotationKeys": [{
17//!     "ed25519Pub": bytes(32),
18//!     "mldsa65Pub": bytes(1952)
19//!   }, ...],
20//!   "sig": {
21//!     "ed25519": bytes(64),
22//!     "mldsa65": bytes(3309)
23//!   }
24//! }
25//! ```
26//!
27//! The signature covers the canonical operation with the entire `sig` field
28//! omitted. Both components are mandatory and are bound using hyprstream's
29//! nested Ed25519 + ML-DSA-65 composite construction. Genesis has
30//! `sequence = 0` and `prev = null`; rotations increment the sequence by one
31//! and set `prev` to the CIDv1 of the complete previous signed operation.
32//!
33//! As in the PLC method, the DID identifier is the first 24 lower-case RFC 4648
34//! base32 characters of SHA-256 over the complete signed genesis DAG-CBOR.
35
36use anyhow::{anyhow, bail, ensure, Context, Result};
37use ed25519_dalek::{SigningKey, VerifyingKey};
38use sha2::{Digest, Sha256};
39
40use hyprstream_crypto::cose_sign::{
41    assemble_composite_nested, sign_composite, split_composite, verify_composite,
42};
43use hyprstream_crypto::pq::{
44    ml_dsa_sk_to_vk_bytes, ml_dsa_vk_bytes, ml_dsa_vk_from_bytes, MlDsaSigningKey,
45    MlDsaVerifyingKey,
46};
47use hyprstream_pds::{dag_cbor::DagCbor, Cid};
48
49/// Fixed operation discriminator, matching the regular PLC operation name.
50pub const DID_OP_TYPE: &str = "plc_operation";
51/// Domain separation for both layers of every DID operation signature.
52pub const DID_OP_SIGNATURE_CONTEXT: &[u8] = b"hyprstream.did-op/1";
53/// PLC-compatible maximum number of active rotation keys.
54pub const MAX_ROTATION_KEYS: usize = 5;
55/// PQ keys and signatures are larger than classical PLC operations.
56pub const MAX_DID_OP_BYTES: usize = 32 * 1024;
57
58const ED25519_PUBLIC_KEY_LEN: usize = 32;
59const ED25519_SIGNATURE_LEN: usize = 64;
60const ML_DSA65_PUBLIC_KEY_LEN: usize = 1952;
61const ML_DSA65_SIGNATURE_LEN: usize = 3309;
62const PLC_IDENTIFIER_LEN: usize = 24;
63const CIDV1_DAG_CBOR_SHA256_TEXT_LEN: usize = 59;
64
65/// One inseparable authorization position in the rotation-key list.
66///
67/// The Ed25519 and ML-DSA-65 keys are paired by position. A verifier never
68/// accepts one component under a different entry.
69#[derive(Clone, Debug, Eq, PartialEq)]
70pub struct HybridRotationKey {
71    pub ed25519_pub: [u8; ED25519_PUBLIC_KEY_LEN],
72    pub mldsa65_pub: Vec<u8>,
73}
74
75impl HybridRotationKey {
76    /// Build and validate a hybrid public-key pair.
77    pub fn new(ed25519_pub: [u8; ED25519_PUBLIC_KEY_LEN], mldsa65_pub: Vec<u8>) -> Result<Self> {
78        let key = Self {
79            ed25519_pub,
80            mldsa65_pub,
81        };
82        key.verifying_keys()?;
83        Ok(key)
84    }
85
86    /// Derive the public pair corresponding to signing keys.
87    pub fn from_signing_keys(ed25519: &SigningKey, mldsa65: &MlDsaSigningKey) -> Self {
88        Self {
89            ed25519_pub: ed25519.verifying_key().to_bytes(),
90            mldsa65_pub: ml_dsa_sk_to_vk_bytes(mldsa65),
91        }
92    }
93
94    fn to_dag_cbor(&self) -> DagCbor {
95        DagCbor::str_map([
96            ("ed25519Pub", DagCbor::Bytes(self.ed25519_pub.to_vec())),
97            ("mldsa65Pub", DagCbor::Bytes(self.mldsa65_pub.clone())),
98        ])
99    }
100
101    fn from_dag_cbor(value: &DagCbor) -> Result<Self> {
102        require_exact_fields(value, &["ed25519Pub", "mldsa65Pub"], "rotation key")?;
103        let ed25519: [u8; ED25519_PUBLIC_KEY_LEN] = required(value, "ed25519Pub")?
104            .as_bytes()?
105            .try_into()
106            .map_err(|_| anyhow!("Ed25519 public key must be {ED25519_PUBLIC_KEY_LEN} bytes"))?;
107        Self::new(ed25519, required(value, "mldsa65Pub")?.as_bytes()?.to_vec())
108    }
109
110    pub(crate) fn verifying_keys(&self) -> Result<(VerifyingKey, MlDsaVerifyingKey)> {
111        ensure!(
112            self.mldsa65_pub.len() == ML_DSA65_PUBLIC_KEY_LEN,
113            "ML-DSA-65 public key must be {ML_DSA65_PUBLIC_KEY_LEN} bytes"
114        );
115        let ed = VerifyingKey::from_bytes(&self.ed25519_pub)
116            .context("invalid Ed25519 rotation public key")?;
117        let pq = ml_dsa_vk_from_bytes(&self.mldsa65_pub)
118            .context("invalid ML-DSA-65 rotation public key")?;
119        Ok((ed, pq))
120    }
121
122    pub(crate) fn matches_signers(&self, ed25519: &SigningKey, mldsa65: &MlDsaSigningKey) -> bool {
123        self.ed25519_pub == ed25519.verifying_key().to_bytes()
124            && self.mldsa65_pub == ml_dsa_sk_to_vk_bytes(mldsa65)
125    }
126}
127
128/// Mandatory two-component signature stored on a DID operation.
129#[derive(Clone, Debug, Eq, PartialEq)]
130pub struct HybridDidOpSignature {
131    pub ed25519: Vec<u8>,
132    pub mldsa65: Vec<u8>,
133}
134
135impl HybridDidOpSignature {
136    fn placeholder() -> Self {
137        Self {
138            ed25519: vec![0; ED25519_SIGNATURE_LEN],
139            mldsa65: vec![0; ML_DSA65_SIGNATURE_LEN],
140        }
141    }
142
143    pub(crate) fn validate_shape(&self) -> Result<()> {
144        ensure!(
145            self.ed25519.len() == ED25519_SIGNATURE_LEN,
146            "Ed25519 signature must be {ED25519_SIGNATURE_LEN} bytes"
147        );
148        ensure!(
149            self.mldsa65.len() == ML_DSA65_SIGNATURE_LEN,
150            "ML-DSA-65 signature must be {ML_DSA65_SIGNATURE_LEN} bytes"
151        );
152        Ok(())
153    }
154
155    fn to_dag_cbor(&self) -> DagCbor {
156        DagCbor::str_map([
157            ("ed25519", DagCbor::Bytes(self.ed25519.clone())),
158            ("mldsa65", DagCbor::Bytes(self.mldsa65.clone())),
159        ])
160    }
161
162    fn from_dag_cbor(value: &DagCbor) -> Result<Self> {
163        require_exact_fields(value, &["ed25519", "mldsa65"], "DID operation signature")?;
164        let sig = Self {
165            ed25519: required(value, "ed25519")?.as_bytes()?.to_vec(),
166            mldsa65: required(value, "mldsa65")?.as_bytes()?.to_vec(),
167        };
168        sig.validate_shape()?;
169        Ok(sig)
170    }
171}
172
173/// A complete signed genesis or rotation operation.
174#[derive(Clone, Debug, Eq, PartialEq)]
175pub struct DidOp {
176    pub sequence: u64,
177    pub prev: Option<String>,
178    /// Complete active rotation-key state after this operation.
179    pub rotation_keys: Vec<HybridRotationKey>,
180    pub signature: HybridDidOpSignature,
181}
182
183impl DidOp {
184    /// Create and hybrid-sign a genesis operation.
185    ///
186    /// The signer must be one of the genesis operation's declared keys.
187    pub fn signed_genesis(
188        rotation_keys: Vec<HybridRotationKey>,
189        ed25519: &SigningKey,
190        mldsa65: &MlDsaSigningKey,
191    ) -> Result<Self> {
192        validate_rotation_keys(&rotation_keys)?;
193        ensure!(
194            rotation_keys
195                .iter()
196                .any(|key| key.matches_signers(ed25519, mldsa65)),
197            "genesis signer is not one of the declared hybrid rotation keys"
198        );
199        Self::sign(0, None, rotation_keys, ed25519, mldsa65)
200    }
201
202    /// Append and hybrid-sign the next rotation.
203    ///
204    /// Authorization comes only from the immediately previous operation's key
205    /// state. The new key state may remove the signer.
206    pub fn signed_rotation(
207        previous: &Self,
208        rotation_keys: Vec<HybridRotationKey>,
209        ed25519: &SigningKey,
210        mldsa65: &MlDsaSigningKey,
211    ) -> Result<Self> {
212        previous.validate_format()?;
213        validate_rotation_keys(&rotation_keys)?;
214        ensure!(
215            previous
216                .rotation_keys
217                .iter()
218                .any(|key| key.matches_signers(ed25519, mldsa65)),
219            "rotation signer is not authorized by the previous operation"
220        );
221        let sequence = previous
222            .sequence
223            .checked_add(1)
224            .ok_or_else(|| anyhow!("DID operation sequence overflow"))?;
225        Self::sign(
226            sequence,
227            Some(previous.cid().encode()),
228            rotation_keys,
229            ed25519,
230            mldsa65,
231        )
232    }
233
234    fn sign(
235        sequence: u64,
236        prev: Option<String>,
237        rotation_keys: Vec<HybridRotationKey>,
238        ed25519: &SigningKey,
239        mldsa65: &MlDsaSigningKey,
240    ) -> Result<Self> {
241        let mut op = Self {
242            sequence,
243            prev,
244            rotation_keys,
245            signature: HybridDidOpSignature::placeholder(),
246        };
247        let payload = op.signable_bytes();
248        let composite = sign_composite(ed25519, Some(mldsa65), &payload, DID_OP_SIGNATURE_CONTEXT)
249            .context("hybrid-signing DID operation")?;
250        let (ed_sig, pq_sig) =
251            split_composite(&composite).context("splitting DID operation composite signature")?;
252        op.signature = HybridDidOpSignature {
253            ed25519: ed_sig,
254            mldsa65: pq_sig.ok_or_else(|| {
255                anyhow!("hybrid DID operation signing produced no ML-DSA-65 component")
256            })?,
257        };
258        op.validate_format()?;
259        ensure!(
260            op.to_dag_cbor().len() <= MAX_DID_OP_BYTES,
261            "DID operation exceeds {MAX_DID_OP_BYTES}-byte format limit"
262        );
263        Ok(op)
264    }
265
266    /// Canonical unsigned DAG-CBOR bytes covered by both signature components.
267    pub fn signable_bytes(&self) -> Vec<u8> {
268        self.to_dag_cbor_value(false).encode()
269    }
270
271    /// Canonical complete signed DAG-CBOR bytes used for CID/DID derivation.
272    pub fn to_dag_cbor(&self) -> Vec<u8> {
273        self.to_dag_cbor_value(true).encode()
274    }
275
276    /// Strictly decode one canonical operation.
277    pub fn from_dag_cbor(bytes: &[u8]) -> Result<Self> {
278        ensure!(
279            bytes.len() <= MAX_DID_OP_BYTES,
280            "DID operation exceeds {MAX_DID_OP_BYTES}-byte format limit"
281        );
282        let value = DagCbor::decode(bytes).context("decoding canonical DID operation DAG-CBOR")?;
283        require_exact_fields(
284            &value,
285            &["prev", "rotationKeys", "sequence", "sig", "type"],
286            "DID operation",
287        )?;
288        ensure!(
289            required(&value, "type")?.as_str()? == DID_OP_TYPE,
290            "unsupported DID operation type"
291        );
292        let prev = match required(&value, "prev")? {
293            DagCbor::Null => None,
294            DagCbor::Text(cid) => Some(cid.clone()),
295            _ => bail!("DID operation prev must be null or a CID string"),
296        };
297        let rotation_keys = required(&value, "rotationKeys")?
298            .as_list()?
299            .iter()
300            .map(HybridRotationKey::from_dag_cbor)
301            .collect::<Result<Vec<_>>>()?;
302        let op = Self {
303            sequence: required(&value, "sequence")?.as_unsigned()?,
304            prev,
305            rotation_keys,
306            signature: HybridDidOpSignature::from_dag_cbor(required(&value, "sig")?)?,
307        };
308        op.validate_format()?;
309        ensure!(
310            op.to_dag_cbor() == bytes,
311            "DID operation is not in canonical DAG-CBOR form"
312        );
313        Ok(op)
314    }
315
316    /// CIDv1/dag-cbor/SHA-256 address of this complete signed operation.
317    pub fn cid(&self) -> Cid {
318        Cid::from_dag_cbor(&self.to_dag_cbor())
319    }
320
321    /// Derive the self-certifying PLC DID from a signed genesis operation.
322    pub fn genesis_did(&self) -> Result<String> {
323        ensure!(
324            self.sequence == 0 && self.prev.is_none(),
325            "PLC DID can only be derived from a genesis operation"
326        );
327        self.validate_format()?;
328        let digest = Sha256::digest(self.to_dag_cbor());
329        let identifier = base32_nopad_lower(&digest);
330        Ok(format!("did:plc:{}", &identifier[..PLC_IDENTIFIER_LEN]))
331    }
332
333    fn validate_format(&self) -> Result<()> {
334        match (&self.prev, self.sequence) {
335            (None, 0) => {}
336            (Some(_), 0) => bail!("genesis sequence zero must have a null prev"),
337            (Some(prev), _) => validate_cid_text(prev)?,
338            (None, _) => bail!("only sequence zero may have a null prev"),
339        }
340        validate_rotation_keys(&self.rotation_keys)?;
341        self.signature.validate_shape()
342    }
343
344    fn to_dag_cbor_value(&self, include_signature: bool) -> DagCbor {
345        let mut fields = vec![
346            (
347                "prev",
348                self.prev
349                    .as_ref()
350                    .map_or(DagCbor::Null, |cid| DagCbor::Text(cid.clone())),
351            ),
352            (
353                "rotationKeys",
354                DagCbor::list(
355                    self.rotation_keys
356                        .iter()
357                        .map(HybridRotationKey::to_dag_cbor),
358                ),
359            ),
360            ("sequence", DagCbor::Unsigned(self.sequence)),
361            ("type", DagCbor::Text(DID_OP_TYPE.to_owned())),
362        ];
363        if include_signature {
364            fields.push(("sig", self.signature.to_dag_cbor()));
365        }
366        DagCbor::str_map(fields)
367    }
368}
369
370/// Verified head state returned by [`verify_did_op_log`].
371#[derive(Clone, Debug, Eq, PartialEq)]
372pub struct VerifiedDidOpLog {
373    pub did: String,
374    pub sequence: u64,
375    pub head_cid: String,
376    pub rotation_keys: Vec<HybridRotationKey>,
377}
378
379/// Verify a complete linear operation log, failing closed on every discrepancy.
380///
381/// Verification pins Hybrid independently of any runtime crypto policy:
382///
383/// - the genesis DID must match the hash-derived expected DID;
384/// - genesis must verify under one of its own declared hybrid key pairs;
385/// - every rotation must link to the immediately prior signed operation;
386/// - sequence values must increase by exactly one;
387/// - every rotation must verify under one complete pair from the prior state.
388pub fn verify_did_op_log(expected_did: &str, log: &[DidOp]) -> Result<VerifiedDidOpLog> {
389    let genesis = log
390        .first()
391        .ok_or_else(|| anyhow!("DID operation log is empty"))?;
392    genesis
393        .validate_format()
394        .context("invalid genesis format")?;
395    ensure!(
396        genesis.sequence == 0 && genesis.prev.is_none(),
397        "first DID operation is not genesis"
398    );
399    let derived_did = genesis.genesis_did()?;
400    ensure!(
401        expected_did == derived_did,
402        "genesis DID mismatch: expected {expected_did:?}, derived {derived_did:?}"
403    );
404    verify_signature(genesis, &genesis.rotation_keys).context("invalid genesis signature")?;
405
406    for (index, pair) in log.windows(2).enumerate() {
407        let previous = &pair[0];
408        let current = &pair[1];
409        current
410            .validate_format()
411            .with_context(|| format!("invalid operation {} format", index + 1))?;
412        let expected_sequence = previous
413            .sequence
414            .checked_add(1)
415            .ok_or_else(|| anyhow!("DID operation sequence overflow"))?;
416        ensure!(
417            current.sequence == expected_sequence,
418            "operation {} sequence is {}, expected {}",
419            index + 1,
420            current.sequence,
421            expected_sequence
422        );
423        let expected_prev = previous.cid().encode();
424        ensure!(
425            current.prev.as_deref() == Some(expected_prev.as_str()),
426            "operation {} has a broken previous-operation hash link",
427            index + 1
428        );
429        verify_signature(current, &previous.rotation_keys).with_context(|| {
430            format!(
431                "operation {} signature is unauthorized or invalid",
432                index + 1
433            )
434        })?;
435    }
436
437    let head = log
438        .last()
439        .ok_or_else(|| anyhow!("DID operation log is empty"))?;
440    Ok(VerifiedDidOpLog {
441        did: derived_did,
442        sequence: head.sequence,
443        head_cid: head.cid().encode(),
444        rotation_keys: head.rotation_keys.clone(),
445    })
446}
447
448fn verify_signature(op: &DidOp, authorized: &[HybridRotationKey]) -> Result<()> {
449    op.signature.validate_shape()?;
450    let payload = op.signable_bytes();
451    let mut errors = Vec::new();
452
453    for key in authorized {
454        let result = (|| {
455            let (ed, pq) = key.verifying_keys()?;
456            let composite = assemble_composite_nested(
457                (ed.to_bytes().to_vec(), op.signature.ed25519.clone()),
458                Some((ml_dsa_vk_bytes(&pq), op.signature.mldsa65.clone())),
459            )
460            .context("assembling hybrid DID operation signature")?;
461            let verified = verify_composite(
462                &composite,
463                &ed,
464                Some(&pq),
465                &payload,
466                DID_OP_SIGNATURE_CONTEXT,
467                true,
468            )
469            .context("verifying hybrid DID operation signature")?;
470            ensure!(
471                verified.eddsa && verified.ml_dsa,
472                "both hybrid signature components were not verified"
473            );
474            Ok::<(), anyhow::Error>(())
475        })();
476        match result {
477            Ok(()) => return Ok(()),
478            Err(error) => errors.push(error.to_string()),
479        }
480    }
481
482    bail!(
483        "no authorized hybrid rotation key verified both signature components: {}",
484        errors.join("; ")
485    )
486}
487
488fn validate_rotation_keys(keys: &[HybridRotationKey]) -> Result<()> {
489    ensure!(!keys.is_empty(), "rotation key list must not be empty");
490    ensure!(
491        keys.len() <= MAX_ROTATION_KEYS,
492        "rotation key list exceeds maximum of {MAX_ROTATION_KEYS}"
493    );
494    for (index, key) in keys.iter().enumerate() {
495        key.verifying_keys()
496            .with_context(|| format!("invalid rotation key at index {index}"))?;
497        ensure!(
498            !keys[..index].contains(key),
499            "duplicate hybrid rotation key at index {index}"
500        );
501        ensure!(
502            !keys[..index]
503                .iter()
504                .any(|existing| existing.ed25519_pub == key.ed25519_pub),
505            "rotation key at index {index} reuses an Ed25519 component"
506        );
507        ensure!(
508            !keys[..index]
509                .iter()
510                .any(|existing| existing.mldsa65_pub == key.mldsa65_pub),
511            "rotation key at index {index} reuses an ML-DSA-65 component"
512        );
513    }
514    Ok(())
515}
516
517fn validate_cid_text(cid: &str) -> Result<()> {
518    ensure!(
519        cid.len() == CIDV1_DAG_CBOR_SHA256_TEXT_LEN,
520        "previous-operation CID must be {CIDV1_DAG_CBOR_SHA256_TEXT_LEN} characters"
521    );
522    ensure!(
523        cid.starts_with('b')
524            && cid[1..]
525                .bytes()
526                .all(|byte| byte.is_ascii_lowercase() || matches!(byte, b'2'..=b'7')),
527        "previous-operation CID must use canonical base32lower multibase"
528    );
529    Ok(())
530}
531
532fn required<'a>(value: &'a DagCbor, field: &str) -> Result<&'a DagCbor> {
533    value
534        .get(field)
535        .ok_or_else(|| anyhow!("missing required field {field:?}"))
536}
537
538fn require_exact_fields(value: &DagCbor, expected: &[&str], what: &str) -> Result<()> {
539    let map = value
540        .as_map()
541        .with_context(|| format!("{what} must be a map"))?;
542    ensure!(
543        map.len() == expected.len(),
544        "{what} must contain exactly fields {expected:?}"
545    );
546    for field in expected {
547        ensure!(
548            value.get(field).is_some(),
549            "{what} is missing required field {field:?}"
550        );
551    }
552    Ok(())
553}
554
555fn base32_nopad_lower(bytes: &[u8]) -> String {
556    const ALPHABET: &[u8; 32] = b"abcdefghijklmnopqrstuvwxyz234567";
557    let mut output = String::with_capacity((bytes.len() * 8).div_ceil(5));
558    let mut buffer = 0_u64;
559    let mut bits = 0_u32;
560    for &byte in bytes {
561        buffer = (buffer << 8) | u64::from(byte);
562        bits += 8;
563        while bits >= 5 {
564            bits -= 5;
565            output.push(ALPHABET[((buffer >> bits) & 0x1f) as usize] as char);
566        }
567    }
568    if bits > 0 {
569        output.push(ALPHABET[((buffer << (5 - bits)) & 0x1f) as usize] as char);
570    }
571    output
572}
573
574#[cfg(test)]
575#[allow(clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used)]
576mod tests {
577    use super::*;
578    use hyprstream_crypto::pq::{ml_dsa_sk_from_seed, MlDsaSigningKey};
579
580    struct TestKeys {
581        ed: SigningKey,
582        pq: MlDsaSigningKey,
583        public: HybridRotationKey,
584    }
585
586    fn keys(seed: u8) -> TestKeys {
587        let ed = SigningKey::from_bytes(&[seed; 32]);
588        let pq = ml_dsa_sk_from_seed(&[seed.wrapping_add(64); 32]);
589        let public = HybridRotationKey::from_signing_keys(&ed, &pq);
590        TestKeys { ed, pq, public }
591    }
592
593    fn two_op_log() -> (String, Vec<DidOp>) {
594        let first = keys(1);
595        let second = keys(2);
596        let genesis =
597            DidOp::signed_genesis(vec![first.public.clone()], &first.ed, &first.pq).unwrap();
598        let did = genesis.genesis_did().unwrap();
599        let rotation =
600            DidOp::signed_rotation(&genesis, vec![second.public], &first.ed, &first.pq).unwrap();
601        (did, vec![genesis, rotation])
602    }
603
604    #[test]
605    fn genesis_derives_plc_identifier_from_signed_canonical_bytes() {
606        let key = keys(7);
607        let genesis = DidOp::signed_genesis(vec![key.public], &key.ed, &key.pq).unwrap();
608        let digest = Sha256::digest(genesis.to_dag_cbor());
609        let expected = format!(
610            "did:plc:{}",
611            &base32_nopad_lower(&digest)[..PLC_IDENTIFIER_LEN]
612        );
613
614        assert_eq!(genesis.genesis_did().unwrap(), expected);
615        assert_eq!(expected, "did:plc:a3remwhfbs5ozfknkp6krfql");
616        assert_eq!(expected.len(), "did:plc:".len() + PLC_IDENTIFIER_LEN);
617    }
618
619    #[test]
620    fn valid_rotation_chain_verifies_and_returns_head_state() {
621        let (did, log) = two_op_log();
622
623        let verified = verify_did_op_log(&did, &log).unwrap();
624
625        assert_eq!(verified.did, did);
626        assert_eq!(verified.sequence, 1);
627        assert_eq!(verified.head_cid, log[1].cid().encode());
628        assert_eq!(verified.rotation_keys, log[1].rotation_keys);
629    }
630
631    #[test]
632    fn canonical_encoding_round_trips() {
633        let (_, log) = two_op_log();
634        for op in log {
635            let bytes = op.to_dag_cbor();
636            let decoded = DidOp::from_dag_cbor(&bytes).unwrap();
637            assert_eq!(decoded, op);
638            assert_eq!(decoded.to_dag_cbor(), bytes);
639        }
640    }
641
642    #[test]
643    fn broken_hash_link_fails_closed() {
644        let (did, mut log) = two_op_log();
645        log[1].prev = Some(Cid::from_dag_cbor(b"attacker-selected").encode());
646
647        let error = verify_did_op_log(&did, &log).unwrap_err();
648        assert!(error
649            .to_string()
650            .contains("broken previous-operation hash link"));
651    }
652
653    #[test]
654    fn bad_signature_fails_closed() {
655        let (did, mut log) = two_op_log();
656        log[1].signature.ed25519[0] ^= 0x80;
657
658        let error = verify_did_op_log(&did, &log).unwrap_err();
659        assert!(error
660            .to_string()
661            .contains("signature is unauthorized or invalid"));
662    }
663
664    #[test]
665    fn classical_only_signature_fails_at_hybrid_required_position() {
666        let first = keys(11);
667        let second = keys(12);
668        let genesis =
669            DidOp::signed_genesis(vec![first.public.clone()], &first.ed, &first.pq).unwrap();
670        let mut rotation =
671            DidOp::signed_rotation(&genesis, vec![second.public], &first.ed, &first.pq).unwrap();
672        let classical = sign_composite(
673            &first.ed,
674            None,
675            &rotation.signable_bytes(),
676            DID_OP_SIGNATURE_CONTEXT,
677        )
678        .unwrap();
679        let (ed_sig, pq_sig) = split_composite(&classical).unwrap();
680        assert!(pq_sig.is_none());
681        rotation.signature = HybridDidOpSignature {
682            ed25519: ed_sig,
683            mldsa65: Vec::new(),
684        };
685        let did = genesis.genesis_did().unwrap();
686
687        let error = verify_did_op_log(&did, &[genesis, rotation]).unwrap_err();
688        assert!(format!("{error:#}").contains("ML-DSA-65 signature must be"));
689    }
690
691    #[test]
692    fn sequence_gap_fails_closed() {
693        let (did, mut log) = two_op_log();
694        log[1].sequence = 2;
695
696        let error = verify_did_op_log(&did, &log).unwrap_err();
697        assert!(error.to_string().contains("sequence is 2, expected 1"));
698    }
699
700    #[test]
701    fn newly_introduced_key_cannot_authorize_its_own_rotation() {
702        let first = keys(21);
703        let attacker = keys(22);
704        let genesis = DidOp::signed_genesis(vec![first.public], &first.ed, &first.pq).unwrap();
705
706        let error =
707            DidOp::signed_rotation(&genesis, vec![attacker.public], &attacker.ed, &attacker.pq)
708                .unwrap_err();
709        assert!(error.to_string().contains("not authorized"));
710    }
711
712    #[test]
713    fn authority_set_rejects_reused_hybrid_components() {
714        let first = keys(31);
715        let second = keys(32);
716        let repeated_ed =
717            HybridRotationKey::new(first.public.ed25519_pub, second.public.mldsa65_pub.clone())
718                .unwrap();
719        let error = DidOp::signed_genesis(
720            vec![first.public.clone(), repeated_ed],
721            &first.ed,
722            &first.pq,
723        )
724        .unwrap_err();
725        assert!(error.to_string().contains("reuses an Ed25519 component"));
726
727        let repeated_pq =
728            HybridRotationKey::new(second.public.ed25519_pub, first.public.mldsa65_pub.clone())
729                .unwrap();
730        let error = DidOp::signed_genesis(vec![first.public, repeated_pq], &first.ed, &first.pq)
731            .unwrap_err();
732        assert!(error.to_string().contains("reuses an ML-DSA-65 component"));
733    }
734
735    #[test]
736    fn wrong_expected_did_fails_closed() {
737        let (_, log) = two_op_log();
738
739        let error = verify_did_op_log("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", &log).unwrap_err();
740        assert!(error.to_string().contains("genesis DID mismatch"));
741    }
742}