cardano-crypto 1.0.8

Pure Rust implementation of Cardano cryptographic primitives (VRF, KES, DSIGN, Hash) with 100% compatibility with cardano-node
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
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
//! Ed25519 digital signature implementation
//!
//! Provides a pure Rust implementation of the Ed25519 signature algorithm that is
//! fully compatible with Cardano's signature verification. Ed25519 is the primary
//! signature scheme used in Cardano for:
//!
//! - Transaction signing and verification
//! - Stake pool operator keys
//! - Payment address authentication
//! - Governance actions
//!
//! # Specification
//!
//! - **Algorithm**: Ed25519 (Edwards-curve Digital Signature Algorithm)
//! - **Curve**: Edwards25519 (twisted Edwards form of Curve25519)
//! - **Security Level**: 128 bits (equivalent to 256-bit symmetric encryption)
//! - **Public Key**: 32 bytes
//! - **Signature**: 64 bytes
//! - **Secret Key**: 64 bytes (32-byte seed + 32-byte public key, Cardano format)
//!
//! # Cardano Compatibility
//!
//! This implementation follows the same Ed25519 format used by Cardano nodes,
//! ensuring full interoperability. Signatures generated here can be verified
//! by Cardano and vice versa.
//!
//! # Security Features
//!
//! - Constant-time operations to prevent timing attacks
//! - Protection against side-channel attacks
//! - Deterministic signatures (no random number generation during signing)
//! - Small keys and signatures for efficient storage and transmission
//!
//! # Examples
//!
//! ```
//! use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
//!
//! // Generate keypair from seed
//! let seed = [42u8; 32];
//! let signing_key = Ed25519::gen_key(&seed);
//! let verification_key = Ed25519::derive_verification_key(&signing_key);
//!
//! // Sign a message
//! let message = b"Cardano transaction";
//! let signature = Ed25519::sign(&signing_key, message);
//!
//! // Verify the signature
//! assert!(Ed25519::verify(&verification_key, message, &signature).is_ok());
//! ```

use crate::common::CryptoError;

use ed25519_dalek::{
    Signature as DalekSignature, SigningKey as DalekSigningKey, VerifyingKey as DalekVerifyingKey,
};
use ed25519_dalek::{Signer, Verifier};

const SEED_SIZE: usize = 32;
const VERIFICATION_KEY_SIZE: usize = 32;
const SIGNATURE_SIZE: usize = 64;
const SECRET_COMPOUND_SIZE: usize = 64;

/// Ed25519 verification (public) key
///
/// A 32-byte compressed Edwards curve point representing the public verification key.
/// This key is derived from the signing key and can be safely shared publicly.
///
/// # Format
///
/// The key is stored as a compressed Edwards curve point in canonical Ed25519 format:
/// - 32 bytes representing the Y coordinate and sign bit
/// - Valid points must lie on the Edwards25519 curve
///
/// # Usage
///
/// - Share publicly for signature verification
/// - Use as input to verification operations
/// - Derive Cardano addresses
/// - Identify stake pools and payment credentials
///
/// # Examples
///
/// ```
/// use cardano_crypto::dsign::ed25519::Ed25519VerificationKey;
///
/// // Parse from bytes
/// let bytes = [0u8; 32];
/// if let Some(vk) = Ed25519VerificationKey::from_bytes(&bytes) {
///     // Use verification key
///     let key_bytes = vk.as_bytes();
///     assert_eq!(key_bytes.len(), 32);
/// }
/// ```
///
/// # Security
///
/// - Cannot be used to forge signatures (one-way derivation from signing key)
/// - Safe to transmit over untrusted networks
/// - Should be validated before use to ensure it's a valid curve point
#[derive(Clone, PartialEq, Eq)]
pub struct Ed25519VerificationKey([u8; VERIFICATION_KEY_SIZE]);

impl core::fmt::Debug for Ed25519VerificationKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Ed25519VerificationKey(<{} bytes>)", self.0.len())
    }
}

impl Ed25519VerificationKey {
    /// Create a verification key from raw bytes with validation
    ///
    /// Validates that the provided bytes represent a valid Ed25519 public key
    /// (a valid point on the Edwards25519 curve). This is important for security
    /// as invalid keys could lead to verification failures or security issues.
    ///
    /// # Parameters
    ///
    /// * `bytes` - 32-byte slice containing the verification key
    ///
    /// # Returns
    ///
    /// * `Some(Ed25519VerificationKey)` if the bytes represent a valid key
    /// * `None` if the bytes are invalid (wrong length or not a valid curve point)
    ///
    /// # Examples
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [1u8; 32];
    /// let signing_key = Ed25519::gen_key(&seed);
    /// let verification_key = Ed25519::derive_verification_key(&signing_key);
    ///
    /// let bytes = verification_key.as_bytes();
    /// let recovered = cardano_crypto::dsign::ed25519::Ed25519VerificationKey::from_bytes(bytes);
    /// assert!(recovered.is_some());
    /// ```
    #[inline]
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != VERIFICATION_KEY_SIZE {
            return None;
        }
        let mut array = [0u8; VERIFICATION_KEY_SIZE];
        array.copy_from_slice(bytes);
        // Validate that this is a valid verification key
        DalekVerifyingKey::from_bytes(&array).ok()?;
        Some(Self(array))
    }

    /// Get the raw bytes of the verification key
    ///
    /// Returns a reference to the internal 32-byte representation of the public key.
    /// This is useful for serialization, transmission, or storage.
    ///
    /// # Returns
    ///
    /// Reference to the 32-byte verification key
    ///
    /// # Examples
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [2u8; 32];
    /// let signing_key = Ed25519::gen_key(&seed);
    /// let verification_key = Ed25519::derive_verification_key(&signing_key);
    ///
    /// let bytes = verification_key.as_bytes();
    /// assert_eq!(bytes.len(), 32);
    /// ```
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; VERIFICATION_KEY_SIZE] {
        &self.0
    }
}

/// Ed25519 signing (secret) key
///
/// A 64-byte compound key structure following the Cardano/libsodium convention.
/// Contains both the 32-byte seed and the derived 32-byte verification key.
///
/// # Format
///
/// ```text
/// [0..32]  - Seed (secret random bytes)
/// [32..64] - Verification key (derived public key)
/// ```
///
/// This format matches Cardano's key storage and allows efficient access to both
/// the secret material and the derived public key without recomputation.
///
/// # Security
///
/// ⚠️ **CRITICAL**: This key must be kept absolutely secret!
/// - Never transmit over untrusted networks
/// - Store encrypted at rest
/// - Zeroize from memory after use
/// - Anyone with this key can forge signatures
///
/// # Usage
///
/// - Generate from a high-entropy 32-byte seed
/// - Use for signing transactions and messages
/// - Derive the public verification key
/// - Store securely in wallets and key management systems
///
/// # Examples
///
/// ```
/// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
///
/// let seed = [42u8; 32];
/// let signing_key = Ed25519::gen_key(&seed);
///
/// // The key contains both seed and verification key
/// assert_eq!(signing_key.compound_bytes().len(), 64);
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Ed25519SigningKey([u8; SECRET_COMPOUND_SIZE]);

impl core::fmt::Debug for Ed25519SigningKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Ed25519SigningKey([REDACTED])")
    }
}

impl Ed25519SigningKey {
    /// Create a signing key from a 32-byte seed
    ///
    /// Generates the complete 64-byte signing key structure from a 32-byte seed.
    /// The verification key is automatically derived and stored in the second half.
    ///
    /// # Parameters
    ///
    /// * `seed` - 32-byte seed (must be from a cryptographically secure RNG)
    ///
    /// # Returns
    ///
    /// 64-byte compound signing key containing seed and derived verification key
    ///
    /// # Security
    ///
    /// The seed must come from a high-quality entropy source. Using predictable
    /// or low-entropy seeds compromises security completely.
    ///
    /// # Examples
    ///
    /// ```
    /// use cardano_crypto::dsign::ed25519::Ed25519SigningKey;
    ///
    /// let seed = [42u8; 32];
    /// let signing_key = Ed25519SigningKey::from_seed_bytes(&seed);
    /// ```
    #[inline]
    pub fn from_seed_bytes(seed: &[u8]) -> Self {
        let mut seed_array = [0u8; SEED_SIZE];
        seed_array.copy_from_slice(seed);

        let signing_key = DalekSigningKey::from_bytes(&seed_array);
        let verifying_key = signing_key.verifying_key();

        let mut compound = [0u8; SECRET_COMPOUND_SIZE];
        compound[..SEED_SIZE].copy_from_slice(&seed_array);
        compound[SEED_SIZE..].copy_from_slice(&verifying_key.to_bytes());

        Self(compound)
    }

    /// Get the seed bytes (first 32 bytes)
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::ed25519::Ed25519SigningKey;
    ///
    /// let seed = [99u8; 32];
    /// let sk = Ed25519SigningKey::from_seed_bytes(&seed);
    /// let extracted_seed = sk.seed_bytes();
    /// assert_eq!(seed, extracted_seed);
    /// ```
    #[inline]
    #[must_use]
    pub fn seed_bytes(&self) -> [u8; SEED_SIZE] {
        let mut seed = [0u8; SEED_SIZE];
        seed.copy_from_slice(&self.0[..SEED_SIZE]);
        seed
    }

    /// Get the verification key bytes (last 32 bytes)
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::ed25519::Ed25519SigningKey;
    ///
    /// let seed = [77u8; 32];
    /// let sk = Ed25519SigningKey::from_seed_bytes(&seed);
    /// let vk_bytes = sk.verifying_bytes();
    /// assert_eq!(vk_bytes.len(), 32);
    /// ```
    #[inline]
    #[must_use]
    pub fn verifying_bytes(&self) -> [u8; VERIFICATION_KEY_SIZE] {
        let mut vk = [0u8; VERIFICATION_KEY_SIZE];
        vk.copy_from_slice(&self.0[SEED_SIZE..]);
        vk
    }

    /// Get the dalek signing key for actual signing operations
    #[inline]
    fn signing_key(&self) -> DalekSigningKey {
        let seed = self.seed_bytes();
        DalekSigningKey::from_bytes(&seed)
    }

    /// Get the compound bytes (all 64 bytes)
    ///
    /// # Example
    ///
    /// ```rust
    /// use cardano_crypto::dsign::ed25519::Ed25519SigningKey;
    ///
    /// let seed = [42u8; 32];
    /// let sk = Ed25519SigningKey::from_seed_bytes(&seed);
    /// let compound = sk.compound_bytes();
    /// assert_eq!(compound.len(), 64);
    /// ```
    #[inline]
    #[must_use]
    pub fn compound_bytes(&self) -> &[u8; SECRET_COMPOUND_SIZE] {
        &self.0
    }
}

/// Ed25519 signature
///
/// A 64-byte digital signature produced by the Ed25519 algorithm.
/// Signatures are deterministic (same message + key always produces the same signature).
///
/// # Format
///
/// ```text
/// [0..32]  - R: Curve point (compressed)
/// [32..64] - S: Scalar value
/// ```
///
/// This follows the standard Ed25519 signature format as defined in RFC 8032.
///
/// # Properties
///
/// - **Deterministic**: No randomness needed; same inputs always produce same signature
/// - **Compact**: Only 64 bytes for quantum-resistant security level
/// - **Fast**: Efficient verification (important for blockchain validation)
/// - **Non-malleable**: Prevents signature modification attacks
///
/// # Usage
///
/// - Prove authenticity of transactions
/// - Verify message integrity
/// - Bind messages to specific keys
/// - Transmit proof of authorization
///
/// # Examples
///
/// ```
/// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
///
/// let seed = [1u8; 32];
/// let signing_key = Ed25519::gen_key(&seed);
/// let message = b"sign this message";
/// let signature = Ed25519::sign(&signing_key, message);
///
/// assert_eq!(signature.as_bytes().len(), 64);
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Ed25519Signature([u8; SIGNATURE_SIZE]);

impl core::fmt::Debug for Ed25519Signature {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Ed25519Signature(<{} bytes>)", self.0.len())
    }
}

impl Ed25519Signature {
    /// Create from raw bytes
    ///
    /// # Example
    ///
    /// ```rust
    /// use cardano_crypto::dsign::ed25519::Ed25519Signature;
    ///
    /// let bytes = [0u8; 64];
    /// let sig = Ed25519Signature::from_bytes(&bytes);
    /// assert!(sig.is_some());
    /// ```
    #[inline]
    #[must_use]
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != SIGNATURE_SIZE {
            return None;
        }
        let mut arr = [0u8; SIGNATURE_SIZE];
        arr.copy_from_slice(bytes);
        Some(Self(arr))
    }

    /// Create from dalek signature
    ///
    /// # Example
    ///
    /// ```rust
    /// use cardano_crypto::dsign::ed25519::Ed25519Signature;
    /// # use ed25519_dalek::Signature as DalekSignature;
    ///
    /// # let bytes = [0u8; 64];
    /// # let dalek_sig = DalekSignature::from_bytes(&bytes);
    /// // Convert from ed25519-dalek signature
    /// let sig = Ed25519Signature::from_dalek(&dalek_sig);
    /// assert_eq!(sig.as_bytes().len(), 64);
    /// ```
    #[inline]
    #[must_use]
    pub fn from_dalek(signature: &DalekSignature) -> Self {
        Self(signature.to_bytes())
    }

    /// Get the raw bytes
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [1u8; 32];
    /// let sk = Ed25519::gen_key(&seed);
    /// let message = b"test";
    /// let sig = Ed25519::sign(&sk, message);
    /// let bytes = sig.as_bytes();
    /// assert_eq!(bytes.len(), 64);
    /// ```
    #[inline]
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; SIGNATURE_SIZE] {
        &self.0
    }
}

/// Ed25519 digital signature algorithm
///
/// Standard Ed25519 as used in Cardano transactions and stake pool operations.
/// This implementation is byte-for-byte compatible with Cardano's Ed25519 usage.
#[derive(Clone, Debug)]
pub struct Ed25519;

impl super::DsignAlgorithm for Ed25519 {
    type SigningKey = Ed25519SigningKey;
    type VerificationKey = Ed25519VerificationKey;
    type Signature = Ed25519Signature;

    const ALGORITHM_NAME: &'static str = "Ed25519";
    const SIGNING_KEY_SIZE: usize = SECRET_COMPOUND_SIZE;
    const VERIFICATION_KEY_SIZE: usize = VERIFICATION_KEY_SIZE;
    const SIGNATURE_SIZE: usize = SIGNATURE_SIZE;

    /// Derive verification key from signing key
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [3u8; 32];
    /// let sk = Ed25519::gen_key(&seed);
    /// let vk = Ed25519::derive_verification_key(&sk);
    /// assert_eq!(vk.as_bytes().len(), 32);
    /// ```
    fn derive_verification_key(signing_key: &Self::SigningKey) -> Self::VerificationKey {
        let mut bytes = [0u8; VERIFICATION_KEY_SIZE];
        bytes.copy_from_slice(&signing_key.verifying_bytes());
        Ed25519VerificationKey(bytes)
    }

    /// Sign a message with the signing key
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [4u8; 32];
    /// let sk = Ed25519::gen_key(&seed);
    /// let message = b"important data";
    /// let sig = Ed25519::sign(&sk, message);
    /// assert_eq!(sig.as_bytes().len(), 64);
    /// ```
    fn sign(signing_key: &Self::SigningKey, message: &[u8]) -> Self::Signature {
        let signing_key = signing_key.signing_key();
        let signature = signing_key.sign(message);
        Ed25519Signature::from_dalek(&signature)
    }

    /// Verify a signature
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [5u8; 32];
    /// let sk = Ed25519::gen_key(&seed);
    /// let vk = Ed25519::derive_verification_key(&sk);
    /// let message = b"verify this";
    /// let sig = Ed25519::sign(&sk, message);
    /// assert!(Ed25519::verify(&vk, message, &sig).is_ok());
    /// ```
    fn verify(
        verification_key: &Self::VerificationKey,
        message: &[u8],
        signature: &Self::Signature,
    ) -> Result<()> {
        let verifying_key = DalekVerifyingKey::from_bytes(verification_key.as_bytes())
            .map_err(|_| CryptoError::InvalidPublicKey)?;

        let signature = DalekSignature::try_from(signature.as_bytes().as_ref())
            .map_err(|_| CryptoError::InvalidSignature)?;

        verifying_key
            .verify(message, &signature)
            .map_err(|_| CryptoError::VerificationFailed)
    }

    /// Generate signing key from seed
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::{Ed25519, DsignAlgorithm};
    ///
    /// let seed = [6u8; 32];
    /// let sk = Ed25519::gen_key(&seed);
    /// assert_eq!(sk.compound_bytes().len(), 64);
    /// ```
    fn gen_key(seed: &[u8]) -> Self::SigningKey {
        assert_eq!(
            seed.len(),
            SEED_SIZE,
            "Ed25519 seed must be exactly 32 bytes"
        );
        Ed25519SigningKey::from_seed_bytes(seed)
    }

    fn raw_serialize_verification_key(key: &Self::VerificationKey) -> &[u8] {
        key.as_bytes()
    }

    fn raw_deserialize_verification_key(bytes: &[u8]) -> Option<Self::VerificationKey> {
        Ed25519VerificationKey::from_bytes(bytes)
    }

    fn raw_serialize_signature(sig: &Self::Signature) -> &[u8] {
        sig.as_bytes()
    }

    fn raw_deserialize_signature(bytes: &[u8]) -> Option<Self::Signature> {
        if bytes.len() != SIGNATURE_SIZE {
            return None;
        }
        let mut array = [0u8; SIGNATURE_SIZE];
        array.copy_from_slice(bytes);
        Some(Ed25519Signature(array))
    }
}

// New trait implementation for compatibility with KES
use crate::common::error::{CryptoError as CommonCryptoError, Result};
use crate::common::traits::DsignAlgorithm as CommonDsignAlgorithm;

impl CommonDsignAlgorithm for Ed25519 {
    type SigningKey = Ed25519SigningKey;
    type VerificationKey = Ed25519VerificationKey;
    type Signature = Ed25519Signature;
    type Context = ();

    const ALGORITHM_NAME: &'static str = "Ed25519";
    const SEED_SIZE: usize = SEED_SIZE;
    const SIGNING_KEY_SIZE: usize = SECRET_COMPOUND_SIZE;
    const VERIFICATION_KEY_SIZE: usize = VERIFICATION_KEY_SIZE;
    const SIGNATURE_SIZE: usize = SIGNATURE_SIZE;

    /// Generate key from seed with error handling
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [7u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// ```
    fn gen_key_from_seed(seed: &[u8]) -> Result<Self::SigningKey> {
        if seed.len() != SEED_SIZE {
            return Err(CommonCryptoError::InvalidKeyLength);
        }
        Ok(Ed25519SigningKey::from_seed_bytes(seed))
    }

    /// Derive verification key with error handling
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [8u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let vk = Ed25519::derive_verification_key(&sk).unwrap();
    /// ```
    fn derive_verification_key(signing_key: &Self::SigningKey) -> Result<Self::VerificationKey> {
        let mut bytes = [0u8; VERIFICATION_KEY_SIZE];
        bytes.copy_from_slice(&signing_key.verifying_bytes());
        Ok(Ed25519VerificationKey(bytes))
    }

    /// Sign message (parameter order: message, key)
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [9u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let sig = Ed25519::sign(b"data", &sk).unwrap();
    /// ```
    fn sign(message: &[u8], signing_key: &Self::SigningKey) -> Result<Self::Signature> {
        let signing_key_dalek = signing_key.signing_key();
        let signature = signing_key_dalek.sign(message);
        Ok(Ed25519Signature::from_dalek(&signature))
    }

    /// Verify signature (parameter order: message, sig, key)
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [10u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let vk = Ed25519::derive_verification_key(&sk).unwrap();
    /// let sig = Ed25519::sign(b"msg", &sk).unwrap();
    /// Ed25519::verify(b"msg", &sig, &vk).unwrap();
    /// ```
    fn verify(
        message: &[u8],
        signature: &Self::Signature,
        verification_key: &Self::VerificationKey,
    ) -> Result<()> {
        let verifying_key = DalekVerifyingKey::from_bytes(verification_key.as_bytes())
            .map_err(|_| CommonCryptoError::InvalidPublicKey)?;

        let sig = DalekSignature::try_from(signature.as_bytes().as_ref())
            .map_err(|_| CommonCryptoError::InvalidSignature)?;

        verifying_key
            .verify(message, &sig)
            .map_err(|_| CommonCryptoError::VerificationFailed)
    }

    /// Serialize verification key to bytes
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [11u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let vk = Ed25519::derive_verification_key(&sk).unwrap();
    /// let bytes = Ed25519::serialize_verification_key(&vk);
    /// assert_eq!(bytes.len(), 32);
    /// ```
    #[cfg(feature = "alloc")]
    fn serialize_verification_key(key: &Self::VerificationKey) -> alloc::vec::Vec<u8> {
        key.as_bytes().to_vec()
    }

    /// Deserialize verification key from bytes
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [12u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let vk = Ed25519::derive_verification_key(&sk).unwrap();
    /// let bytes = Ed25519::serialize_verification_key(&vk);
    /// let recovered = Ed25519::deserialize_verification_key(&bytes).unwrap();
    /// assert_eq!(vk.as_bytes(), recovered.as_bytes());
    /// ```
    fn deserialize_verification_key(bytes: &[u8]) -> Result<Self::VerificationKey> {
        Ed25519VerificationKey::from_bytes(bytes).ok_or(CommonCryptoError::InvalidPublicKey)
    }

    /// Serialize signature to bytes
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [13u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let sig = Ed25519::sign(b"test", &sk).unwrap();
    /// let bytes = Ed25519::serialize_signature(&sig);
    /// assert_eq!(bytes.len(), 64);
    /// ```
    #[cfg(feature = "alloc")]
    fn serialize_signature(signature: &Self::Signature) -> alloc::vec::Vec<u8> {
        signature.as_bytes().to_vec()
    }

    /// Deserialize signature from bytes
    ///
    /// # Example
    ///
    /// ```
    /// use cardano_crypto::dsign::Ed25519;
    /// use cardano_crypto::common::traits::DsignAlgorithm;
    ///
    /// let seed = [14u8; 32];
    /// let sk = Ed25519::gen_key_from_seed(&seed).unwrap();
    /// let sig = Ed25519::sign(b"test", &sk).unwrap();
    /// let bytes = Ed25519::serialize_signature(&sig);
    /// let recovered = Ed25519::deserialize_signature(&bytes).unwrap();
    /// ```
    fn deserialize_signature(bytes: &[u8]) -> Result<Self::Signature> {
        if bytes.len() != SIGNATURE_SIZE {
            return Err(CommonCryptoError::InvalidSignature);
        }
        let mut array = [0u8; SIGNATURE_SIZE];
        array.copy_from_slice(bytes);
        Ok(Ed25519Signature(array))
    }

    fn forget_signing_key(mut signing_key: Self::SigningKey) {
        // Securely zeroize the signing key to prevent it from remaining in memory
        use zeroize::Zeroize;
        signing_key.0.zeroize();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dsign::DsignAlgorithm;

    #[test]
    fn test_key_generation_deterministic() {
        let seed = [7u8; 32];
        let signing1 = Ed25519::gen_key(&seed);
        let signing2 = Ed25519::gen_key(&seed);
        assert_eq!(signing1.compound_bytes(), signing2.compound_bytes());
    }

    #[test]
    fn test_sign_and_verify_roundtrip() {
        let seed = [42u8; 32];
        let signing_key = Ed25519::gen_key(&seed);
        let verification_key =
            <Ed25519 as crate::dsign::DsignAlgorithm>::derive_verification_key(&signing_key);

        let message = b"cardano";
        let signature = <Ed25519 as crate::dsign::DsignAlgorithm>::sign(&signing_key, message);

        let result = <Ed25519 as crate::dsign::DsignAlgorithm>::verify(
            &verification_key,
            message,
            &signature,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_verify_fails_wrong_message() {
        let seed = [9u8; 32];
        let signing_key = Ed25519::gen_key(&seed);
        let verification_key =
            <Ed25519 as crate::dsign::DsignAlgorithm>::derive_verification_key(&signing_key);

        let signature = <Ed25519 as crate::dsign::DsignAlgorithm>::sign(&signing_key, b"hello");
        let result = <Ed25519 as crate::dsign::DsignAlgorithm>::verify(
            &verification_key,
            b"world",
            &signature,
        );

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), CryptoError::VerificationFailed);
    }

    #[test]
    fn test_verify_fails_wrong_key() {
        let seed1 = [1u8; 32];
        let seed2 = [2u8; 32];

        let signing_key1 = Ed25519::gen_key(&seed1);
        let signing_key2 = Ed25519::gen_key(&seed2);
        let verification_key2 =
            <Ed25519 as crate::dsign::DsignAlgorithm>::derive_verification_key(&signing_key2);

        let message = b"test";
        let signature1 = <Ed25519 as crate::dsign::DsignAlgorithm>::sign(&signing_key1, message);

        let result = <Ed25519 as crate::dsign::DsignAlgorithm>::verify(
            &verification_key2,
            message,
            &signature1,
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_message() {
        let seed = [42u8; 32];
        let signing_key = Ed25519::gen_key(&seed);
        let verification_key =
            <Ed25519 as crate::dsign::DsignAlgorithm>::derive_verification_key(&signing_key);

        let signature = <Ed25519 as crate::dsign::DsignAlgorithm>::sign(&signing_key, b"");
        let result =
            <Ed25519 as crate::dsign::DsignAlgorithm>::verify(&verification_key, b"", &signature);
        assert!(result.is_ok());
    }

    #[test]
    fn test_large_message() {
        let seed = [99u8; 32];
        let signing_key = Ed25519::gen_key(&seed);
        let verification_key =
            <Ed25519 as crate::dsign::DsignAlgorithm>::derive_verification_key(&signing_key);

        let large_message = vec![0xAB; 10_000];
        let signature =
            <Ed25519 as crate::dsign::DsignAlgorithm>::sign(&signing_key, &large_message);
        let result = <Ed25519 as crate::dsign::DsignAlgorithm>::verify(
            &verification_key,
            &large_message,
            &signature,
        );
        assert!(result.is_ok());
    }

    #[test]
    fn test_hash_verification_key() {
        use crate::dsign::DsignAlgorithm;
        use crate::hash::{Blake2b224, Blake2b256};

        let seed = [42u8; 32];
        let signing_key = Ed25519::gen_key(&seed);
        let vk = <Ed25519 as DsignAlgorithm>::derive_verification_key(&signing_key);

        // Hash with Blake2b-256
        let hash_256 = Ed25519::hash_verification_key::<Blake2b256>(&vk);
        assert_eq!(hash_256.len(), 32);

        // Hash with Blake2b-224
        let hash_224 = Ed25519::hash_verification_key::<Blake2b224>(&vk);
        assert_eq!(hash_224.len(), 28);

        // Different keys should produce different hashes
        let seed2 = [43u8; 32];
        let signing_key2 = Ed25519::gen_key(&seed2);
        let vk2 = <Ed25519 as DsignAlgorithm>::derive_verification_key(&signing_key2);
        let hash2_256 = Ed25519::hash_verification_key::<Blake2b256>(&vk2);
        assert_ne!(hash_256, hash2_256);

        // Same key should produce same hash
        let hash_256_again = Ed25519::hash_verification_key::<Blake2b256>(&vk);
        assert_eq!(hash_256, hash_256_again);
    }
}

// Helper for hex encoding in tests
#[cfg(test)]
mod hex {
    #[allow(dead_code)]
    pub(crate) fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{:02x}", b)).collect()
    }
}