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
//! VRF implementation following IETF draft-03 specification
//!
//! Implements **ECVRF-ED25519-SHA512-Elligator2** as defined in
//! [draft-irtf-cfrg-vrf-03](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-vrf-03).
//! This variant produces 80-byte proofs and provides full byte-for-byte compatibility
//! with Cardano's libsodium VRF implementation.
//!
//! # Specification Details
//!
//! - **Suite**: ECVRF-ED25519-SHA512-Elligator2
//! - **Curve**: Edwards25519 (Ed25519)
//! - **Hash Function**: SHA-512
//! - **Hash-to-Curve**: Elligator2 (for non-uniform hash-to-curve)
//! - **Proof Size**: 80 bytes (Gamma point 32 bytes + challenge 16 bytes + response 32 bytes)
//! - **Public Key Size**: 32 bytes
//! - **Secret Key Size**: 64 bytes (32-byte seed || 32-byte public key, Ed25519 format)
//! - **Output Size**: 64 bytes (SHA-512 hash)
//!
//! # Cardano Compatibility
//!
//! This implementation is **100% compatible** with Cardano's VRF as used in:
//! - Block production (VRF-based leader selection)
//! - Epoch nonce generation
//! - Praos consensus protocol
//!
//! All proofs generated by this library can be verified by Cardano nodes and vice versa.
//!
//! # Security
//!
//! - Constant-time operations for secret key material
//! - Automatic memory zeroization for sensitive data
//! - No unsafe code
//! - Extensively tested against official test vectors
//!
//! # Examples
//!
//! ```rust,ignore
//! use cardano_crypto::vrf::VrfDraft03;
//!
//! // Generate keypair from seed
//! let seed = [42u8; 32];
//! let (secret_key, public_key) = VrfDraft03::keypair_from_seed(&seed);
//!
//! // Generate proof
//! let message = b"Cardano block production";
//! let proof = VrfDraft03::prove(&secret_key, message)?;
//!
//! // Verify proof and get VRF output
//! let output = VrfDraft03::verify(&public_key, &proof, message)?;
//!
//! // Convert proof directly to hash (without verification)
//! let hash = VrfDraft03::proof_to_hash(&proof)?;
//! assert_eq!(&output[..], &hash[..]);
//! ```
//!
//! # Performance
//!
//! Typical operation times on modern hardware:
//! - Keypair generation: ~20μs
//! - Proof generation: ~1.2ms
//! - Proof verification: ~800μs
//!
//! # When to Use
//!
//! Use this variant when:
//! - You need Cardano compatibility
//! - Proof size (80 bytes) is acceptable
//! - You're working with existing Cardano infrastructure

use curve25519_dalek::{constants::ED25519_BASEPOINT_POINT, scalar::Scalar};
use sha2::{Digest, Sha512};
use zeroize::Zeroizing;

use crate::common::{clamp_scalar, point_to_bytes, CryptoResult, SUITE_DRAFT03, THREE};
use crate::vrf::cardano_compat::{cardano_vrf_prove, cardano_vrf_verify};

/// VRF proof size for draft-03: 80 bytes
///
/// Structure: Gamma (32 bytes) || c (16 bytes) || s (32 bytes)
/// - Gamma: Hashed message point on Edwards curve
///
/// # Example
///
/// ```rust
/// use cardano_crypto::vrf::{VrfDraft03, draft03::PROOF_SIZE};
///
/// # fn main() -> cardano_crypto::common::Result<()> {
/// // Generate a keypair
/// let seed = [1u8; 32];
/// let (sk, pk) = VrfDraft03::keypair_from_seed(&seed);
///
/// // Create a proof
/// let message = b"test message";
/// let proof = VrfDraft03::prove(&sk, message)?;
///
/// // Verify the proof length
/// assert_eq!(proof.len(), PROOF_SIZE);
/// # Ok(())
/// # }
/// ```
/// - c: Challenge scalar (truncated to 16 bytes)
/// - s: Response scalar
pub const PROOF_SIZE: usize = 80;

/// Ed25519 public key size: 32 bytes
///
/// Compressed Edwards curve point in standard Ed25519 format.
///
/// # Example
///
/// ```
/// use cardano_crypto::vrf::draft03::PUBLIC_KEY_SIZE;
///
/// assert_eq!(PUBLIC_KEY_SIZE, 32);
/// ```
pub const PUBLIC_KEY_SIZE: usize = 32;

/// Ed25519 secret key size: 64 bytes
///
/// Format: seed (32 bytes) || public_key (32 bytes)
/// This follows the Ed25519 expanded secret key format used by Cardano.
///
/// # Example
///
/// ```
/// use cardano_crypto::vrf::draft03::SECRET_KEY_SIZE;
///
/// assert_eq!(SECRET_KEY_SIZE, 64);
/// ```
pub const SECRET_KEY_SIZE: usize = 64;

/// Random seed size for keypair generation: 32 bytes
///
/// High-quality randomness is critical for security. Use a
/// cryptographically secure random number generator.
///
/// # Example
///
/// ```
/// use cardano_crypto::vrf::draft03::SEED_SIZE;
///
/// assert_eq!(SEED_SIZE, 32);
/// ```
pub const SEED_SIZE: usize = 32;

/// VRF output hash size: 64 bytes
///
/// SHA-512 hash of the VRF proof's Gamma point.
///
/// # Example
///
/// ```
/// use cardano_crypto::vrf::draft03::OUTPUT_SIZE;
///
/// assert_eq!(OUTPUT_SIZE, 64);
/// ```
pub const OUTPUT_SIZE: usize = 64;

/// VRF Draft-03 implementation (ECVRF-ED25519-SHA512-Elligator2)
///
/// Zero-sized type providing static methods for VRF operations following
/// the draft-03 specification. All methods are stateless and thread-safe.
///
/// # Cloning
///
/// This type is `Clone` but contains no data - clones are identical.
///
/// # Examples
///
/// ```rust,ignore
/// use cardano_crypto::vrf::VrfDraft03;
///
/// // All operations are static - no instance needed
/// let seed = [0u8; 32];
/// let (sk, pk) = VrfDraft03::keypair_from_seed(&seed);
/// ```
#[derive(Clone, Debug)]
pub struct VrfDraft03;

impl VrfDraft03 {
    /// Generates a VRF proof for the given message using the secret key
    ///
    /// Produces an 80-byte proof that can be verified by anyone with the corresponding
    /// public key. The proof binds the message to the secret key while maintaining
    /// the randomness properties required for VRF applications.
    ///
    /// # Arguments
    ///
    /// * `secret_key` - 64-byte Ed25519 expanded secret key (seed || public_key)
    /// * `message` - Arbitrary-length message to prove (typically a blockchain slot ID or similar)
    ///
    /// # Returns
    ///
    /// 80-byte proof on success containing (Gamma || c || s)
    ///
    /// # Errors
    ///
    /// Returns [`crate::common::error::CryptoError`] if:
    /// - Secret key is malformed or invalid
    /// - Internal cryptographic operations fail (extremely rare)
    ///
    /// # Security
    ///
    /// - Uses constant-time operations for secret key handling
    /// - Automatically zeroizes sensitive intermediate values
    /// - Safe against timing attacks
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use cardano_crypto::vrf::VrfDraft03;
    ///
    /// let seed = [1u8; 32];
    /// let (secret_key, public_key) = VrfDraft03::keypair_from_seed(&seed);
    ///
    /// let message = b"slot_12345";
    /// let proof = VrfDraft03::prove(&secret_key, message)?;
    ///
    /// assert_eq!(proof.len(), 80);
    /// ```
    ///
    /// # Panics
    ///
    /// May panic if internal cryptographic operations encounter invalid state
    /// (extremely unlikely in correct usage).
    pub fn prove(
        secret_key: &[u8; SECRET_KEY_SIZE],
        message: &[u8],
    ) -> CryptoResult<[u8; PROOF_SIZE]> {
        cardano_vrf_prove(secret_key, message)
    }

    /// Verifies a VRF proof and returns the deterministic VRF output
    ///
    /// Checks that the proof is cryptographically valid for the given public key
    /// and message. If verification succeeds, returns the deterministic 64-byte
    /// VRF output - a deterministic 64-byte value derived from the proof.
    ///
    /// # Arguments
    ///
    /// * `public_key` - 32-byte Ed25519 public key
    /// * `proof` - 80-byte VRF proof to verify
    /// * `message` - Message that was allegedly proven
    ///
    /// # Returns
    ///
    /// 64-byte VRF output (SHA-512 hash) on successful verification
    ///
    /// # Errors
    ///
    /// Returns [`crate::common::error::CryptoError`] if:
    /// - `InvalidPublicKey`: Public key is malformed or not on the curve
    /// - `InvalidProof`: Proof is malformed, wrong length, or contains invalid data
    /// - `VerificationFailed`: Proof is well-formed but cryptographically invalid
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use cardano_crypto::vrf::VrfDraft03;
    ///
    /// let seed = [2u8; 32];
    /// let (secret_key, public_key) = VrfDraft03::keypair_from_seed(&seed);
    ///
    /// let message = b"verify_this_message";
    /// let proof = VrfDraft03::prove(&secret_key, message)?;
    ///
    /// // Verify proof and get VRF output
    /// let output = VrfDraft03::verify(&public_key, &proof, message)?;
    /// assert_eq!(output.len(), 64);
    ///
    /// // Wrong message should fail verification
    /// assert!(VrfDraft03::verify(&public_key, &proof, b"wrong").is_err());
    /// ```
    pub fn verify(
        public_key: &[u8; PUBLIC_KEY_SIZE],
        proof: &[u8; PROOF_SIZE],
        message: &[u8],
    ) -> CryptoResult<[u8; OUTPUT_SIZE]> {
        cardano_vrf_verify(public_key, proof, message)
    }

    /// Extracts the VRF output hash directly from a proof without verification
    ///
    /// Computes the VRF output (SHA-512 hash of the Gamma point) from a proof
    /// **without verifying** its validity. This is useful when the proof has
    /// already been verified or when you need to extract the hash for other purposes.
    ///
    /// ⚠️ **WARNING**: This function does NOT verify the proof's authenticity.
    /// Use [`verify`](Self::verify) if you need cryptographic assurance.
    ///
    /// # Arguments
    ///
    /// * `proof` - 80-byte VRF proof
    ///
    /// # Returns
    ///
    /// 64-byte VRF output hash (same as what `verify` would return)
    ///
    /// # Errors
    ///
    /// Returns [`crate::common::error::CryptoError::InvalidProof`] if the proof is malformed
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use cardano_crypto::vrf::VrfDraft03;
    ///
    /// let seed = [3u8; 32];
    /// let (secret_key, public_key) = VrfDraft03::keypair_from_seed(&seed);
    ///
    /// let message = b"extract_hash_example";
    /// let proof = VrfDraft03::prove(&secret_key, message)?;
    ///
    /// // Extract hash without verification (fast)
    /// let hash = VrfDraft03::proof_to_hash(&proof)?;
    ///
    /// // Verify that it matches the verified output
    /// let verified_output = VrfDraft03::verify(&public_key, &proof, message)?;
    /// assert_eq!(hash, verified_output);
    /// ```
    pub fn proof_to_hash(proof: &[u8; PROOF_SIZE]) -> CryptoResult<[u8; OUTPUT_SIZE]> {
        use crate::common::bytes_to_point;
        use crate::vrf::cardano_compat::cardano_clear_cofactor;

        let gamma_bytes: [u8; 32] = proof[0..32]
            .try_into()
            .expect("proof gamma segment must be 32 bytes");

        let gamma = bytes_to_point(&gamma_bytes)?;
        let gamma_cleared = cardano_clear_cofactor(&gamma);

        let mut hasher = Sha512::new();
        hasher.update([SUITE_DRAFT03]);
        hasher.update([THREE]);
        hasher.update(point_to_bytes(&gamma_cleared));
        let hash = hasher.finalize();

        let mut output = [0u8; OUTPUT_SIZE];
        output.copy_from_slice(&hash);
        Ok(output)
    }

    /// Generate keypair from seed
    ///
    /// Derives a deterministic Ed25519 keypair from a 32-byte seed using SHA-512
    /// and standard Ed25519 scalar clamping.
    ///
    /// # Arguments
    ///
    /// * `seed` - 32-byte random seed (must be cryptographically secure)
    ///
    /// # Returns
    ///
    /// Tuple of (secret_key, public_key):
    /// - `secret_key`: 64 bytes (seed || public_key)
    /// - `public_key`: 32 bytes (compressed Edwards point)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use cardano_crypto::vrf::VrfDraft03;
    ///
    /// let seed = [42u8; 32];
    /// let (secret_key, public_key) = VrfDraft03::keypair_from_seed(&seed);
    ///
    /// assert_eq!(secret_key.len(), 64);
    /// assert_eq!(public_key.len(), 32);
    /// ```
    #[must_use]
    pub fn keypair_from_seed(
        seed: &[u8; SEED_SIZE],
    ) -> ([u8; SECRET_KEY_SIZE], [u8; PUBLIC_KEY_SIZE]) {
        let mut hasher = Sha512::new();
        hasher.update(seed);
        let hash = hasher.finalize();

        let mut secret_scalar = Zeroizing::new([0u8; 32]);
        secret_scalar.copy_from_slice(&hash[0..32]);
        *secret_scalar = clamp_scalar(*secret_scalar);

        let scalar = Scalar::from_bytes_mod_order(*secret_scalar);
        let public_point = ED25519_BASEPOINT_POINT * scalar;
        let public_key = point_to_bytes(&public_point);

        let mut secret_key = [0u8; SECRET_KEY_SIZE];
        secret_key[0..32].copy_from_slice(seed);
        secret_key[32..64].copy_from_slice(&public_key);

        (secret_key, public_key)
    }
}

// ============================================================================
// VrfAlgorithm trait implementation
// ============================================================================

impl crate::vrf::VrfAlgorithm for VrfDraft03 {
    type SecretKey = [u8; SECRET_KEY_SIZE];
    type VerificationKey = [u8; PUBLIC_KEY_SIZE];
    type Proof = [u8; PROOF_SIZE];
    type Output = [u8; OUTPUT_SIZE];

    const ALGORITHM_NAME: &'static str = "ECVRF-ED25519-SHA512-Elligator2-Draft03";
    const SEED_SIZE: usize = SEED_SIZE;
    const SECRET_KEY_SIZE: usize = SECRET_KEY_SIZE;
    const VERIFICATION_KEY_SIZE: usize = PUBLIC_KEY_SIZE;
    const PROOF_SIZE: usize = PROOF_SIZE;
    const OUTPUT_SIZE: usize = OUTPUT_SIZE;

    fn keypair_from_seed(seed: &[u8; 32]) -> (Self::SecretKey, Self::VerificationKey) {
        VrfDraft03::keypair_from_seed(seed)
    }

    fn derive_verification_key(sk: &Self::SecretKey) -> Self::VerificationKey {
        let mut pk = [0u8; PUBLIC_KEY_SIZE];
        pk.copy_from_slice(&sk[32..64]);
        pk
    }

    fn prove(sk: &Self::SecretKey, message: &[u8]) -> CryptoResult<Self::Proof> {
        VrfDraft03::prove(sk, message)
    }

    fn verify(
        vk: &Self::VerificationKey,
        proof: &Self::Proof,
        message: &[u8],
    ) -> CryptoResult<Self::Output> {
        VrfDraft03::verify(vk, proof, message)
    }

    fn proof_to_hash(proof: &Self::Proof) -> CryptoResult<Self::Output> {
        VrfDraft03::proof_to_hash(proof)
    }

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

    fn raw_deserialize_verification_key(bytes: &[u8]) -> Option<Self::VerificationKey> {
        if bytes.len() != PUBLIC_KEY_SIZE {
            return None;
        }
        let mut vk = [0u8; PUBLIC_KEY_SIZE];
        vk.copy_from_slice(bytes);
        Some(vk)
    }

    fn raw_serialize_proof(proof: &Self::Proof) -> &[u8] {
        proof.as_slice()
    }

    fn raw_deserialize_proof(bytes: &[u8]) -> Option<Self::Proof> {
        if bytes.len() != PROOF_SIZE {
            return None;
        }
        let mut proof = [0u8; PROOF_SIZE];
        proof.copy_from_slice(bytes);
        Some(proof)
    }
}

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

    #[test]
    fn test_prove_verify_roundtrip() {
        let seed = [42u8; SEED_SIZE];
        let (sk, pk) = VrfDraft03::keypair_from_seed(&seed);
        let message = b"test message";

        let proof = VrfDraft03::prove(&sk, message).expect("prove failed");
        let output = VrfDraft03::verify(&pk, &proof, message).expect("verify failed");

        assert_eq!(output.len(), OUTPUT_SIZE);
    }

    #[test]
    fn test_verify_rejects_invalid_proof() {
        let seed = [42u8; SEED_SIZE];
        let (_sk, pk) = VrfDraft03::keypair_from_seed(&seed);
        let message = b"test message";

        let invalid_proof = [0u8; PROOF_SIZE];
        let result = VrfDraft03::verify(&pk, &invalid_proof, message);

        assert!(result.is_err());
    }

    #[test]
    fn test_proof_to_hash_deterministic() {
        let seed = [42u8; SEED_SIZE];
        let (sk, _pk) = VrfDraft03::keypair_from_seed(&seed);
        let message = b"test message";

        let proof = VrfDraft03::prove(&sk, message).expect("prove failed");
        let hash1 = VrfDraft03::proof_to_hash(&proof).expect("hash failed");
        let hash2 = VrfDraft03::proof_to_hash(&proof).expect("hash failed");

        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_keypair_generation() {
        let seed = [1u8; 32];
        let (sk, pk) = VrfDraft03::keypair_from_seed(&seed);

        // Check sizes
        assert_eq!(sk.len(), 64);
        assert_eq!(pk.len(), 32);

        // Check that secret key contains seed and public key
        assert_eq!(&sk[0..32], &seed);
        assert_eq!(&sk[32..64], &pk);
    }

    #[test]
    fn test_proof_sizes() {
        assert_eq!(PROOF_SIZE, 80);
        assert_eq!(SECRET_KEY_SIZE, 64);
        assert_eq!(PUBLIC_KEY_SIZE, 32);
        assert_eq!(OUTPUT_SIZE, 64);
        assert_eq!(SEED_SIZE, 32);
    }

    #[test]
    fn test_vrf_algorithm_trait() {
        use crate::hash::Blake2b256;
        use crate::vrf::VrfAlgorithm;

        let seed = [42u8; 32];
        let (sk, vk) = <VrfDraft03 as VrfAlgorithm>::keypair_from_seed(&seed);

        // Test trait constants
        assert_eq!(<VrfDraft03 as VrfAlgorithm>::SEED_SIZE, 32);
        assert_eq!(<VrfDraft03 as VrfAlgorithm>::SECRET_KEY_SIZE, 64);
        assert_eq!(<VrfDraft03 as VrfAlgorithm>::VERIFICATION_KEY_SIZE, 32);
        assert_eq!(<VrfDraft03 as VrfAlgorithm>::PROOF_SIZE, 80);
        assert_eq!(<VrfDraft03 as VrfAlgorithm>::OUTPUT_SIZE, 64);

        // Test prove/verify through trait
        let message = b"test message";
        let proof = <VrfDraft03 as VrfAlgorithm>::prove(&sk, message).unwrap();
        let output = <VrfDraft03 as VrfAlgorithm>::verify(&vk, &proof, message).unwrap();
        assert_eq!(output.len(), 64);

        // Test hash_verification_key
        let hash = <VrfDraft03 as VrfAlgorithm>::hash_verification_key::<Blake2b256>(&vk);
        assert_eq!(hash.len(), 32);

        // Different keys should have different hashes
        let seed2 = [43u8; 32];
        let (_, vk2) = <VrfDraft03 as VrfAlgorithm>::keypair_from_seed(&seed2);
        let hash2 = <VrfDraft03 as VrfAlgorithm>::hash_verification_key::<Blake2b256>(&vk2);
        assert_ne!(hash, hash2);
    }

    #[test]
    fn test_serialization_roundtrip() {
        use crate::vrf::VrfAlgorithm;

        let seed = [99u8; 32];
        let (sk, vk) = VrfDraft03::keypair_from_seed(&seed);
        let message = b"test";
        let proof = VrfDraft03::prove(&sk, message).unwrap();

        // Test verification key roundtrip
        let vk_bytes = <VrfDraft03 as VrfAlgorithm>::raw_serialize_verification_key(&vk);
        let vk_restored =
            <VrfDraft03 as VrfAlgorithm>::raw_deserialize_verification_key(vk_bytes).unwrap();
        assert_eq!(vk, vk_restored);

        // Test proof roundtrip
        let proof_bytes = <VrfDraft03 as VrfAlgorithm>::raw_serialize_proof(&proof);
        let proof_restored =
            <VrfDraft03 as VrfAlgorithm>::raw_deserialize_proof(proof_bytes).unwrap();
        assert_eq!(proof, proof_restored);
    }
}