tectonic-bedrock 0.3.0

Tectonic's common cryptography library
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
#![warn(missing_docs)]

//! # Hybrid Hierarchical Deterministic (HD) Wallet Library
//!
//! This library provides a framework for managing hybrid hierarchical deterministic ([HD wallets](https://en.bitcoin.it/wiki/Deterministic_wallet))
//! that support multiple signature schemes from a single [BIP-39 mnemonic seed phrase](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki).
//! It enables seamless coexistence of both classical ([ECDSA secp256k1](https://en.bitcoin.it/wiki/Secp256k1)) and
//! post-quantum ([Falcon-512](https://falcon-sign.info/)) signature schemes within a unified wallet structure.
//! The post-quantum Falcon-512 primitive leverages [Tectonic's Bedrock repository](https://github.com/tectonic-labs/bedrock),
//! which implements FN-DSA (Falcon) in pure Rust via the [`fn-dsa`](https://crates.io/crates/fn-dsa) crates.
//!
//! ## Features
//!
//! - **Multi-Scheme Support**: Derive keys for multiple signature schemes (ECDSA secp256k1, Falcon-512)
//! - **Single Mnemonic**: Use one BIP-39 mnemonic to derive all scheme-specific seeds
//! - **BIP-85 Derivation**: Scheme-specific seed derivation using BIP-85 standard
//! - **BIP-32 & SLIP-0010**: Support for both BIP-32 (ECDSA) and SLIP-0010 (Falcon) HD key derivation
//! - **Deterministic**: All keys are deterministically derived from the master seed
//! - **Cryptographic Separation**: Each signature scheme uses independent derivation paths
//!
//! ## Quick Start
//!
//! ### Creating and Using a Hybrid HD Wallet with ECDSA and Falcon
//! ```ignore
//! // Note: This example requires features: sign, vrfy, eth_falcon
//! use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
//!
//! // Create a new wallet with both ECDSA and Falcon support
//! let wallet = HHDWallet::new(
//!     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
//!     None, // Optional BIP-39 passphrase
//! ).unwrap();
//!
//! // Derive a keypair for ECDSA at address index 0
//! let (ecdsa_sk, ecdsa_vk) = wallet.derive_ecdsa_secp256k1_keypair(
//!     0,
//! ).unwrap();
//!
//! // Sign and verify with ECDSA
//! use tectonic_bedrock::hhd::ecdsa::{Signature, signature::{Verifier, Signer}};
//!
//! let message = b"Hello, world!";
//! let ecdsa_signature: Signature = ecdsa_sk.sign(message);
//! let verified = ecdsa_vk.verify(message, &ecdsa_signature);
//! assert!(verified.is_ok());
//!
//! // Derive a keypair for Falcon at address index 0
//! let (falcon_sk, falcon_vk) = wallet.derive_fn_dsa512_keypair(
//!     0,
//! ).unwrap();
//!
//! // Sign and verify with Falcon
//! use tectonic_bedrock::falcon::FalconScheme;
//! let falcon_signature = FalconScheme::Dsa512.sign(message, &falcon_sk).unwrap();
//! let falcon_verified = FalconScheme::Dsa512.verify(message, &falcon_signature, &falcon_vk);
//! assert!(falcon_verified.is_ok());
//! ```
//!
//! ### Importing a Wallet from an Existing Mnemonic Phrase
//! ```no_run
//! use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme, Mnemonic};
//!
//! // Your BIP-39 phrase (for example, a 24-word phrase)
//! let phrase = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
//! let mnemonic = Mnemonic::from_phrase(phrase).unwrap();
//!
//! // You can optionally provide a BIP-39 passphrase
//! let password = Some("my secret password");
//!
//! // Import the wallet with both ECDSA and Falcon enabled
//! let wallet = HHDWallet::new_from_mnemonic(
//!     mnemonic,
//!     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
//!     password,
//! ).unwrap();
//!
//! // Now, use wallet.derive_ecdsa_secp256k1_keypair, wallet.derive_fn_dsa512_keypair, etc. as above.
//! ```
//!
//! ## Architecture
//!
//!
//! The hybrid HD wallet architecture enables multiple signature schemes to coexist within a single wallet structure while maintaining cryptographic separation.
//!
//! ## Overview
//!
//! The wallet follows a hierarchical derivation model:
//!
//! 1. **Master Mnemonic** (BIP-39): A single 24-word mnemonic phrase serves as the root entropy source for the entire wallet
//! 2. **Scheme-Specific Seeds** (BIP-85): Each signature scheme receives its own 64-byte seed derived from the master mnemonic
//! 3. **Keypairs** (BIP-32/SLIP-0010): Individual keypairs are derived from scheme seeds using address indices
//!
//! This design ensures that:
//! - All keys are deterministically derived from a single mnemonic, allowing them to be restored from the mnemonic alone
//! - Different signature schemes use cryptographically independent seeds
//!
//! ## Derivation Paths
//!
//! ### BIP-85 Scheme Seed Derivation
//!
//! Each signature scheme gets its own unique seed through BIP-85 derivation from the master mnemonic. Two different paths are used for each signature type::
//!
//! - **ECDSA secp256k1**: `m/83696968'/83286642'/1'`
//! - **Falcon-512**: `m/83696968'/83286642'/2'`
//!
//! The base path `m/83696968'` is the standard BIP-85 path, `/83286642'` stands for Tectonic in a T9 keypad, and the final component (`1'` or `2'`) identifies the signature scheme. This ensures that even though both schemes share the same mnemonic, they operate on cryptographically independent seeds.
//!
//! ### Key Derivation Paths
//!
//! Once a scheme-specific seed is obtained, individual keypairs are derived using address indices:
//!
//! **ECDSA secp256k1** (BIP-32, BIP-44):
//! - Domain separator: `Bitcoin seed`
//! - Base path: `m/44'/60'/0'/0`
//! - Full path: `m/44'/60'/0'/0/{address_index}`
//! - Standard: BIP-32 (non-hardened address index)
//! - Example for address index 0: `m/44'/60'/0'/0/0`
//!
//! **Falcon-512** (SLIP-0010, hardened):
//! - Domain separator: `Falcon-512 seed`
//! - Base path: `m/44'/60'/0'/0'`
//! - Full path: `m/44'/60'/0'/0'/{address_index}'`
//! - Standard: SLIP-0010 (all components hardened)
//! - Example for address index 0: `m/44'/60'/0'/0'/0'`
//!
//! ### Key Differences
//!
//! |      Signature       |   ECDSA secp256k1    |  Falcon-512          |
//! |----------------------|----------------------|----------------------|
//! | **BIP-85 Index**     | `1'`                 | `2'`                 |
//! | **HD Standard**      | BIP-32               | SLIP-0010            |
//! | **Domain Separator** | `Bitcoin seed`       | `Falcon-512 seed` |
//! | **Address Index**    | Non-hardened         | Hardened             |
//!
//! For more detailed implementation information, see the [ARCHITECTURE.md](https://github.com/tectonic-labs/bedrock/blob/main/src/hhd/ARCHITECTURE.md) document.
//!
//! ## Standards
//!
//! This library implements the following standards:
//!
//! - [BIP-39]: Mnemonic code for generating deterministic keys
//! - [BIP-32]: Hierarchical Deterministic Wallets
//! - [BIP-44]: Multi-Account Hierarchy for Deterministic Wallets
//! - [BIP-85]: Deterministic Entropy From BIP32 Keychains
//! - [SLIP-0010]: Universal private key derivation from master private key
//!
//! [ARCHITECTURE.md]: https://github.com/tectonic-labs/bedrock/blob/main/src/hhd/ARCHITECTURE.md
//! [BIP-39]: https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki
//! [BIP-32]: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
//! [BIP-44]: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki
//! [BIP-85]: https://github.com/bitcoin/bips/blob/master/bip-0085.mediawiki
//! [SLIP-0010]: https://github.com/satoshilabs/slips/blob/master/slip-0010.md

mod bip85;
mod keys;
mod mnemonic;
mod signatures;
mod slip10;

pub use bip32::secp256k1::ecdsa;
pub use bip85::{Bip85, Bip85Error};
pub use keys::KeyError;
pub use mnemonic::{Mnemonic, MnemonicError};
pub use signatures::{SignatureScheme, SignatureSchemeError, SignatureSeed};
pub use slip10::Slip10Error;

#[cfg(feature = "falcon")]
use crate::falcon::{FalconSigningKey, FalconVerificationKey};
#[cfg(feature = "mayo")]
use crate::mayo::{MayoSigningKey, MayoVerificationKey};
#[cfg(feature = "ml-dsa")]
use crate::ml_dsa::{MlDsaSigningKey, MlDsaVerificationKey};
use bip32::secp256k1::ecdsa::{SigningKey, VerifyingKey};
use keys::EcdsaSecp256k1;
#[cfg(feature = "falcon")]
use keys::FnDsa512;
#[cfg(feature = "mayo")]
use keys::{Mayo1, Mayo2, Mayo3};
#[cfg(feature = "ml-dsa")]
use keys::{MlDsa44, MlDsa65, MlDsa87};
use std::{collections::HashMap, fmt};

/// A Hybrid Hierarchical Deterministic (HD) Wallet derived from a single BIP-39 mnemonic.
///
/// This wallet structure enables managing multiple signature schemes (e.g., ECDSA secp256k1
/// and Falcon-512) from a single BIP-39 mnemonic phrase. Each signature scheme gets its own
/// scheme-specific seed derived using BIP-85, ensuring cryptographic seed separation while
/// maintaining a unified wallet structure.
///
/// # Key Concepts
///
/// - **Master Mnemonic**: A single BIP-39 mnemonic phrase that serves as the root entropy
/// - **Scheme-Specific Seeds**: Each signature scheme has its own derived seed (via BIP-85)
/// - **Address Indexing**: Keys are derived from scheme seeds using hierarchical derivation paths
/// - **Cryptographic Isolation**: Different schemes use different derived seeds
///
/// # Derivation Flow
///
/// 1. **Master Mnemonic** → BIP-39 seed conversion
/// 2. **BIP-85 Derivation** → Scheme-specific seed for each signature scheme
/// 3. **HD Key Derivation** → Keypairs at specific address indices
///    - ECDSA: Uses BIP-32 with BIP-44 paths
///    - Falcon: Uses SLIP-0010 with hardened paths
///
/// # Example
///
/// ```ignore
/// // Note: This example requires features: falcon
/// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
///
/// // Create wallet with both schemes
/// let wallet = HHDWallet::new(
///     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
///     None,
/// ).unwrap();
///
/// // Get the mnemonic (backup this!)
/// let mnemonic_phrase = wallet.mnemonic().to_phrase();
///
/// // Derive keypairs for both schemes at the same address index
/// let (ecdsa_sk, ecdsa_vk) = wallet.derive_ecdsa_secp256k1_keypair(0).unwrap();
/// let (falcon_sk, falcon_vk) = wallet.derive_fn_dsa512_keypair(0).unwrap();
/// ```
pub struct HHDWallet {
    /// Root mnemonic phrase (BIP-39 compatible) used to derive all scheme-specific seeds.
    pub mnemonic: Mnemonic,
    /// Master seeds indexed by signature scheme, derived from the mnemonic using BIP-85.
    /// All seeds are zeroized on drop according to bip32 crate implementation.
    pub master_seeds: HashMap<SignatureScheme, SignatureSeed>,
}

impl fmt::Debug for HHDWallet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HHDWallet")
            .field("mnemonic", &"<redacted>")
            .field("master_seeds", &self.master_seeds)
            .finish()
    }
}

impl HHDWallet {
    /// Creates a new hybrid HD wallet from a given mnemonic phrase.
    ///
    /// This method takes an existing BIP-39 mnemonic and derives scheme-specific seeds
    /// for each provided signature scheme using BIP-85. This allows you to restore a
    /// wallet from a known mnemonic phrase.
    ///
    /// # Arguments
    ///
    /// * `mnemonic` - The BIP-39 mnemonic phrase to derive the wallet from
    /// * `schemes` - A vector of signature schemes to support in this wallet
    /// * `password` - Optional BIP-39 passphrase (adds extra security to the mnemonic)
    ///
    /// # Returns
    ///
    /// * `Ok(HHDWallet)` - The newly created wallet with derived seeds
    /// * `Err(WalletError)` - If seed derivation fails for any scheme
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `Bip85Error`: If BIP-85 seed derivation fails
    /// - `Mnemonic`: If mnemonic processing fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, Mnemonic, SignatureScheme};
    ///
    /// let mnemonic = Mnemonic::from_phrase(
    ///     "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about"
    /// ).unwrap();
    ///
    /// let wallet = HHDWallet::new_from_mnemonic(
    ///     mnemonic,
    ///     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
    ///     None, // Optional passphrase
    /// ).unwrap();
    /// ```
    pub fn new_from_mnemonic(
        mnemonic: Mnemonic,
        schemes: Vec<SignatureScheme>,
        password: Option<&str>,
    ) -> Result<Self, WalletError> {
        let mut master_seeds = HashMap::new();
        for scheme in schemes {
            let child_seed = Bip85::derive_seed_from_mnemonic(mnemonic.clone(), scheme, password)?;
            master_seeds.insert(scheme, child_seed);
        }

        Ok(HHDWallet {
            mnemonic,
            master_seeds,
        })
    }

    /// Creates a new hybrid HD wallet with a randomly generated mnemonic.
    ///
    /// This method generates a new random BIP-39 mnemonic phrase (24 words) and derives
    /// scheme-specific seeds for each provided signature scheme. This is the recommended
    /// way to create a new wallet.
    ///
    /// # Important
    ///
    /// **Backup the mnemonic phrase!** The wallet can only be restored if you have the
    /// mnemonic phrase. Use `wallet.mnemonic().to_phrase()` to get the phrase.
    ///
    /// # Arguments
    ///
    /// * `schemes` - A vector of signature schemes to support in this wallet
    /// * `password` - Optional BIP-39 passphrase (adds extra security layer)
    ///
    /// # Returns
    ///
    /// * `Ok(HHDWallet)` - The newly created wallet with a random mnemonic
    /// * `Err(WalletError)` - If wallet creation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` if seed derivation fails for any scheme.
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// // Create a new wallet supporting both ECDSA and Falcon
    /// let wallet = HHDWallet::new(
    ///     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
    ///     None, // Optional passphrase
    /// ).unwrap();
    ///
    /// // Save the mnemonic phrase for backup
    /// let mnemonic_phrase = wallet.mnemonic().to_phrase();
    /// println!("Your mnemonic phrase: {}", mnemonic_phrase);
    /// ```
    pub fn new(schemes: Vec<SignatureScheme>, password: Option<&str>) -> Result<Self, WalletError> {
        let mnemonic = Mnemonic::new_random();
        Self::new_from_mnemonic(mnemonic, schemes, password)
    }

    /// Gets a reference to the wallet's mnemonic phrase.
    ///
    /// The mnemonic is the root entropy source for the entire wallet. All scheme-specific
    /// seeds are deterministically derived from this mnemonic using BIP-85.
    ///
    /// # Returns
    ///
    /// A reference to the `Mnemonic` instance containing the BIP-39 phrase.
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::EcdsaSecp256k1], None).unwrap();
    /// let mnemonic_phrase = wallet.mnemonic().to_phrase();
    /// println!("Mnemonic: {}", mnemonic_phrase);
    /// ```
    pub fn mnemonic(&self) -> &Mnemonic {
        &self.mnemonic
    }

    /// Gets a reference to the master seeds map.
    ///
    /// Returns a map of signature schemes to their corresponding scheme-specific seeds.
    /// These seeds are derived from the master mnemonic using BIP-85 and serve as the
    /// root for hierarchical key derivation in each scheme.
    ///
    /// # Returns
    ///
    /// A reference to the `HashMap` mapping signature schemes to their seeds.
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(
    ///     vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
    ///     None,
    /// ).unwrap();
    ///
    /// let master_seeds = wallet.master_seeds();
    /// assert!(master_seeds.contains_key(&SignatureScheme::EcdsaSecp256k1));
    /// assert!(master_seeds.contains_key(&SignatureScheme::Falcon512));
    /// ```
    pub fn master_seeds(&self) -> &HashMap<SignatureScheme, SignatureSeed> {
        &self.master_seeds
    }

    /// Derives a ECDSA secp256k1 keypair at the given address index.
    ///
    /// This method derives a ECDSA secp256k1 keypair using the scheme-specific seed and the provided
    /// address index. The derivation path is `m/44'/60'/0'/0/{address_index}` (BIP-44 path).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(SigningKey, VerifyingKey)` - The derived ECDSA secp256k1 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If ECDSA secp256k1 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::EcdsaSecp256k1], None).unwrap();
    ///
    /// // Derive ECDSA keypair at address index 0
    /// let (ecdsa_sk, ecdsa_vk) = wallet.derive_ecdsa_secp256k1_keypair(0).unwrap();
    ///
    /// // Derive another keypair at address index 1
    /// let (ecdsa_sk2, ecdsa_vk2) = wallet.derive_ecdsa_secp256k1_keypair(1).unwrap();
    /// ```
    pub fn derive_ecdsa_secp256k1_keypair(
        &self,
        address_index: u32,
    ) -> Result<(SigningKey, VerifyingKey), WalletError> {
        // 1. Extract child seed for the corresponding scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::EcdsaSecp256k1)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        EcdsaSecp256k1::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "falcon")]
    /// Derives a Falcon-512 keypair at the given address index.
    ///
    /// This method derives a Falcon-512 keypair using the scheme-specific seed and the provided
    /// address index. The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(FalconSigningKey, FalconVerificationKey)` - The derived Falcon-512 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If Falcon-512 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::Falcon512], None).unwrap();
    ///
    /// // Derive ECDSA keypair at address index 0
    /// let (falcon_sk, falcon_vk) = wallet.derive_fn_dsa512_keypair(0).unwrap();
    ///
    /// // Derive another keypair at address index 1
    /// let (falcon_sk2, falcon_vk2) = wallet.derive_fn_dsa512_keypair(1).unwrap();
    /// ```
    pub fn derive_fn_dsa512_keypair(
        &self,
        address_index: u32,
    ) -> Result<(FalconSigningKey, FalconVerificationKey), WalletError> {
        // 1. Extract child seed for the Falcon-512 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::Falcon512)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        FnDsa512::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "ml-dsa")]
    /// Derives an ML-DSA-44 keypair at the given address index.
    ///
    /// # Errors
    ///
    /// Returns [`WalletError::InvalidScheme`] if ML-DSA-44 is not configured in this wallet,
    /// or [`WalletError::KeyError`] if key derivation fails.
    #[deprecated(since = "0.3.0", note = "use derive_mldsa65_keypair")]
    pub fn derive_mldsa44_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MlDsaSigningKey, MlDsaVerificationKey), WalletError> {
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::MlDsa44)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        MlDsa44::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "ml-dsa")]
    /// Derives a ML-DSA-65 keypair at the given address index.
    ///
    /// This method derives a ML-DSA-65 keypair using the scheme-specific seed and the provided
    /// address index. The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(MlDsaSigningKey, MlDsaVerificationKey)` - The derived ML-DSA-65 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If ML-DSA-65 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::MlDsa65], None).unwrap();
    ///
    /// // Derive ML-DSA keypair at address index 0
    /// let (mldsa_sk, mldsa_vk) = wallet.derive_mldsa65_keypair(0).unwrap();
    ///
    /// // Derive another keypair at address index 1
    /// let (mldsa_sk2, mldsa_vk2) = wallet.derive_mldsa65_keypair(1).unwrap();
    /// ```
    pub fn derive_mldsa65_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MlDsaSigningKey, MlDsaVerificationKey), WalletError> {
        // 1. Extract child seed for the ML-DSA 65 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::MlDsa65)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        MlDsa65::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "ml-dsa")]
    /// Derives a ML-DSA-87 keypair at the given address index.
    ///
    /// This method derives a ML-DSA-87 keypair using the scheme-specific seed and the provided
    /// address index. The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(MlDsaSigningKey, MlDsaVerificationKey)` - The derived ML-DSA-87 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If ML-DSA-87 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::MlDsa87], None).unwrap();
    ///
    /// // Derive ML-DSA keypair at address index 0
    /// let (mldsa_sk, mldsa_vk) = wallet.derive_mldsa87_keypair(0).unwrap();
    ///
    /// // Derive another keypair at address index 1
    /// let (mldsa_sk2, mldsa_vk2) = wallet.derive_mldsa87_keypair(1).unwrap();
    /// ```
    pub fn derive_mldsa87_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MlDsaSigningKey, MlDsaVerificationKey), WalletError> {
        // 1. Extract child seed for the ML-DSA 87 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::MlDsa87)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        MlDsa87::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "mayo")]
    /// Derives a MAYO-1 keypair at the given address index.
    ///
    /// The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path). The
    /// 32-byte SLIP-0010 child key is truncated to its first 24 bytes to match the MAYO-1
    /// keygen seed size (SLIP-0010 output is uniform, so truncation preserves the 192-bit
    /// seed security targeted by MAYO-1).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(MayoSigningKey, MayoVerificationKey)` - The derived MAYO-1 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If MAYO-1 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::Mayo1], None).unwrap();
    ///
    /// // Derive MAYO-1 keypair at address index 0
    /// let (mayo_sk, mayo_vk) = wallet.derive_mayo1_keypair(0).unwrap();
    /// ```
    pub fn derive_mayo1_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MayoSigningKey, MayoVerificationKey), WalletError> {
        // 1. Extract child seed for the MAYO-1 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::Mayo1)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        Mayo1::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "mayo")]
    /// Derives a MAYO-2 keypair at the given address index.
    ///
    /// The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path). The
    /// 32-byte SLIP-0010 child key is truncated to its first 24 bytes to match the MAYO-2
    /// keygen seed size (SLIP-0010 output is uniform, so truncation preserves the 192-bit
    /// seed security targeted by MAYO-2).
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(MayoSigningKey, MayoVerificationKey)` - The derived MAYO-2 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If MAYO-2 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::Mayo2], None).unwrap();
    ///
    /// // Derive MAYO-2 keypair at address index 0
    /// let (mayo_sk, mayo_vk) = wallet.derive_mayo2_keypair(0).unwrap();
    /// ```
    pub fn derive_mayo2_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MayoSigningKey, MayoVerificationKey), WalletError> {
        // 1. Extract child seed for the MAYO-2 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::Mayo2)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        Mayo2::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }

    #[cfg(feature = "mayo")]
    /// Derives a MAYO-3 keypair at the given address index.
    ///
    /// The derivation path is `m/44'/60'/0'/0'/{address_index}'` (hardened path). MAYO-3
    /// uses all 32 bytes of the SLIP-0010 child key directly. MAYO-5 is not offered in HHD
    /// because its 40-byte seed would require expansion.
    ///
    /// # Arguments
    ///
    /// * `address_index` - The address index (non-negative integer)
    ///
    /// # Returns
    ///
    /// * `Ok(MayoSigningKey, MayoVerificationKey)` - The derived MAYO-3 keypair
    /// * `Err(WalletError)` - If derivation fails
    ///
    /// # Errors
    ///
    /// Returns `WalletError` in the following cases:
    /// - `InvalidScheme`: If MAYO-3 is not supported in this wallet
    /// - `KeyError`: If key derivation fails
    ///
    /// # Example
    ///
    /// ```
    /// use tectonic_bedrock::hhd::{HHDWallet, SignatureScheme};
    ///
    /// let wallet = HHDWallet::new(vec![SignatureScheme::Mayo3], None).unwrap();
    ///
    /// // Derive MAYO-3 keypair at address index 0
    /// let (mayo_sk, mayo_vk) = wallet.derive_mayo3_keypair(0).unwrap();
    /// ```
    pub fn derive_mayo3_keypair(
        &self,
        address_index: u32,
    ) -> Result<(MayoSigningKey, MayoVerificationKey), WalletError> {
        // 1. Extract child seed for the MAYO-3 scheme
        let signature_seed = self
            .master_seeds
            .get(&SignatureScheme::Mayo3)
            .ok_or(WalletError::InvalidScheme)?;
        let seed_bytes = signature_seed.as_seed().as_bytes();

        Mayo3::derive_from_seed(seed_bytes, address_index).map_err(WalletError::KeyError)
    }
}

/// Errors that can occur during wallet operations.
#[derive(Debug, thiserror::Error)]
pub enum WalletError {
    /// Invalid seed length encountered during operation.
    #[error("Invalid seed length: expected {expected}, got {actual}")]
    InvalidSeedLength {
        /// Expected seed length in bytes
        expected: usize,
        /// Actual seed length in bytes
        actual: usize,
    },
    /// The requested signature scheme is not supported in this wallet.
    #[error("Invalid scheme")]
    InvalidScheme,
    /// Invalid derivation path encountered during key derivation.
    #[error("Invalid derivation path")]
    InvalidDerivationPath,
    /// Invalid HMAC key length during entropy extraction.
    #[error("Invalid HMAC key length: expected {expected}, got {actual}")]
    InvalidHmacKeyLength {
        /// Expected HMAC key length in bytes
        expected: usize,
        /// Actual HMAC key length in bytes
        actual: usize,
    },
    /// Error occurred during mnemonic processing (BIP-39).
    #[error("Mnemonic error: {0}")]
    Bip39(#[from] MnemonicError),
    /// Error occurred during BIP-32 key derivation.
    #[error("BIP32 error: {0}")]
    Bip32(#[from] bip32::Error),
    /// Error occurred in signature scheme configuration or derivation.
    #[error("Signature scheme error: {0}")]
    SignatureSchemeError(#[from] SignatureSchemeError),
    /// Error occurred during key operations (derivation, signing, verification).
    #[error("Key error: {0}")]
    KeyError(#[from] KeyError),
    /// Error occurred during BIP-85 seed derivation.
    #[error("BIP85 error: {0}")]
    Bip85Error(#[from] Bip85Error),
}

#[cfg(feature = "falcon")]
#[test]
fn mnemonic_determinism() {
    let mnemonic = Mnemonic::new_random();
    let schemes = vec![SignatureScheme::Falcon512];

    let wallet1 = HHDWallet::new_from_mnemonic(mnemonic.clone(), schemes.clone(), None).unwrap();
    let wallet2 = HHDWallet::new_from_mnemonic(mnemonic.clone(), schemes.clone(), None).unwrap();

    let keypair1 = wallet1.derive_fn_dsa512_keypair(0).unwrap();
    let keypair2 = wallet2.derive_fn_dsa512_keypair(0).unwrap();

    assert_eq!(keypair1.0, keypair2.0);
    assert_eq!(keypair1.1, keypair2.1);
}

#[cfg(all(feature = "sign", feature = "vrfy"))]
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    #[cfg(feature = "falcon")]
    use crate::falcon::FalconScheme;
    #[cfg(feature = "mayo")]
    use crate::mayo::MayoScheme;
    #[cfg(feature = "ml-dsa")]
    use crate::ml_dsa::MlDsaScheme;
    use bip32::secp256k1::ecdsa::{
        signature::{Signer, Verifier},
        Signature,
    };
    use rstest::rstest;

    #[rstest]
    #[cfg_attr(
        all(feature = "ml-dsa", feature = "sign", feature = "vrfy"),
        case::mldsa44(SignatureScheme::MlDsa44)
    )]
    #[cfg_attr(
        all(feature = "ml-dsa", feature = "sign", feature = "vrfy"),
        case::mldsa65(SignatureScheme::MlDsa65)
    )]
    #[cfg_attr(
        all(feature = "ml-dsa", feature = "sign", feature = "vrfy"),
        case::mldsa87(SignatureScheme::MlDsa87)
    )]
    #[cfg_attr(feature = "ml-dsa", case::mldsa87(SignatureScheme::MlDsa87))]
    #[case::mldsa87(SignatureScheme::MlDsa87)]
    fn test_hhd_wallet_sign_verify_with_schemes(#[case] scheme: SignatureScheme) {
        let wallet = HHDWallet::new(vec![scheme], None).unwrap();
        let message = b"Hello, world!";

        let (sk, vk) = match scheme {
            SignatureScheme::MlDsa44 => wallet.derive_mldsa44_keypair(0).unwrap(),
            SignatureScheme::MlDsa65 => wallet.derive_mldsa65_keypair(0).unwrap(),
            SignatureScheme::MlDsa87 => wallet.derive_mldsa87_keypair(0).unwrap(),
            _ => panic!("Invalid scheme"),
        };
        let signature = match scheme {
            SignatureScheme::MlDsa44 => MlDsaScheme::Dsa44.sign(message, &sk).unwrap(),
            SignatureScheme::MlDsa65 => MlDsaScheme::Dsa65.sign(message, &sk).unwrap(),
            SignatureScheme::MlDsa87 => MlDsaScheme::Dsa87.sign(message, &sk).unwrap(),
            _ => panic!("Invalid scheme"),
        };
        let res = match scheme {
            SignatureScheme::MlDsa44 => MlDsaScheme::Dsa44.verify(message, &signature, &vk),
            SignatureScheme::MlDsa65 => MlDsaScheme::Dsa65.verify(message, &signature, &vk),
            SignatureScheme::MlDsa87 => MlDsaScheme::Dsa87.verify(message, &signature, &vk),
            _ => panic!("Invalid scheme"),
        };
        assert!(res.is_ok());
    }

    #[cfg(all(feature = "falcon", feature = "sign", feature = "vrfy"))]
    #[test]
    fn test_hhd_wallet_sign_verify_with_falcon() {
        let wallet = HHDWallet::new(vec![SignatureScheme::Falcon512], None).unwrap();
        let message = b"Hello, world!";
        let (sk, vk) = wallet.derive_fn_dsa512_keypair(0).unwrap();
        let signature = FalconScheme::Dsa512.sign(message, &sk).unwrap();
        let res = FalconScheme::Dsa512.verify(message, &signature, &vk);
        assert!(res.is_ok());
    }

    #[cfg(all(feature = "mayo", feature = "sign", feature = "vrfy"))]
    #[rstest]
    #[case::mayo1(SignatureScheme::Mayo1, MayoScheme::Mayo1)]
    #[case::mayo2(SignatureScheme::Mayo2, MayoScheme::Mayo2)]
    #[case::mayo3(SignatureScheme::Mayo3, MayoScheme::Mayo3)]
    fn test_hhd_wallet_sign_verify_with_mayo(
        #[case] scheme: SignatureScheme,
        #[case] mayo_scheme: MayoScheme,
    ) {
        let wallet = HHDWallet::new(vec![scheme], None).unwrap();
        let message = b"Hello, world!";
        let (sk, vk) = match scheme {
            SignatureScheme::Mayo1 => wallet.derive_mayo1_keypair(0).unwrap(),
            SignatureScheme::Mayo2 => wallet.derive_mayo2_keypair(0).unwrap(),
            SignatureScheme::Mayo3 => wallet.derive_mayo3_keypair(0).unwrap(),
            _ => panic!("Invalid scheme"),
        };
        let signature = mayo_scheme.sign(message, &sk).unwrap();
        let res = mayo_scheme.verify(message, &signature, &vk);
        assert!(res.is_ok());
    }

    #[test]
    fn test_hhd_wallet_sign_verify_with_ecdsa() {
        let wallet = HHDWallet::new(vec![SignatureScheme::EcdsaSecp256k1], None).unwrap();
        let message = b"Hello, world!";
        let (sk, vk) = wallet.derive_ecdsa_secp256k1_keypair(0).unwrap();
        let signature: Signature = sk.sign(message);
        let res = vk.verify(message, &signature);
        assert!(res.is_ok());
    }

    #[test]
    fn test_hhd_wallet_debug_display() {
        let wallet = HHDWallet::new(
            vec![SignatureScheme::EcdsaSecp256k1, SignatureScheme::Falcon512],
            None,
        )
        .unwrap();
        let debug_display = format!("{:?}", wallet);
        println!("{}", debug_display);
        assert!(debug_display.contains("mnemonic"));
        assert!(debug_display.contains("master_seeds"));
        assert!(debug_display.contains("ECDSAsecp256k1"));
        assert!(debug_display.contains("Falcon512"));
    }
}