latticearc 0.9.0

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), and FIPS 140-3 backend — one crate, zero unsafe.
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
//! Ed25519 signature operations
//!
//! This module provides Ed25519 digital signature operations.
//!
//! ## Unified API with SecurityMode
//!
//! All cryptographic operations use `SecurityMode` to specify verification behavior:
//!
//! ```no_run
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! use latticearc::unified_api::{sign_ed25519, verify_ed25519, SecurityMode, VerifiedSession};
//! # let data = b"example data";
//! # let private_key = [0u8; 32];
//! # let pk = [0u8; 32];
//! # let sk = [0u8; 32];
//! # let session = VerifiedSession::establish(&pk, &sk)?;
//!
//! // With Zero Trust verification (recommended)
//! let signature = sign_ed25519(data, &private_key, SecurityMode::Verified(&session))?;
//!
//! // Without verification (opt-out)
//! let signature = sign_ed25519(data, &private_key, SecurityMode::Unverified)?;
//! # Ok(())
//! # }
//! ```

use crate::{
    log_crypto_operation_complete, log_crypto_operation_error, log_crypto_operation_start,
};
use tracing::debug;

use crate::primitives::ec::ed25519::{
    ED25519_PUBLIC_KEY_LEN, ED25519_SECRET_KEY_LEN, ED25519_SIGNATURE_LEN, Ed25519KeyPair,
    Ed25519Signature as Ed25519SignatureOps,
};
use crate::primitives::ec::traits::{EcKeyPair, EcSignature};
use crate::primitives::resource_limits::validate_signature_size;

use crate::unified_api::CoreConfig;
use crate::unified_api::error::{CoreError, Result};
use crate::unified_api::logging::op;
use crate::unified_api::zero_trust::SecurityMode;

// ============================================================================
// Internal Implementation
// ============================================================================

/// Internal implementation of Ed25519 signing.
pub(crate) fn sign_ed25519_internal(data: &[u8], ed25519_sk: &[u8]) -> Result<Vec<u8>> {
    log_crypto_operation_start!(op::ED25519_SIGN, algorithm = "Ed25519", data_len = data.len());

    // bound message length before
    // SHA-512 hashes the entire payload, opaquely.
    if let Err(e) = validate_signature_size(data.len()) {
        log_crypto_operation_error!(op::ED25519_SIGN, e);
        return Err(CoreError::ResourceExceeded("message exceeds resource limit".to_string()));
    }

    // reject non-canonical SK lengths at the
    // boundary. Previously we accepted any `len >= 32` and silently
    // truncated to the leading 32 bytes via `sk.get(..32)`. libsodium-
    // style 64-byte expanded SKs (seed || derived PK) were misinterpreted
    // — the trailing 32 bytes were silently discarded. The correct
    // contract is "Ed25519 SK is exactly 32 bytes (the RFC 8032 seed)".
    if ed25519_sk.len() != ED25519_SECRET_KEY_LEN {
        let err = CoreError::InvalidKeyLength {
            expected: ED25519_SECRET_KEY_LEN,
            actual: ed25519_sk.len(),
        };
        log_crypto_operation_error!(op::ED25519_SIGN, err);
        return Err(err);
    }

    // opaque error mapping — upstream parse
    // wording is version-volatile and would leak which exact validity
    // check failed.
    let keypair = Ed25519KeyPair::from_secret_key(ed25519_sk).map_err(|e| {
        log_crypto_operation_error!(op::ED25519_SIGN, e);
        CoreError::InvalidKey("invalid Ed25519 secret key".to_string())
    })?;

    let signature = keypair.sign(data).map_err(|e| {
        log_crypto_operation_error!(op::ED25519_SIGN, e);
        CoreError::ResourceExceeded("message exceeds resource limit".to_string())
    })?;
    let sig_bytes = Ed25519SignatureOps::signature_bytes(&signature);

    log_crypto_operation_complete!(
        "ed25519_sign",
        algorithm = "Ed25519",
        signature_len = sig_bytes.len()
    );
    debug!(algorithm = "Ed25519", "Created Ed25519 signature");

    Ok(sig_bytes)
}

/// Internal implementation of Ed25519 verification.
pub(crate) fn verify_ed25519_internal(
    data: &[u8],
    signature_bytes: &[u8],
    ed25519_pk: &[u8],
) -> Result<bool> {
    log_crypto_operation_start!(op::ED25519_VERIFY, algorithm = "Ed25519", data_len = data.len());

    // bound message length before SHA-512
    // hashes the payload (RFC 8032 §5.1.7).
    if let Err(e) = validate_signature_size(data.len()) {
        log_crypto_operation_error!(op::ED25519_VERIFY, e);
        return Err(CoreError::ResourceExceeded("message exceeds resource limit".to_string()));
    }

    // reject non-canonical signature/PK
    // lengths at the boundary. Previously we accepted any `len >=
    // expected` and silently truncated to the leading prefix, which let
    // relays append junk and still verify the signature — a
    // wire-format-canonicalization break. Sig length must be exactly 64
    // and PK length must be exactly 32 per RFC 8032.
    if signature_bytes.len() != ED25519_SIGNATURE_LEN {
        let err = CoreError::InvalidInput("invalid Ed25519 signature length".to_string());
        log_crypto_operation_error!(op::ED25519_VERIFY, err);
        return Err(err);
    }
    if ed25519_pk.len() != ED25519_PUBLIC_KEY_LEN {
        let err = CoreError::InvalidKeyLength {
            expected: ED25519_PUBLIC_KEY_LEN,
            actual: ed25519_pk.len(),
        };
        log_crypto_operation_error!(op::ED25519_VERIFY, err);
        return Err(err);
    }

    // Parse the signature via the primitives layer.
    let signature = Ed25519SignatureOps::signature_from_bytes(signature_bytes).map_err(|e| {
        log_crypto_operation_error!(op::ED25519_VERIFY, e);
        // opaque parse-failure mapping —
        // never relay upstream variant wording.
        CoreError::InvalidInput("invalid Ed25519 signature".to_string())
    })?;

    // collapse all adversary-reachable verify
    // errors (off-curve PK, tampered signature, MAC mismatch) to
    // `Ok(false)` so a probing attacker cannot distinguish reject
    // reasons from the Result shape. The underlying cause is logged
    // via tracing::debug for operators.
    let result = match Ed25519SignatureOps::verify(ed25519_pk, data, &signature) {
        Ok(()) => Ok(true),
        Err(e) => {
            tracing::debug!(error = %e, "Ed25519 verification rejected");
            Ok(false)
        }
    };

    match &result {
        Ok(valid) => {
            log_crypto_operation_complete!(
                op::ED25519_VERIFY,
                algorithm = "Ed25519",
                valid = valid
            );
            debug!(algorithm = "Ed25519", valid = valid, "Ed25519 verification completed");
        }
        Err(e) => {
            log_crypto_operation_error!(op::ED25519_VERIFY, e);
        }
    }

    result
}

// ============================================================================
// Unified API with SecurityMode
// ============================================================================

/// Sign data using Ed25519.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before signing
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Example
///
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::unified_api::{sign_ed25519, SecurityMode, VerifiedSession, generate_keypair};
/// # let private_key = [0u8; 32];
///
/// let (pk, sk) = generate_keypair()?;
/// let session = VerifiedSession::establish(pk.as_slice(), sk.expose_secret())?;
///
/// // With Zero Trust verification (recommended)
/// let signature = sign_ed25519(b"message", &private_key, SecurityMode::Verified(&session))?;
///
/// // Without verification (opt-out)
/// let signature = sign_ed25519(b"message", &private_key, SecurityMode::Unverified)?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired (`CoreError::SessionExpired`) when using `SecurityMode::Verified`
/// - The private key is less than 32 bytes
#[inline]
pub fn sign_ed25519(data: &[u8], ed25519_sk: &[u8], mode: SecurityMode) -> Result<Vec<u8>> {
    mode.validate()?;
    sign_ed25519_internal(data, ed25519_sk)
}

/// Verify an Ed25519 signature.
///
/// Uses `SecurityMode` to specify verification behavior:
/// - `SecurityMode::Verified(&session)`: Validates session before verification
/// - `SecurityMode::Unverified`: Skips session validation
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired (`CoreError::SessionExpired`) when using `SecurityMode::Verified`
/// - The signature is less than 64 bytes
/// - The public key is less than 32 bytes
/// - The public key is invalid (not a valid curve point)
#[inline]
pub fn verify_ed25519(
    data: &[u8],
    signature_bytes: &[u8],
    ed25519_pk: &[u8],
    mode: SecurityMode,
) -> Result<bool> {
    mode.validate()?;
    verify_ed25519_internal(data, signature_bytes, ed25519_pk)
}

/// Sign data using Ed25519 with configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `SecurityMode::Verified`
/// - The configuration validation fails
/// - The private key is less than 32 bytes
#[inline]
pub fn sign_ed25519_with_config(
    data: &[u8],
    ed25519_sk: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<Vec<u8>> {
    mode.validate()?;
    config.validate()?;
    sign_ed25519_internal(data, ed25519_sk)
}

/// Verify an Ed25519 signature with configuration.
///
/// # Errors
///
/// Returns an error if:
/// - The session has expired when using `SecurityMode::Verified`
/// - The configuration validation fails
/// - The signature or public key is invalid
#[inline]
pub fn verify_ed25519_with_config(
    data: &[u8],
    signature_bytes: &[u8],
    ed25519_pk: &[u8],
    config: &CoreConfig,
    mode: SecurityMode,
) -> Result<bool> {
    mode.validate()?;
    config.validate()?;
    verify_ed25519_internal(data, signature_bytes, ed25519_pk)
}

// ============================================================================
// Unverified API (Opt-Out) — see `convenience::mod` docs for the shared
// security guidance on when to use `_unverified` variants.
// ============================================================================

/// Sign data using Ed25519 without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The private key is less than 32 bytes
#[inline]
pub fn sign_ed25519_unverified(data: &[u8], ed25519_sk: &[u8]) -> Result<Vec<u8>> {
    sign_ed25519(data, ed25519_sk, SecurityMode::Unverified)
}

/// Verify an Ed25519 signature without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The signature is less than 64 bytes
/// - The public key is less than 32 bytes
/// - The public key is invalid (not a valid curve point)
#[inline]
pub fn verify_ed25519_unverified(
    data: &[u8],
    signature_bytes: &[u8],
    ed25519_pk: &[u8],
) -> Result<bool> {
    verify_ed25519(data, signature_bytes, ed25519_pk, SecurityMode::Unverified)
}

/// Sign data using Ed25519 with configuration without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The configuration validation fails
/// - The private key is less than 32 bytes
#[inline]
pub fn sign_ed25519_with_config_unverified(
    data: &[u8],
    ed25519_sk: &[u8],
    config: &CoreConfig,
) -> Result<Vec<u8>> {
    sign_ed25519_with_config(data, ed25519_sk, config, SecurityMode::Unverified)
}

/// Verify an Ed25519 signature with configuration without Zero Trust verification.
///
/// This is an opt-out function for scenarios where Zero Trust verification
/// is not required or not possible.
///
/// # Errors
///
/// Returns an error if:
/// - The configuration validation fails
/// - The signature is less than 64 bytes
/// - The public key is less than 32 bytes
/// - The public key is invalid (not a valid curve point)
#[inline]
pub fn verify_ed25519_with_config_unverified(
    data: &[u8],
    signature_bytes: &[u8],
    ed25519_pk: &[u8],
    config: &CoreConfig,
) -> Result<bool> {
    verify_ed25519_with_config(data, signature_bytes, ed25519_pk, config, SecurityMode::Unverified)
}

#[cfg(test)]
#[expect(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic_in_result_fn,
    reason = "test/bench scaffolding: lints suppressed for this module"
)]
mod tests {
    use super::*;
    use crate::{SecurityMode, VerifiedSession, generate_keypair};

    // Basic sign/verify tests (unverified API)
    #[test]
    fn test_sign_verify_ed25519_unverified_roundtrip_succeeds() -> Result<()> {
        let message = b"Test message for Ed25519";
        let (pk, sk) = generate_keypair()?;

        let signature = sign_ed25519_unverified(message, sk.expose_secret())?;
        assert!(!signature.is_empty());
        assert_eq!(signature.len(), 64, "Ed25519 signature should be 64 bytes");

        let is_valid = verify_ed25519_unverified(message, &signature, pk.as_slice())?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_sign_ed25519_deterministic_produces_same_signature_is_deterministic() -> Result<()> {
        let message = b"Same message";
        let (_, sk) = generate_keypair()?;

        let sig1 = sign_ed25519_unverified(message, sk.expose_secret())?;
        let sig2 = sign_ed25519_unverified(message, sk.expose_secret())?;

        assert_eq!(sig1, sig2, "Ed25519 signatures should be deterministic");
        Ok(())
    }

    #[test]
    fn test_verify_ed25519_wrong_message_returns_false() {
        // adversary-reachable verify failures
        // now collapse to `Ok(false)` instead of `Err(VerificationFailed)`
        // so a probing attacker cannot distinguish reject reasons from
        // the Result shape. Test renamed to reflect the new contract.
        let message = b"Original message";
        let wrong_message = b"Wrong message";
        let (pk, sk) = generate_keypair().expect("keygen should succeed");

        let signature =
            sign_ed25519_unverified(message, sk.expose_secret()).expect("signing should succeed");
        let result = verify_ed25519_unverified(wrong_message, &signature, pk.as_slice());
        assert_eq!(result.ok(), Some(false), "Wrong message should yield Ok(false)");
    }

    #[test]
    fn test_verify_ed25519_invalid_signature_returns_false() {
        // an all-zero 64-byte buffer is a
        // valid Ed25519 signature *encoding* (no parse-time validity
        // check exists in RFC 8032), so it goes through the verify path
        // and is rejected with `Ok(false)`, not `Err`.
        let message = b"Test message";
        let (pk, _sk) = generate_keypair().expect("keygen should succeed");
        let invalid_signature = vec![0u8; 64];

        let result = verify_ed25519_unverified(message, &invalid_signature, pk.as_slice());
        assert_eq!(result.ok(), Some(false), "Invalid signature should yield Ok(false)");
    }

    #[test]
    fn test_verify_ed25519_wrong_public_key_returns_false() {
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let (wrong_pk, _) = generate_keypair().expect("keygen should succeed");

        let signature =
            sign_ed25519_unverified(message, sk.expose_secret()).expect("signing should succeed");
        let result = verify_ed25519_unverified(message, &signature, wrong_pk.as_slice());
        // wrong PK is adversary-reachable, so
        // it collapses to Ok(false).
        assert_eq!(result.ok(), Some(false), "Wrong public key should yield Ok(false)");
    }

    // With config tests
    #[test]
    fn test_sign_verify_ed25519_with_config_unverified_roundtrip() -> Result<()> {
        let message = b"Test with config";
        let (pk, sk) = generate_keypair()?;
        let config = CoreConfig::default();

        let signature = sign_ed25519_with_config_unverified(message, sk.expose_secret(), &config)?;
        let is_valid =
            verify_ed25519_with_config_unverified(message, &signature, pk.as_slice(), &config)?;
        assert!(is_valid);
        Ok(())
    }

    // Verified API tests (with SecurityMode)
    #[test]
    fn test_sign_verify_ed25519_verified_roundtrip_succeeds() -> Result<()> {
        let message = b"Test with verified session";
        let (pk, sk) = generate_keypair()?;

        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.expose_secret())?;

        let signature =
            sign_ed25519(message, sk.expose_secret(), SecurityMode::Verified(&session))?;
        let is_valid =
            verify_ed25519(message, &signature, pk.as_slice(), SecurityMode::Verified(&session))?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_sign_verify_ed25519_unverified_mode_roundtrip_succeeds() -> Result<()> {
        let message = b"Test unverified mode";
        let (pk, sk) = generate_keypair()?;

        let signature = sign_ed25519(message, sk.expose_secret(), SecurityMode::Unverified)?;
        let is_valid =
            verify_ed25519(message, &signature, pk.as_slice(), SecurityMode::Unverified)?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_sign_verify_ed25519_with_config_verified_roundtrip() -> Result<()> {
        let message = b"Test with config and session";
        let (pk, sk) = generate_keypair()?;
        let config = CoreConfig::default();

        let (auth_pk, auth_sk) = generate_keypair()?;
        let session = VerifiedSession::establish(auth_pk.as_slice(), auth_sk.expose_secret())?;

        let signature = sign_ed25519_with_config(
            message,
            sk.expose_secret(),
            &config,
            SecurityMode::Verified(&session),
        )?;
        let is_valid = verify_ed25519_with_config(
            message,
            &signature,
            pk.as_slice(),
            &config,
            SecurityMode::Verified(&session),
        )?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_sign_verify_ed25519_with_config_unverified_mode_roundtrip() -> Result<()> {
        let message = b"Test with config unverified mode";
        let (pk, sk) = generate_keypair()?;
        let config = CoreConfig::default();

        let signature = sign_ed25519_with_config(
            message,
            sk.expose_secret(),
            &config,
            SecurityMode::Unverified,
        )?;
        let is_valid = verify_ed25519_with_config(
            message,
            &signature,
            pk.as_slice(),
            &config,
            SecurityMode::Unverified,
        )?;
        assert!(is_valid);
        Ok(())
    }

    // Edge cases
    #[test]
    fn test_ed25519_empty_message_signs_and_verifies_succeeds() -> Result<()> {
        let message = b"";
        let (pk, sk) = generate_keypair()?;

        let signature = sign_ed25519_unverified(message, sk.expose_secret())?;
        let is_valid = verify_ed25519_unverified(message, &signature, pk.as_slice())?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_ed25519_large_message_signs_and_verifies_succeeds() -> Result<()> {
        // Ed25519 sign/verify now bound message
        // length via `validate_signature_size` (default 64 KiB). The
        // previous 100,000-byte fixture exceeded the cap; use 50 KiB so
        // the test still exercises a "large" message under the new
        // contract.
        let message = vec![0xAB; 50 * 1024];
        let (pk, sk) = generate_keypair()?;

        let signature = sign_ed25519_unverified(&message, sk.expose_secret())?;
        let is_valid = verify_ed25519_unverified(&message, &signature, pk.as_slice())?;
        assert!(is_valid);
        Ok(())
    }

    #[test]
    fn test_ed25519_signature_length_is_constant_64_bytes_has_correct_size() -> Result<()> {
        let (_, sk) = generate_keypair()?;
        let short_msg = b"short";
        let long_msg = vec![0xFF; 10000];

        let sig1 = sign_ed25519_unverified(short_msg, sk.expose_secret())?;
        let sig2 = sign_ed25519_unverified(&long_msg, sk.expose_secret())?;

        assert_eq!(sig1.len(), 64, "Signature length should be constant");
        assert_eq!(sig2.len(), 64, "Signature length should be constant");
        Ok(())
    }

    #[test]
    fn test_ed25519_different_messages_produce_different_signatures_succeeds() -> Result<()> {
        let (_, sk) = generate_keypair()?;
        let msg1 = b"First message";
        let msg2 = b"Second message";

        let sig1 = sign_ed25519_unverified(msg1, sk.expose_secret())?;
        let sig2 = sign_ed25519_unverified(msg2, sk.expose_secret())?;

        assert_ne!(sig1, sig2, "Different messages should produce different signatures");
        Ok(())
    }

    #[test]
    fn test_ed25519_different_keys_produce_different_signatures_succeeds() -> Result<()> {
        let message = b"Same message";
        let (_, sk1) = generate_keypair()?;
        let (_, sk2) = generate_keypair()?;

        let sig1 = sign_ed25519_unverified(message, sk1.expose_secret())?;
        let sig2 = sign_ed25519_unverified(message, sk2.expose_secret())?;

        assert_ne!(sig1, sig2, "Different keys should produce different signatures");
        Ok(())
    }

    // Invalid input tests
    #[test]
    fn test_ed25519_invalid_signature_length_returns_error() {
        let message = b"Test message";
        let (pk, _sk) = generate_keypair().expect("keygen should succeed");
        let invalid_sig = vec![0u8; 32]; // Wrong length

        let result = verify_ed25519_unverified(message, &invalid_sig, pk.as_slice());
        assert!(result.is_err(), "Should reject signature with wrong length");
    }

    #[test]
    fn test_ed25519_invalid_public_key_length_returns_error() {
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let invalid_pk = vec![0u8; 16]; // Wrong length

        let signature =
            sign_ed25519_unverified(message, sk.expose_secret()).expect("signing should succeed");
        let result = verify_ed25519_unverified(message, &signature, &invalid_pk);
        assert!(result.is_err(), "Should reject public key with wrong length");
    }

    #[test]
    fn test_ed25519_invalid_secret_key_length_returns_error() {
        let message = b"Test message";
        let invalid_sk = vec![0u8; 16]; // Wrong length

        let result = sign_ed25519_unverified(message, &invalid_sk);
        assert!(result.is_err(), "Should reject secret key with wrong length");
    }

    // === Additional error branch tests ===

    #[test]
    fn test_ed25519_empty_key_returns_error() {
        let message = b"Test message";
        let result = sign_ed25519_unverified(message, &[]);
        assert!(result.is_err(), "Empty secret key should fail");
    }

    #[test]
    fn test_ed25519_verify_empty_signature_returns_error() {
        let message = b"Test message";
        let (pk, _sk) = generate_keypair().expect("keygen should succeed");

        let result = verify_ed25519_unverified(message, &[], pk.as_slice());
        assert!(result.is_err(), "Empty signature should fail verification");
    }

    #[test]
    fn test_ed25519_verify_empty_public_key_returns_error() {
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let signature = sign_ed25519_unverified(message, sk.expose_secret()).unwrap();

        let result = verify_ed25519_unverified(message, &signature, &[]);
        assert!(result.is_err(), "Empty public key should fail");
    }

    #[test]
    fn test_ed25519_verify_invalid_public_key_format_returns_false() {
        // an off-curve PK (correct length, but
        // not a valid Ed25519 point) is adversary-reachable, so verify
        // collapses it to `Ok(false)` rather than `Err(InvalidKey)` —
        // otherwise the variant shape is itself a side-channel into
        // which check failed (off-curve vs malformed encoding vs MAC
        // mismatch).
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let signature = sign_ed25519_unverified(message, sk.expose_secret()).unwrap();

        // 32 bytes but not a valid Ed25519 point
        let bad_pk = vec![0xFF; 32];
        let result = verify_ed25519_unverified(message, &signature, bad_pk.as_slice());
        assert_eq!(result.ok(), Some(false), "Invalid Ed25519 point should yield Ok(false)");
    }

    #[test]
    fn test_ed25519_sign_with_config_validation_succeeds() {
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let config = CoreConfig::default();

        let result = sign_ed25519_with_config(
            message,
            sk.expose_secret(),
            &config,
            SecurityMode::Unverified,
        );
        assert!(result.is_ok(), "Signing with valid config should succeed");
    }

    #[test]
    fn test_ed25519_verify_with_config_validation_succeeds() {
        let message = b"Test message";
        let (pk, sk) = generate_keypair().expect("keygen should succeed");
        let config = CoreConfig::default();

        let signature = sign_ed25519_unverified(message, sk.expose_secret()).unwrap();
        let result = verify_ed25519_with_config(
            message,
            &signature,
            pk.as_slice(),
            &config,
            SecurityMode::Unverified,
        );
        assert!(result.is_ok());
    }

    // Unverified variant tests for coverage
    #[test]
    fn test_ed25519_sign_with_config_unverified_succeeds() {
        let message = b"Test message";
        let (_, sk) = generate_keypair().expect("keygen should succeed");
        let config = CoreConfig::default();

        let result = sign_ed25519_with_config_unverified(message, sk.expose_secret(), &config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_ed25519_verify_with_config_unverified_succeeds() {
        let message = b"Test message";
        let (pk, sk) = generate_keypair().expect("keygen should succeed");
        let config = CoreConfig::default();

        let signature = sign_ed25519_unverified(message, sk.expose_secret()).unwrap();
        let result =
            verify_ed25519_with_config_unverified(message, &signature, pk.as_slice(), &config);
        assert!(result.is_ok());
    }
}