miden-crypto 0.34.0

Miden Cryptographic primitives
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
use alloc::{string::ToString, vec::Vec};
use core::marker::PhantomData;

use miden_crypto_derive::{SilentDebug, SilentDisplay};
use num::{Complex, Float, Zero};
use num_complex::Complex64;
use rand::{CryptoRng, Rng};

use super::{
    super::{
        FalconVariant, LOG_N, MODULUS, N, Nonce, SIG_L2_BOUND, SIGMA, SK_LEN, ShortLatticeBasis,
        Signature,
        math::{
            FalconFelt, FastFft, LdlTree, Polynomial, check_coefficients_bound, ffldl, ffsampling,
            gram, has_acceptable_gram_schmidt_norm, normalize_tree, ntru_gen,
        },
        signature::SignaturePoly,
    },
    PublicKey,
};
use crate::{
    Word,
    hash::blake::Blake3_256,
    utils::{
        ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
        read_sensitive_array,
        zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing},
    },
};

// CONSTANTS
// ================================================================================================

pub(crate) const WIDTH_BIG_POLY_COEFFICIENT: usize = 8;
pub(crate) const WIDTH_SMALL_POLY_COEFFICIENT: usize = 6;

// SECRET KEY
// ================================================================================================

/// Represents the secret key for Falcon DSA.
///
/// The secret key is a quadruple [[g, -f], [G, -F]] of polynomials with integer coefficients. Each
/// polynomial has degree at most N = 512, and computations use the quotient ring defined by the
/// monic irreducible polynomial ϕ = x^N + 1. The secret key is a short basis for a lattice under
/// the norm bound required by the security parameters. The public key is another basis for the
/// same lattice and can be described by a single polynomial h with integer coefficients modulo ϕ.
/// The two keys are related by the following relation:
///
/// 1. h = g /f [mod ϕ][mod p]
/// 2. f.G - g.F = p [mod ϕ]
///
/// where p = 12289 is the Falcon prime. Equation 2 is called the NTRU equation.
/// The secret key is generated by first sampling a random pair (f, g) of polynomials using
/// an appropriate distribution that yields short but not too short polynomials with integer
/// coefficients modulo ϕ. The NTRU equation is then used to find a matching pair (F, G).
/// The public key is then derived from the secret key using equation 1.
///
/// For efficient signature generation, the secret key is preprocessed into an LDL tree. This form
/// supports fast sampling of short lattice vectors with the ffSampling algorithm described as
/// Algorithm 11 in [1].
///
/// [1]: <https://falcon-sign.info/falcon.pdf>
#[derive(Clone, SilentDebug, SilentDisplay)]
pub struct SecretKey<V: FalconVariant> {
    secret_key: ShortLatticeBasis,
    tree: LdlTree,
    variant: PhantomData<fn() -> V>,
}

impl<V: FalconVariant> Zeroize for SecretKey<V> {
    fn zeroize(&mut self) {
        self.secret_key.zeroize();
        self.tree.zeroize();
    }
}

// Implement `Drop` manually because the `ZeroizeOnDrop` derive is unavailable when `zeroize`
// comes through `k256`.
impl<V: FalconVariant> Drop for SecretKey<V> {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl<V: FalconVariant> ZeroizeOnDrop for SecretKey<V> {}

#[allow(clippy::new_without_default)]
impl<V: FalconVariant> SecretKey<V> {
    // CONSTRUCTORS
    // --------------------------------------------------------------------------------------------

    /// Generates a secret key from OS-provided randomness.
    #[cfg(feature = "std")]
    pub fn new() -> Self {
        let mut rng = rand::rng();
        Self::with_rng(&mut rng)
    }

    /// Generates a secret key with the provided random-number generator.
    pub fn with_rng<R: CryptoRng + Rng>(rng: &mut R) -> Self {
        let basis = ntru_gen(N, rng);
        Self::from_short_lattice_basis(basis)
    }

    /// Computes the normalized Falcon LDL tree from the short basis [[g, -f], [G, -F]].
    pub(crate) fn from_short_lattice_basis(basis: ShortLatticeBasis) -> Self {
        // FFT each polynomial of the short basis.
        let basis_fft = to_complex_fft(&basis);
        // Compute the Gram matrix.
        let gram_fft = gram(&basis_fft);
        // Construct the LDL tree of the Gram matrix.
        let mut tree = ffldl(&gram_fft);
        // Normalize the leaves of the LDL tree.
        normalize_tree(&mut tree, SIGMA);
        Self {
            secret_key: basis,
            tree,
            variant: PhantomData,
        }
    }

    // PUBLIC ACCESSORS
    // --------------------------------------------------------------------------------------------

    /// Returns the polynomials of the short lattice basis of this secret key.
    pub fn short_lattice_basis(&self) -> &ShortLatticeBasis {
        &self.secret_key
    }

    /// Returns the public key corresponding to this secret key.
    pub fn public_key(&self) -> PublicKey<V> {
        self.compute_pub_key_poly()
    }

    /// Returns the LDL tree associated to this secret key.
    pub fn tree(&self) -> &LdlTree {
        &self.tree
    }

    // SIGNATURE GENERATION
    // --------------------------------------------------------------------------------------------

    /// Signs a message with this secret key.
    pub fn sign(&self, message: Word) -> Signature<V> {
        use rand::SeedableRng;
        use rand_chacha::ChaCha20Rng;

        let seed = Zeroizing::new(self.generate_seed(&message));
        let mut rng = ChaCha20Rng::from_seed(*seed);
        self.sign_with_rng(message, &mut rng)
    }

    /// Signs a message using randomness from the provided generator.
    pub fn sign_with_rng<R: CryptoRng + Rng>(&self, message: Word, rng: &mut R) -> Signature<V> {
        let nonce = Nonce::deterministic();

        let h = self.compute_pub_key_poly();
        let c = V::hash_message_to_point(message, &nonce);
        let s2 = self.sign_helper(&c, rng);

        Signature::new(nonce, h, s2)
    }

    /// Signs a message using the reference implementation's test configuration.
    ///
    /// This testing helper differs from [`SecretKey::sign_with_rng`] in two ways:
    ///
    /// 1. uses `SHAKE256` for the hash-to-point algorithm, and
    /// 2. uses `ChaCha20` in `Self::sign_helper`.
    ///
    /// It therefore uses separate random-number generators for the nonce and trapdoor sampling,
    /// matching the reference implementation.
    #[cfg(test)]
    pub(crate) fn sign_with_rng_testing<R: Rng>(
        &self,
        message: &[u8],
        rng: &mut R,
    ) -> Signature<V> {
        use super::super::test_utils::{ChaCha, hash_to_point_shake256};

        let nonce = Nonce::random(rng);

        let h = self.compute_pub_key_poly();
        let c = hash_to_point_shake256(message, &nonce);

        let mut chacha_prng = ChaCha::new(rng);
        let s2 = self.sign_helper(&c, &mut chacha_prng);

        Signature::new(nonce, h, s2)
    }

    // HELPER METHODS
    // --------------------------------------------------------------------------------------------

    /// Derives the public key corresponding to this secret key using h = g /f [mod ϕ][mod p].
    fn compute_pub_key_poly(&self) -> PublicKey<V> {
        let g: Polynomial<FalconFelt> = self.secret_key[0].clone().into();
        let g_fft = g.fft();
        let minus_f: Polynomial<FalconFelt> = self.secret_key[1].clone().into();
        let f = -minus_f;
        let f_fft = f.fft();
        let h_fft = g_fft.hadamard_div(&f_fft);
        h_fft.ifft().into()
    }

    /// Signs a message polynomial with the secret key.
    ///
    /// Takes a randomness generator implementing `Rng` and message polynomial representing `c`
    /// the hash-to-point of the message to be signed. It outputs a signature polynomial `s2`.
    fn sign_helper<R: Rng>(&self, c: &Polynomial<FalconFelt>, rng: &mut R) -> SignaturePoly {
        let one_over_q = 1.0 / (MODULUS as f64);
        let c_over_q_fft = c.map(|cc| Complex::new(one_over_q * cc.value() as f64, 0.0)).fft();

        // B = [[FFT(g), -FFT(f)], [FFT(G), -FFT(F)]]
        let [g_fft, minus_f_fft, big_g_fft, minus_big_f_fft] = to_complex_fft(&self.secret_key);
        let t0 = c_over_q_fft.hadamard_mul(&minus_big_f_fft);
        let t1 = -c_over_q_fft.hadamard_mul(&minus_f_fft);

        loop {
            let bold_s = loop {
                let z = ffsampling(&(t0.clone(), t1.clone()), &self.tree, rng);
                let t0_min_z0 = t0.clone() - z.0;
                let t1_min_z1 = t1.clone() - z.1;

                // s = (t-z) * B
                let s0 = t0_min_z0.hadamard_mul(&g_fft) + t1_min_z1.hadamard_mul(&big_g_fft);
                let s1 =
                    t0_min_z0.hadamard_mul(&minus_f_fft) + t1_min_z1.hadamard_mul(&minus_big_f_fft);

                // compute the norm of (s0||s1) and note that they are in FFT representation
                let length_squared: f64 =
                    (s0.coefficients.iter().map(|a| (a * a.conj()).re).sum::<f64>()
                        + s1.coefficients.iter().map(|a| (a * a.conj()).re).sum::<f64>())
                        / (N as f64);

                if length_squared > (SIG_L2_BOUND as f64) {
                    continue;
                }

                break [-s0, s1];
            };

            let s2 = bold_s[1].ifft();
            let s2_coef: [i16; N] = s2
                .coefficients
                .iter()
                .map(|a| Float::round(a.re) as i16)
                .collect::<Vec<i16>>()
                .try_into()
                .expect("The number of coefficients should be equal to N");

            if let Ok(s2) = SignaturePoly::try_from(&s2_coef) {
                return s2;
            }
        }
    }

    /// Derives the deterministic seed used by the trapdoor-sampling PRNG.
    ///
    /// Following [RFC 6979, Section 3.5](https://datatracker.ietf.org/doc/html/rfc6979#section-3.5),
    /// the private key and hashed message are combined as `sk || H(m)` to seed a PRNG. The input
    /// also includes `log_2(N)`, where `N = 512`, to separate Falcon parameter sets as described
    /// in Section 3.4.1 of [1].
    ///
    /// [1]: <https://github.com/algorand/falcon/blob/main/falcon-det.pdf>
    fn generate_seed(&self, message: &Word) -> [u8; 32] {
        let serialized_key = Zeroizing::new(self.to_bytes());
        let mut buffer = Zeroizing::new(Vec::with_capacity(1 + SK_LEN + Word::SERIALIZED_SIZE));
        buffer.push(LOG_N);
        buffer.extend_from_slice(&serialized_key);
        buffer.extend_from_slice(&message.to_bytes());

        let digest = Blake3_256::hash(&buffer);
        digest.into()
    }
}

impl<V: FalconVariant> PartialEq for SecretKey<V> {
    fn eq(&self, other: &Self) -> bool {
        use subtle::ConstantTimeEq;

        let self_bytes = Zeroizing::new(self.to_bytes());
        let other_bytes = Zeroizing::new(other.to_bytes());
        self_bytes.ct_eq(&other_bytes).into()
    }
}

impl<V: FalconVariant> Eq for SecretKey<V> {}

// SERIALIZATION / DESERIALIZATION
// ================================================================================================

impl<V: FalconVariant> Serializable for SecretKey<V> {
    fn write_into<W: ByteWriter>(&self, target: &mut W) {
        let basis = &self.secret_key;

        // header
        let n = basis[0].coefficients.len();
        let l = n.checked_ilog2().unwrap() as u8;
        let header: u8 = (5 << 4) | l;

        let neg_f = &basis[1];
        let g = &basis[0];
        let neg_big_f = &basis[3];

        let mut buffer = Zeroizing::new(Vec::with_capacity(SK_LEN));
        buffer.push(header);

        let f_i8 = Zeroizing::new(
            neg_f
                .coefficients
                .iter()
                .map(|&a| secret_key_coefficient_to_i8(-FalconFelt::new(a)))
                .collect::<Vec<i8>>(),
        );
        let f_i8_encoded = Zeroizing::new(
            encode_i8(&f_i8, WIDTH_SMALL_POLY_COEFFICIENT)
                .expect("valid Falcon key coefficients must be encodable"),
        );
        buffer.extend_from_slice(&f_i8_encoded);

        let g_i8 = Zeroizing::new(
            g.coefficients
                .iter()
                .map(|&a| secret_key_coefficient_to_i8(FalconFelt::new(a)))
                .collect::<Vec<i8>>(),
        );
        let g_i8_encoded = Zeroizing::new(
            encode_i8(&g_i8, WIDTH_SMALL_POLY_COEFFICIENT)
                .expect("valid Falcon key coefficients must be encodable"),
        );
        buffer.extend_from_slice(&g_i8_encoded);

        let big_f_i8 = Zeroizing::new(
            neg_big_f
                .coefficients
                .iter()
                .map(|&a| secret_key_coefficient_to_i8(-FalconFelt::new(a)))
                .collect::<Vec<i8>>(),
        );
        let big_f_i8_encoded = Zeroizing::new(
            encode_i8(&big_f_i8, WIDTH_BIG_POLY_COEFFICIENT)
                .expect("valid Falcon key coefficients must be encodable"),
        );
        buffer.extend_from_slice(&big_f_i8_encoded);

        target.write_bytes(&buffer);
    }
}

impl<V: FalconVariant> Deserializable for SecretKey<V> {
    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
        let byte_vector = read_sensitive_array::<SK_LEN, _>(source)?;

        // read fields
        let header = byte_vector[0];

        // check fixed bits in header
        if (header >> 4) != 5 {
            return Err(DeserializationError::InvalidValue("Invalid header format".to_string()));
        }

        // check log n
        let logn = (header & 15) as usize;
        let n = 1 << logn;

        // match against const variant generic parameter
        if n != N {
            return Err(DeserializationError::InvalidValue(
                "Unsupported Falcon DSA variant".to_string(),
            ));
        }

        let chunk_size_f = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
        let chunk_size_g = ((n * WIDTH_SMALL_POLY_COEFFICIENT) + 7) >> 3;
        let chunk_size_big_f = ((n * WIDTH_BIG_POLY_COEFFICIENT) + 7) >> 3;

        let f = Zeroizing::new(
            decode_i8(&byte_vector[1..chunk_size_f + 1], WIDTH_SMALL_POLY_COEFFICIENT).ok_or(
                DeserializationError::InvalidValue("Failed to decode f coefficients".to_string()),
            )?,
        );
        let g = Zeroizing::new(
            decode_i8(
                &byte_vector[chunk_size_f + 1..(chunk_size_f + chunk_size_g + 1)],
                WIDTH_SMALL_POLY_COEFFICIENT,
            )
            .ok_or(DeserializationError::InvalidValue(
                "Failed to decode g coefficients".to_string(),
            ))?,
        );
        let big_f = Zeroizing::new(
            decode_i8(
                &byte_vector[(chunk_size_f + chunk_size_g + 1)
                    ..(chunk_size_f + chunk_size_g + chunk_size_big_f + 1)],
                WIDTH_BIG_POLY_COEFFICIENT,
            )
            .ok_or(DeserializationError::InvalidValue(
                "Failed to decode F coefficients".to_string(),
            ))?,
        );

        let mut f = Polynomial::new(f.iter().map(|&c| i16::from(c)).collect());
        let g = Polynomial::new(g.iter().map(|&c| i16::from(c)).collect());
        let mut big_f = Polynomial::new(big_f.iter().map(|&c| i16::from(c)).collect());

        let f_fft = Polynomial::<FalconFelt>::from(&f).fft();
        if f_fft.coefficients.iter().any(Zero::is_zero) {
            return Err(DeserializationError::InvalidValue(
                "Falcon secret key polynomial f is not invertible".to_string(),
            ));
        }

        if !has_acceptable_gram_schmidt_norm(&f, &g) {
            return Err(DeserializationError::InvalidValue(
                "Falcon secret key exceeds the Gram-Schmidt norm bound".to_string(),
            ));
        }

        let g_fft = Polynomial::<FalconFelt>::from(&g).fft();
        let big_f_fft = Polynomial::<FalconFelt>::from(&big_f).fft();
        let big_g = g_fft.hadamard_div(&f_fft).hadamard_mul(&big_f_fft).ifft();
        let big_g = Polynomial::new(big_g.to_balanced_values());

        let big_coefficient_bound = (1 << (WIDTH_BIG_POLY_COEFFICIENT - 1)) - 1;
        if !check_coefficients_bound(&big_g, big_coefficient_bound as i16) {
            return Err(DeserializationError::InvalidValue(
                "Falcon secret key polynomial G exceeds its coefficient bound".to_string(),
            ));
        }

        if !satisfies_ntru_relation(&f, &g, &big_f, &big_g) {
            return Err(DeserializationError::InvalidValue(
                "Falcon secret key does not satisfy the NTRU equation".to_string(),
            ));
        }

        for coefficient in &mut f.coefficients {
            *coefficient = -*coefficient;
        }
        for coefficient in &mut big_f.coefficients {
            *coefficient = -*coefficient;
        }

        let basis = [g, f, big_g, big_f];
        Ok(Self::from_short_lattice_basis(basis))
    }
}

// HELPER FUNCTIONS
// ================================================================================================

/// Computes the complex FFT of the secret key polynomials.
fn to_complex_fft(basis: &[Polynomial<i16>; 4]) -> [Polynomial<Complex<f64>>; 4] {
    let [g, f, big_g, big_f] = basis.clone();
    let g_fft = g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
    let minus_f_fft = f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
    let big_g_fft = big_g.map(|cc| Complex64::new(*cc as f64, 0.0)).fft();
    let minus_big_f_fft = big_f.map(|cc| -Complex64::new(*cc as f64, 0.0)).fft();
    [g_fft, minus_f_fft, big_g_fft, minus_big_f_fft]
}

/// Checks `f * G - g * F = q` in `Z[x] / (x^N + 1)`.
fn satisfies_ntru_relation(
    f: &Polynomial<i16>,
    g: &Polynomial<i16>,
    big_f: &Polynomial<i16>,
    big_g: &Polynomial<i16>,
) -> bool {
    let f = f.map(|&coefficient| i64::from(coefficient));
    let g = g.map(|&coefficient| i64::from(coefficient));
    let big_f = big_f.map(|&coefficient| i64::from(coefficient));
    let big_g = big_g.map(|&coefficient| i64::from(coefficient));

    let determinant = (f * big_g - g * big_f).reduce_by_cyclotomic(N);
    determinant == Polynomial::constant(i64::from(MODULUS))
}

fn secret_key_coefficient_to_i8(coefficient: FalconFelt) -> i8 {
    i8::try_from(coefficient.balanced_value())
        .expect("valid Falcon secret-key coefficients must fit in i8")
}

/// Encodes a sequence of signed integers such that each integer x satisfies |x| < 2^(bits-1)
/// for a given parameter bits. bits can take either the value 6 or 8.
pub fn encode_i8(x: &[i8], bits: usize) -> Option<Vec<u8>> {
    let maxv = (1 << (bits - 1)) - 1_usize;
    let maxv = maxv as i8;
    let minv = -maxv;

    for &c in x {
        if c > maxv || c < minv {
            return None;
        }
    }

    let out_len = ((N * bits) + 7) >> 3;
    let mut buf = vec![0_u8; out_len];

    let mut acc = 0_u32;
    let mut acc_len = 0;
    let mask = ((1_u16 << bits) - 1) as u8;

    let mut input_pos = 0;
    for &c in x {
        acc = (acc << bits) | (c as u8 & mask) as u32;
        acc_len += bits;
        while acc_len >= 8 {
            acc_len -= 8;
            buf[input_pos] = (acc >> acc_len) as u8;
            input_pos += 1;
        }
    }
    if acc_len > 0 {
        buf[input_pos] = (acc >> (8 - acc_len)) as u8;
    }

    Some(buf)
}

/// Decodes a sequence of bytes into a sequence of signed integers such that each integer x
/// satisfies |x| < 2^(bits-1) for a given parameter bits. bits can take either the value 6 or 8.
pub fn decode_i8(buf: &[u8], bits: usize) -> Option<Vec<i8>> {
    let mut x = Zeroizing::new([0_i8; N]);

    let mut i = 0;
    let mut j = 0;
    let mut acc = 0_u32;
    let mut acc_len = 0;
    let mask = (1_u32 << bits) - 1;
    let a = (1 << bits) as u8;
    let b = ((1 << (bits - 1)) - 1) as u8;

    while i < N {
        acc = (acc << 8) | (buf[j] as u32);
        j += 1;
        acc_len += 8;

        while acc_len >= bits && i < N {
            acc_len -= bits;
            let w = (acc >> acc_len) & mask;

            if w == 1 << (bits - 1) {
                return None;
            }

            let w = w as u8;

            let z = if w > b { w as i8 - a as i8 } else { w as i8 };

            x[i] = z;
            i += 1;
        }
    }

    if (acc & ((1u32 << acc_len) - 1)) == 0 {
        Some(x.to_vec())
    } else {
        None
    }
}

// TESTS
// ================================================================================================

#[cfg(test)]
mod tests {
    use rand::SeedableRng;
    use rand_chacha::ChaCha20Rng;

    use super::*;

    type TestSecretKey = SecretKey<super::super::super::TestVariant>;

    #[test]
    fn secret_key_deserialization_rejects_noninvertible_f() {
        let mut encoded = vec![0u8; SK_LEN];
        encoded[0] = (5 << 4) | LOG_N;

        assert_invalid_key(&encoded, "Falcon secret key polynomial f is not invertible");
    }

    #[test]
    fn secret_key_deserialization_rejects_excessive_norm() {
        let mut f = Polynomial::new(vec![0i16; N]);
        f.coefficients[0] = 1;
        let g = Polynomial::new(vec![31i16; N]);
        let big_f = Polynomial::new(vec![0i16; N]);
        let encoded = encode_secret_key(&f, &g, &big_f);

        assert_invalid_key(&encoded, "Falcon secret key exceeds the Gram-Schmidt norm bound");
    }

    #[test]
    fn secret_key_deserialization_rejects_invalid_ntru_relation() {
        let (f, g) = acceptable_f_and_g();
        let big_f = Polynomial::new(vec![0i16; N]);
        let encoded = encode_secret_key(&f, &g, &big_f);

        assert_invalid_key(&encoded, "Falcon secret key does not satisfy the NTRU equation");
    }

    #[test]
    fn secret_key_deserialization_rejects_out_of_range_reconstructed_big_g() {
        let (f, g) = acceptable_f_and_g();
        // This deterministic pair reconstructs a coefficient of G outside the signed 8-bit
        // encoding range when F is the constant polynomial 127.
        let big_f = constant_polynomial(127);
        let encoded = encode_secret_key(&f, &g, &big_f);

        assert_invalid_key(
            &encoded,
            "Falcon secret key polynomial G exceeds its coefficient bound",
        );
    }

    #[test]
    fn secret_key_deserialization_rejects_forbidden_minimum_coefficients() {
        let f_offset = 1;
        let g_offset = f_offset + N * WIDTH_SMALL_POLY_COEFFICIENT / 8;
        let big_f_offset = g_offset + N * WIDTH_SMALL_POLY_COEFFICIENT / 8;

        for (offset, polynomial) in [(f_offset, "f"), (g_offset, "g"), (big_f_offset, "F")] {
            let mut encoded = vec![0u8; SK_LEN];
            encoded[0] = (5 << 4) | LOG_N;
            encoded[offset] = 0b1000_0000;

            assert_invalid_key(&encoded, &format!("Failed to decode {polynomial} coefficients"));
        }
    }

    fn constant_polynomial(value: i16) -> Polynomial<i16> {
        let mut polynomial = Polynomial::new(vec![0i16; N]);
        polynomial.coefficients[0] = value;
        polynomial
    }

    fn acceptable_f_and_g() -> (Polynomial<i16>, Polynomial<i16>) {
        let mut rng = ChaCha20Rng::from_seed([9u8; 32]);
        let [g, minus_f, _, _] = ntru_gen(N, &mut rng);
        (-minus_f, g)
    }

    fn encode_secret_key(
        f: &Polynomial<i16>,
        g: &Polynomial<i16>,
        big_f: &Polynomial<i16>,
    ) -> Vec<u8> {
        let encode = |polynomial: &Polynomial<i16>, width| {
            let coefficients = polynomial
                .coefficients
                .iter()
                .map(|&coefficient| coefficient as i8)
                .collect::<Vec<_>>();
            encode_i8(&coefficients, width).unwrap()
        };

        let mut encoded = Vec::with_capacity(SK_LEN);
        encoded.push((5 << 4) | LOG_N);
        encoded.extend_from_slice(&encode(f, WIDTH_SMALL_POLY_COEFFICIENT));
        encoded.extend_from_slice(&encode(g, WIDTH_SMALL_POLY_COEFFICIENT));
        encoded.extend_from_slice(&encode(big_f, WIDTH_BIG_POLY_COEFFICIENT));
        assert_eq!(encoded.len(), SK_LEN);
        encoded
    }

    fn assert_invalid_key(encoded: &[u8], expected_message: &str) {
        let error = TestSecretKey::read_from_bytes(encoded).unwrap_err();
        assert_eq!(error, DeserializationError::InvalidValue(expected_message.to_string()),);
    }
}