vta-keys 0.6.1

VTA key management — master-seed storage, BIP-32 key derivation, key wrapping, and the seed-store backend selection
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
use crate::PreRotationKeyData;
use crate::paths::allocate_path;
use crate::seed_store::SeedStore;
use affinidi_tdk::secrets_resolver::secrets::Secret;
use rand::Rng;
use tracing::{debug, info};
use vti_common::error::{AppError, key_derivation_error};
use vti_common::slip10::{DerivationPath, ExtendedSigningKey};
use vti_common::store::KeyspaceHandle;

/// Derive `count` BIP-32 pre-rotation keys under `base`, returning their
/// public-key-multibase hashes (for `next_key_hashes`) and the full
/// [`PreRotationKeyData`] records. Each key allocates a fresh derivation path
/// from the keys keyspace, so a peek/commit sees monotonically increasing
/// paths. Used by the did:webvh create/update ops and by TEE first-boot DID
/// autogen.
pub async fn derive_pre_rotation_keys(
    seed: &[u8],
    base: &str,
    label: &str,
    keys_ks: &KeyspaceHandle,
    count: u32,
) -> Result<(Vec<String>, Vec<PreRotationKeyData>), AppError> {
    if count == 0 {
        return Ok((vec![], vec![]));
    }

    let root = ExtendedSigningKey::from_seed(seed)
        .map_err(|e| AppError::Internal(format!("failed to create BIP-32 root key: {e}")))?;

    let mut hashes = Vec::with_capacity(count as usize);
    let mut key_data = Vec::with_capacity(count as usize);

    for i in 0..count {
        let path = allocate_path(keys_ks, base)
            .await
            .map_err(|e| AppError::Internal(format!("{e}")))?;
        let derivation_path: DerivationPath = path
            .parse()
            .map_err(|e| AppError::Internal(format!("invalid derivation path: {e}")))?;
        let derived_key = root
            .derive(&derivation_path)
            .map_err(|e| AppError::Internal(format!("key derivation failed: {e}")))?;

        let secret = Secret::generate_ed25519(None, Some(derived_key.signing_key.as_bytes()));
        let pub_mb = secret
            .get_public_keymultibase()
            .map_err(|e| AppError::Internal(format!("{e}")))?;
        let hash = secret
            .get_public_keymultibase_hash()
            .map_err(|e| AppError::Internal(format!("{e}")))?;

        key_data.push(PreRotationKeyData {
            path,
            public_key: pub_mb,
            label: format!("{label} pre-rotation key {i}"),
        });

        hashes.push(hash);
    }

    Ok((hashes, key_data))
}

/// Wrapper holding a derived P-256 secret key.
pub struct P256Secret {
    pub secret_key: p256::SecretKey,
}

pub trait Bip32Extension {
    /// Derive an Ed25519 key pair from a seed and BIP32 derivation path.
    ///
    /// Returns `Secret`.
    fn derive_ed25519(&self, path: &str) -> Result<Secret, AppError>;
    /// Derive an X25519 key pair from a seed and BIP32 derivation path.
    ///
    /// Returns `Secret`.
    fn derive_x25519(&self, path: &str) -> Result<Secret, AppError>;
    /// Derive a P-256 key pair from a seed and BIP32 derivation path.
    ///
    /// Uses HMAC-SHA512 domain separation to produce P-256 key material
    /// independent from the Ed25519 key at the same path. This avoids
    /// cross-curve key reuse, Ed25519 clamping artifacts, and group-order bias.
    fn derive_p256(&self, path: &str) -> Result<P256Secret, AppError>;

    /// Derive an ML-DSA-44 (FIPS 204) key pair from a seed and BIP32 path.
    ///
    /// Domain-separated for the same reason as [`Self::derive_p256`], and it is
    /// the whole reason this is not a two-line function. `derive_ed25519` feeds
    /// the SLIP-0010 output straight to the key constructor; doing that here
    /// would make the ML-DSA seed **equal to the Ed25519 private key at the same
    /// path**, so compromising either would yield the other. The label also
    /// differs per parameter set: ML-DSA-44 and ML-DSA-65 are different
    /// algorithms and must not share a seed either.
    ///
    /// Simpler than P-256 in one respect — FIPS 204 KeyGen takes xi as 32
    /// arbitrary bytes with no group-order constraint, so there is no reduction
    /// and no retry loop. Any 32 bytes is a valid seed.
    fn derive_ml_dsa_44(&self, path: &str) -> Result<Secret, AppError>;

    /// Derive an ML-DSA-65 (FIPS 204) key pair from a seed and BIP32 path.
    ///
    /// See [`Self::derive_ml_dsa_44`]; this uses a distinct domain label so the
    /// two parameter sets never share key material at one path.
    fn derive_ml_dsa_65(&self, path: &str) -> Result<Secret, AppError>;
}

impl Bip32Extension for ExtendedSigningKey {
    fn derive_ed25519(&self, path: &str) -> Result<Secret, AppError> {
        let derivation_path: DerivationPath = path
            .parse()
            .map_err(|e| key_derivation_error(format!("invalid derivation path: {e}")))?;

        let derived = self
            .derive(&derivation_path)
            .map_err(|e| key_derivation_error(format!("derivation failed: {e}")))?;

        Ok(Secret::generate_ed25519(
            None,
            Some(derived.signing_key.as_bytes()),
        ))
    }

    fn derive_x25519(&self, path: &str) -> Result<Secret, AppError> {
        let derivation_path: DerivationPath = path
            .parse()
            .map_err(|e| key_derivation_error(format!("invalid derivation path: {e}")))?;

        let derived = self
            .derive(&derivation_path)
            .map_err(|e| key_derivation_error(format!("derivation failed: {e}")))?;

        // Use the same conversion path as DID creation (keys/mod.rs derive_entity_keys):
        // generate Ed25519 secret, then convert to X25519 via Secret::to_x25519().
        // This ensures the runtime key matches the public key in the DID document.
        let ed_secret = Secret::generate_ed25519(None, Some(derived.signing_key.as_bytes()));
        ed_secret
            .to_x25519()
            .map_err(|e| key_derivation_error(format!("X25519 conversion failed: {e}")))
    }

    fn derive_p256(&self, path: &str) -> Result<P256Secret, AppError> {
        use hmac::{Hmac, KeyInit, Mac};
        use sha2::Sha512;

        let derivation_path: DerivationPath = path
            .parse()
            .map_err(|e| key_derivation_error(format!("invalid derivation path: {e}")))?;

        let derived = self
            .derive(&derivation_path)
            .map_err(|e| key_derivation_error(format!("derivation failed: {e}")))?;

        // Domain-separated derivation via HMAC-SHA512.
        // Prevents cross-curve key reuse: the same BIP-32 path produces
        // independent key material for Ed25519 and P-256.
        let mut mac = Hmac::<Sha512>::new_from_slice(b"p256-key-derivation")
            .expect("HMAC accepts any key length");
        mac.update(derived.signing_key.as_bytes());
        mac.update(&derived.chain_code);
        let hmac_output = mac.finalize().into_bytes();

        // First 32 bytes → P-256 scalar. from_bytes() reduces mod n automatically.
        //
        // `TryFrom` rather than the deprecated `FieldBytes::from_slice`: the
        // slice is a fixed 32-byte window of a SHA-512 HMAC so the conversion
        // cannot fail, but the fallible form is the supported one in
        // elliptic-curve 0.14 and it keeps the length check explicit rather
        // than resting on a panic inside the old helper.
        let field_bytes = p256::FieldBytes::try_from(&hmac_output[..32])
            .map_err(|e| key_derivation_error(format!("P-256 scalar is not 32 bytes: {e}")))?;
        let secret_key = p256::SecretKey::from_bytes(&field_bytes)
            .map_err(|e| key_derivation_error(format!("P-256 key creation failed: {e}")))?;

        Ok(P256Secret { secret_key })
    }

    fn derive_ml_dsa_44(&self, path: &str) -> Result<Secret, AppError> {
        let seed = self.domain_separated_seed(path, b"ml-dsa-44-key-derivation")?;
        Ok(Secret::generate_ml_dsa_44(None, Some(&seed)))
    }

    fn derive_ml_dsa_65(&self, path: &str) -> Result<Secret, AppError> {
        let seed = self.domain_separated_seed(path, b"ml-dsa-65-key-derivation")?;
        Ok(Secret::generate_ml_dsa_65(None, Some(&seed)))
    }
}

/// The HMAC-SHA512 domain separation both post-quantum derivations use.
///
/// Extracted rather than written twice because the two differ only in the
/// label, and a second copy is how the two parameter sets would eventually
/// come to disagree about how a seed is produced — which is unrecoverable
/// rather than merely wrong, since the key cannot be re-derived afterwards.
///
/// Mirrors `derive_p256`'s construction exactly: HMAC-SHA512 over the derived
/// signing key and chain code, keyed by the label, first 32 bytes taken.
trait DomainSeparatedSeed {
    fn domain_separated_seed(&self, path: &str, label: &[u8]) -> Result<[u8; 32], AppError>;
}

impl DomainSeparatedSeed for ExtendedSigningKey {
    fn domain_separated_seed(&self, path: &str, label: &[u8]) -> Result<[u8; 32], AppError> {
        use hmac::{Hmac, KeyInit, Mac};
        use sha2::Sha512;

        let derivation_path: DerivationPath = path
            .parse()
            .map_err(|e| key_derivation_error(format!("invalid derivation path: {e}")))?;

        let derived = self
            .derive(&derivation_path)
            .map_err(|e| key_derivation_error(format!("derivation failed: {e}")))?;

        let mut mac = Hmac::<Sha512>::new_from_slice(label).expect("HMAC accepts any key length");
        mac.update(derived.signing_key.as_bytes());
        mac.update(&derived.chain_code);
        let out = mac.finalize().into_bytes();

        out[..32].try_into().map_err(|_| {
            key_derivation_error("HMAC-SHA512 output is shorter than 32 bytes".to_string())
        })
    }
}

/// Load an existing master seed from the store, or generate/derive a new one.
///
/// - If `mnemonic` is provided, validates it as a BIP-39 phrase and derives a
///   64-byte seed via PBKDF2 (with an empty passphrase), then stores it.
/// - If no mnemonic and a seed already exists, returns the existing seed.
/// - If no mnemonic and no seed exists, generates 32 random bytes and stores them.
///
/// `dead_code` allowed: called by the `vta-enclave` binary's bootstrap
/// path, which compiles in a different crate. rustc's dead-code lint
/// doesn't see the cross-crate usage.
#[allow(dead_code)]
pub async fn load_or_generate_seed(
    seed_store: &dyn SeedStore,
    mnemonic: Option<&str>,
) -> Result<ExtendedSigningKey, AppError> {
    if let Some(phrase) = mnemonic {
        let m = bip39::Mnemonic::parse(phrase)
            .map_err(|e| key_derivation_error(format!("invalid BIP-39 mnemonic: {e}")))?;
        let seed = m.to_seed("");
        seed_store.set(&seed).await?;
        info!("master seed derived from mnemonic and stored");
        return ExtendedSigningKey::from_seed(&seed).map_err(|e| {
            key_derivation_error(format!(
                "Couldn't create bip32 root signing key! Reason: {e}"
            ))
        });
    }

    if let Some(existing) = seed_store.get().await? {
        debug!("master seed loaded from store");
        // Master seed in plaintext — wipe on drop (P0.7).
        let existing = zeroize::Zeroizing::new(existing);
        return ExtendedSigningKey::from_seed(&existing).map_err(|e| {
            key_derivation_error(format!(
                "Couldn't create bip32 root signing key! Reason: {e}"
            ))
        });
    }

    let mut seed = zeroize::Zeroizing::new([0u8; 32]);
    rand::rng().fill_bytes(&mut *seed);
    seed_store.set(&*seed).await?;
    info!("new random master seed generated and stored");
    ExtendedSigningKey::from_seed(&*seed).map_err(|e| {
        key_derivation_error(format!(
            "Couldn't create bip32 root signing key! Reason: {e}"
        ))
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use p256::elliptic_curve::sec1::ToSec1Point;

    /// The raw key material inside a multibase private key, with the
    /// multicodec prefix removed.
    ///
    /// Needed because the codec differs between Ed25519 and ML-DSA, so
    /// comparing the encoded strings would report "different" even if the
    /// underlying 32 bytes were identical — which is precisely the failure the
    /// tests below exist to catch.
    fn seed_of(multibase_key: &str) -> Vec<u8> {
        let (_base, bytes) = multibase::decode(multibase_key).expect("valid multibase");
        // Every codec used here is a 2-byte unsigned varint.
        bytes[2..].to_vec()
    }

    fn get_bip32() -> ExtendedSigningKey {
        ExtendedSigningKey::from_seed(&[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ])
        .unwrap()
    }

    #[test]
    fn test_derive_ed25519_deterministic() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let secret = bip32.derive_ed25519(path).unwrap();

        assert_eq!(
            secret.get_private_keymultibase().unwrap(),
            "z3u2RHYaCxd1wzvJB6wQEcnrLth65xcNHcGDDSdfwDjmkoG3".to_string()
        );
        assert_eq!(
            secret.get_public_keymultibase().unwrap(),
            "z6MkestKNR7EyyB8yojbPcRoG8rF6iX4uXYkyVbDBsM9Fj5i".to_string()
        );
    }

    #[test]
    fn test_derive_ed25519_different_paths() {
        let bip32 = get_bip32();

        let secret1 = bip32.derive_ed25519("m/44'/0'/0'").unwrap();
        let secret2 = bip32.derive_ed25519("m/44'/0'/1'").unwrap();

        assert_eq!(
            secret1.get_private_keymultibase().unwrap(),
            "z3u2RHYaCxd1wzvJB6wQEcnrLth65xcNHcGDDSdfwDjmkoG3".to_string()
        );
        assert_eq!(
            secret1.get_public_keymultibase().unwrap(),
            "z6MkestKNR7EyyB8yojbPcRoG8rF6iX4uXYkyVbDBsM9Fj5i".to_string()
        );
        assert_eq!(
            secret2.get_private_keymultibase().unwrap(),
            "z3u2iLUGo3YPXjUFE6LR2z1f84ufRDe4PEeQpvA9dPU8HZ1G".to_string()
        );
        assert_eq!(
            secret2.get_public_keymultibase().unwrap(),
            "z6Mkw5tnbEgzv7zc4SJmSACo6FbfKLHveK4dCHjar8h2voDE".to_string()
        );
    }

    #[test]
    fn test_derive_x25519_deterministic() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let secret = bip32.derive_x25519(path).unwrap();

        assert_eq!(
            secret.get_private_keymultibase().unwrap(),
            "z3wenSajog3TCG3QxA8yVvEniVxp2QU9mE3fYgDYQj8j6MHo".to_string()
        );
        assert_eq!(
            secret.get_public_keymultibase().unwrap(),
            "z6LStYM3H4UG8qn79pQwGmSRd81VMETBPjH49uf5SeqJBB7G".to_string()
        );
    }

    #[test]
    fn test_derive_x25519_differs_from_ed25519() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let ed_secret = bip32.derive_ed25519(path).unwrap();
        let x_secret = bip32.derive_x25519(path).unwrap();

        assert_ne!(
            ed_secret.get_public_keymultibase().unwrap(),
            x_secret.get_private_keymultibase().unwrap()
        );
    }

    #[test]
    fn test_invalid_path() {
        let bip32 = get_bip32();
        let result = bip32.derive_ed25519("not/a/valid/path");
        assert!(result.is_err());
    }

    #[test]
    fn test_bip39_seed_deterministic() {
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let m1 = bip39::Mnemonic::parse(phrase).unwrap();
        let m2 = bip39::Mnemonic::parse(phrase).unwrap();
        assert_eq!(m1.to_seed(""), m2.to_seed(""));
        // BIP-39 produces a 64-byte seed
        assert_eq!(m1.to_seed("").len(), 64);
    }

    #[test]
    fn test_bip39_invalid_mnemonic() {
        let result = bip39::Mnemonic::parse("not a valid mnemonic");
        assert!(result.is_err());
    }

    // -----------------------------------------------------------------------
    // Key creation ↔ recovery consistency tests
    //
    // These simulate the two code paths that must agree:
    //   Creation:  derive_entity_keys() in keys/mod.rs  (DID document keys)
    //   Recovery:  init_auth() in server.rs              (restart re-derivation)
    // -----------------------------------------------------------------------

    /// Simulate DID-creation for Ed25519: manual BIP-32 derive → Secret::generate_ed25519.
    /// This mirrors what `derive_entity_keys()` does.
    fn creation_path_ed25519(seed: &[u8], path: &str) -> Secret {
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        let dp: DerivationPath = path.parse().unwrap();
        let derived = root.derive(&dp).unwrap();
        Secret::generate_ed25519(None, Some(derived.signing_key.as_bytes()))
    }

    /// Simulate DID-creation for X25519: manual BIP-32 derive → Ed25519 → to_x25519.
    /// This mirrors what `derive_entity_keys()` does.
    fn creation_path_x25519(seed: &[u8], path: &str) -> Secret {
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        let dp: DerivationPath = path.parse().unwrap();
        let derived = root.derive(&dp).unwrap();
        let ed = Secret::generate_ed25519(None, Some(derived.signing_key.as_bytes()));
        ed.to_x25519().unwrap()
    }

    /// Simulate recovery for Ed25519: Bip32Extension::derive_ed25519.
    /// This mirrors what `init_auth()` does on restart.
    fn recovery_path_ed25519(seed: &[u8], path: &str) -> Secret {
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        root.derive_ed25519(path).unwrap()
    }

    /// Simulate recovery for X25519: Bip32Extension::derive_x25519.
    /// This mirrors what `init_auth()` does on restart.
    fn recovery_path_x25519(seed: &[u8], path: &str) -> Secret {
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        root.derive_x25519(path).unwrap()
    }

    #[test]
    fn test_ed25519_creation_matches_recovery() {
        let seed = &[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ];
        for path in ["m/44'/0'/0'", "m/44'/0'/1'", "m/44'/0'/99'"] {
            let created = creation_path_ed25519(seed, path);
            let recovered = recovery_path_ed25519(seed, path);

            assert_eq!(
                created.get_public_keymultibase().unwrap(),
                recovered.get_public_keymultibase().unwrap(),
                "Ed25519 public key mismatch at path {path}: creation vs recovery"
            );
            assert_eq!(
                created.get_private_keymultibase().unwrap(),
                recovered.get_private_keymultibase().unwrap(),
                "Ed25519 private key mismatch at path {path}: creation vs recovery"
            );
        }
    }

    #[test]
    fn test_x25519_creation_matches_recovery() {
        let seed = &[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ];
        for path in ["m/44'/0'/0'", "m/44'/0'/1'", "m/44'/0'/99'"] {
            let created = creation_path_x25519(seed, path);
            let recovered = recovery_path_x25519(seed, path);

            assert_eq!(
                created.get_public_keymultibase().unwrap(),
                recovered.get_public_keymultibase().unwrap(),
                "X25519 public key mismatch at path {path}: creation vs recovery \
                 (the key in the DID document would not match the runtime key)"
            );
            assert_eq!(
                created.get_private_keymultibase().unwrap(),
                recovered.get_private_keymultibase().unwrap(),
                "X25519 private key mismatch at path {path}: creation vs recovery"
            );
        }
    }

    /// Multiple re-derivations from the same seed + path must produce identical
    /// keys (simulates multiple VTA restarts).
    #[test]
    fn test_multiple_restarts_produce_identical_keys() {
        let seed = &[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ];
        let sign_path = "m/44'/0'/0'";
        let ka_path = "m/44'/0'/1'";

        let first_sign = recovery_path_ed25519(seed, sign_path);
        let first_ka = recovery_path_x25519(seed, ka_path);

        for i in 1..=5 {
            let sign = recovery_path_ed25519(seed, sign_path);
            let ka = recovery_path_x25519(seed, ka_path);

            assert_eq!(
                first_sign.get_public_keymultibase().unwrap(),
                sign.get_public_keymultibase().unwrap(),
                "Ed25519 public key drifted on restart {i}"
            );
            assert_eq!(
                first_ka.get_public_keymultibase().unwrap(),
                ka.get_public_keymultibase().unwrap(),
                "X25519 public key drifted on restart {i}"
            );
        }
    }

    /// BIP-39 mnemonic → seed → keys must be fully deterministic.
    #[test]
    fn test_bip39_seed_to_keys_deterministic() {
        let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
        let m = bip39::Mnemonic::parse(phrase).unwrap();
        let seed = m.to_seed("");

        let sign1 = creation_path_ed25519(&seed, "m/44'/0'/0'");
        let ka1 = creation_path_x25519(&seed, "m/44'/0'/1'");

        // Repeat from mnemonic
        let m2 = bip39::Mnemonic::parse(phrase).unwrap();
        let seed2 = m2.to_seed("");
        let sign2 = recovery_path_ed25519(&seed2, "m/44'/0'/0'");
        let ka2 = recovery_path_x25519(&seed2, "m/44'/0'/1'");

        assert_eq!(
            sign1.get_public_keymultibase().unwrap(),
            sign2.get_public_keymultibase().unwrap(),
            "Ed25519 key not deterministic from same mnemonic"
        );
        assert_eq!(
            ka1.get_public_keymultibase().unwrap(),
            ka2.get_public_keymultibase().unwrap(),
            "X25519 key not deterministic from same mnemonic"
        );
    }

    /// The stored ka_priv (Ed25519 seed bytes at the KA derivation path) must
    /// reconstruct the same X25519 key when fed through the canonical conversion.
    /// This is how DidSecretsBundle and external importers reconstruct keys.
    #[test]
    fn test_ka_priv_reconstructs_x25519() {
        let seed = &[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ];
        let ka_path = "m/44'/0'/1'";

        // Simulate derive_entity_keys: get ka_priv (Ed25519 seed bytes, multibase)
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        let dp: DerivationPath = ka_path.parse().unwrap();
        let derived = root.derive(&dp).unwrap();
        let ka_priv = multibase::encode(multibase::Base::Base58Btc, derived.signing_key.as_bytes());

        // Original X25519 key (as would be in DID document)
        let original = creation_path_x25519(seed, ka_path);
        let original_pub = original.get_public_keymultibase().unwrap();

        // Reconstruct from ka_priv (as an external importer would)
        let (_, raw_bytes) = multibase::decode(&ka_priv).unwrap();
        let seed_arr: &[u8; 32] = raw_bytes.as_slice().try_into().unwrap();
        let reconstructed_ed = Secret::generate_ed25519(None, Some(seed_arr));
        let reconstructed_x = reconstructed_ed.to_x25519().unwrap();
        let reconstructed_pub = reconstructed_x.get_public_keymultibase().unwrap();

        assert_eq!(
            original_pub, reconstructed_pub,
            "X25519 key reconstructed from stored ka_priv does not match DID document key"
        );
    }

    /// Ensure the signing key's public multibase matches what ed25519_multibase_pubkey
    /// produces (the format used in DID documents and did:key identifiers).
    #[test]
    fn test_signing_pub_matches_did_document_format() {
        let seed = &[
            7, 26, 142, 230, 65, 85, 188, 182, 29, 129, 52, 229, 217, 159, 243, 182, 73, 89, 196,
            246, 58, 28, 100, 144, 187, 21, 157, 39, 4, 188, 154, 180,
        ];
        let path = "m/44'/0'/0'";

        // What derive_entity_keys stores as signing_pub
        let secret = creation_path_ed25519(seed, path);
        let signing_pub = secret.get_public_keymultibase().unwrap();

        // What the DID document formatter produces from raw bytes
        let root = ExtendedSigningKey::from_seed(seed).unwrap();
        let dp: DerivationPath = path.parse().unwrap();
        let derived = root.derive(&dp).unwrap();
        let raw_pub = ed25519_dalek::SigningKey::from_bytes(derived.signing_key.as_bytes())
            .verifying_key()
            .to_bytes();
        let did_doc_pub = vta_sdk::did_key::ed25519_multibase_pubkey(&raw_pub);

        assert_eq!(
            signing_pub, did_doc_pub,
            "Secret::get_public_keymultibase() does not match ed25519_multibase_pubkey()"
        );
    }

    // -----------------------------------------------------------------------
    // P-256 key derivation tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_derive_p256_deterministic() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let p256_1 = bip32.derive_p256(path).unwrap();
        let p256_2 = bip32.derive_p256(path).unwrap();

        // Same seed + path must produce the same key
        assert_eq!(p256_1.secret_key.to_bytes(), p256_2.secret_key.to_bytes());

        // Public key must be derivable
        let pk = p256_1.secret_key.public_key();
        let encoded = pk.to_sec1_point(true);
        assert_eq!(
            encoded.len(),
            33,
            "compressed P-256 pubkey should be 33 bytes"
        );
    }

    #[test]
    fn test_derive_p256_different_paths() {
        let bip32 = get_bip32();

        let p256_1 = bip32.derive_p256("m/44'/0'/0'").unwrap();
        let p256_2 = bip32.derive_p256("m/44'/0'/1'").unwrap();

        assert_ne!(
            p256_1.secret_key.to_bytes(),
            p256_2.secret_key.to_bytes(),
            "different paths must produce different keys"
        );
    }

    #[test]
    fn test_derive_p256_sign_verify() {
        let bip32 = get_bip32();
        let p256_secret = bip32.derive_p256("m/44'/0'/0'").unwrap();

        let signing_key = p256::ecdsa::SigningKey::from(&p256_secret.secret_key);
        let verifying_key = p256::ecdsa::VerifyingKey::from(&signing_key);

        use p256::ecdsa::signature::{Signer, Verifier};
        let message = b"hello VTA signing oracle";
        let sig: p256::ecdsa::Signature = signing_key.sign(message);

        assert!(verifying_key.verify(message, &sig).is_ok());
    }

    #[test]
    fn test_derive_p256_invalid_path() {
        let bip32 = get_bip32();
        let result = bip32.derive_p256("not/a/valid/path");
        assert!(result.is_err());
    }

    /// The post-quantum seed must not equal the Ed25519 private key at the same
    /// path.
    ///
    /// This is the property the domain separation exists for, and it is the one
    /// a naive implementation gets wrong: `derive_ed25519` hands the SLIP-0010
    /// output straight to the key constructor, and ML-DSA's constructor takes a
    /// 32-byte seed, so the two line up and the obvious code compiles and looks
    /// right. It would mean compromising either key yields the other.
    #[test]
    fn ml_dsa_seed_is_independent_of_the_ed25519_key_at_the_same_path() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let ed = bip32.derive_ed25519(path).unwrap();
        let ml44 = bip32.derive_ml_dsa_44(path).unwrap();
        let ml65 = bip32.derive_ml_dsa_65(path).unwrap();

        // Compared as multibase because that is the persisted form and the
        // raw bytes are `pub(crate)` upstream. The codec prefix differs
        // between Ed25519 and ML-DSA, so this compares the *material* by
        // decoding past it — the seeds are both 32 bytes, which is exactly why
        // the collision is easy to write by accident.
        let ed_mb = ed.get_private_keymultibase().unwrap();
        let ml44_mb = ml44.get_private_keymultibase().unwrap();
        let ml65_mb = ml65.get_private_keymultibase().unwrap();

        assert_ne!(
            seed_of(&ml44_mb),
            seed_of(&ed_mb),
            "ML-DSA-44 seed equals the Ed25519 private key — domain separation is not applied"
        );
        assert_ne!(
            seed_of(&ml65_mb),
            seed_of(&ed_mb),
            "ML-DSA-65 seed equals the Ed25519 private key — domain separation is not applied"
        );
    }

    /// The two parameter sets must not share a seed either.
    ///
    /// ML-DSA-44 and ML-DSA-65 are different algorithms; deriving both at one
    /// path with one label would make a holder of the -44 key able to
    /// reconstruct the -65 one. The labels differ for that reason and nothing
    /// else, so this is the only thing asserting they still do.
    #[test]
    fn the_two_ml_dsa_parameter_sets_get_independent_seeds() {
        let bip32 = get_bip32();
        let path = "m/44'/0'/0'";

        let a = bip32.derive_ml_dsa_44(path).unwrap();
        let b = bip32.derive_ml_dsa_65(path).unwrap();

        assert_ne!(
            seed_of(&a.get_private_keymultibase().unwrap()),
            seed_of(&b.get_private_keymultibase().unwrap()),
            "ML-DSA-44 and ML-DSA-65 share a seed — the domain labels are not distinct"
        );
        // Different parameter sets: ML-DSA-65's verifying key is 1952 bytes to
        // ML-DSA-44's 1312, so the encodings cannot be the same length.
        assert!(
            b.get_public_keymultibase().unwrap().len() > a.get_public_keymultibase().unwrap().len(),
            "ML-DSA-65's verifying key should encode longer than ML-DSA-44's"
        );
    }

    /// Derivation is deterministic — the property the whole BIP-32 chain exists
    /// for, and what makes a derived post-quantum key recoverable from the
    /// mnemonic rather than stranded like an internal one.
    #[test]
    fn ml_dsa_derivation_is_deterministic() {
        let path = "m/44'/0'/1'";
        let first = get_bip32().derive_ml_dsa_44(path).unwrap();
        let second = get_bip32().derive_ml_dsa_44(path).unwrap();

        assert_eq!(
            first.get_private_keymultibase().unwrap(),
            second.get_private_keymultibase().unwrap()
        );
        assert_eq!(
            first.get_public_keymultibase().unwrap(),
            second.get_public_keymultibase().unwrap()
        );

        // A different path gives different material, or the path is being ignored.
        let other = get_bip32().derive_ml_dsa_44("m/44'/0'/2'").unwrap();
        assert_ne!(
            first.get_private_keymultibase().unwrap(),
            other.get_private_keymultibase().unwrap()
        );
    }
}