Skip to main content

tide_fn_dsa_comm/
lib.rs

1#![no_std]
2
3//! This crate contains low-level utility functions which are used by the
4//! sibling FN-DSA crates for key pair generation, signing, and verifying.
5//! It is public only because these crates are split at the Cargo level;
6//! applications should normally depend on `tide-fn-dsa`,
7//! `tide-fn-dsa-kgen`, `tide-fn-dsa-sign`, or `tide-fn-dsa-vrfy`
8//! instead.
9//!
10//! The modules exposed here are implementation-level building blocks, not a
11//! stable application-facing API surface.
12
13use core::fmt;
14
15/// Encoding/decoding primitives.
16#[doc(hidden)]
17pub mod codec;
18
19/// Computations with polynomials modulo X^n+1 and modulo q = 12289.
20#[doc(hidden)]
21pub mod mq;
22
23/// SHAKE implementation.
24#[doc(hidden)]
25pub mod shake;
26
27/// Specialized versions of `mq` which use AVX2 opcodes (on x86 CPUs).
28/// Kept available when features are unified across split packages; runtime
29/// dispatch is disabled globally by `no_avx2`.
30#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
31#[doc(hidden)]
32pub mod mq_avx2;
33
34// Re-export RNG traits to get a smooth dependency management.
35pub use rand_core::{CryptoRng, Error as RngError, RngCore};
36
37/// Symbolic constant for FN-DSA with degree 512 (`logn = 9`).
38pub const FN_DSA_LOGN_512: u32 = 9;
39
40/// Symbolic constant for FN-DSA with degree 1024 (`logn = 10`).
41pub const FN_DSA_LOGN_1024: u32 = 10;
42
43/// Error type for invalid degree parameters.
44#[derive(Copy, Clone, Debug, Eq, PartialEq)]
45pub enum LogNError {
46    /// Supported degree parameters are in the `2..=10` range.
47    UnsupportedLogN { logn: u32 },
48}
49
50impl fmt::Display for LogNError {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        match *self {
53            Self::UnsupportedLogN { logn } => {
54                write!(f, "unsupported degree parameter logn={logn}")
55            }
56        }
57    }
58}
59
60/// Validate a degree parameter.
61pub const fn check_logn(logn: u32) -> Result<(), LogNError> {
62    if logn < 2 || logn > 10 {
63        Err(LogNError::UnsupportedLogN { logn })
64    } else {
65        Ok(())
66    }
67}
68
69const fn sign_key_size_inner(logn: u32) -> usize {
70    let n = 1usize << logn;
71    let nbits_fg = match logn {
72        2..=5 => 8,
73        6..=7 => 7,
74        8..=9 => 6,
75        _ => 5,
76    };
77    1 + (nbits_fg << (logn - 2)) + n
78}
79
80/// Signing key size for degree 512 (`logn = 9`).
81pub const SIGN_KEY_SIZE_512: usize = sign_key_size_inner(FN_DSA_LOGN_512);
82
83/// Signing key size for degree 1024 (`logn = 10`).
84pub const SIGN_KEY_SIZE_1024: usize = sign_key_size_inner(FN_DSA_LOGN_1024);
85
86/// Get the size (in bytes) of a signing key for the provided degree
87/// (degree is `n = 2^logn`, with `2 <= logn <= 10`).
88pub const fn sign_key_size(logn: u32) -> Result<usize, LogNError> {
89    if let Err(err) = check_logn(logn) {
90        Err(err)
91    } else {
92        Ok(sign_key_size_inner(logn))
93    }
94}
95
96const fn vrfy_key_size_inner(logn: u32) -> usize {
97    1 + (7 << (logn - 2))
98}
99
100/// Verifying key size for degree 512 (`logn = 9`).
101pub const VRFY_KEY_SIZE_512: usize = vrfy_key_size_inner(FN_DSA_LOGN_512);
102
103/// Verifying key size for degree 1024 (`logn = 10`).
104pub const VRFY_KEY_SIZE_1024: usize = vrfy_key_size_inner(FN_DSA_LOGN_1024);
105
106/// Get the size (in bytes) of a verifying key for the provided degree
107/// (degree is `n = 2^logn`, with `2 <= logn <= 10`).
108pub const fn vrfy_key_size(logn: u32) -> Result<usize, LogNError> {
109    if let Err(err) = check_logn(logn) {
110        Err(err)
111    } else {
112        Ok(vrfy_key_size_inner(logn))
113    }
114}
115
116const fn signature_size_inner(logn: u32) -> usize {
117    44 + 3 * (256 >> (10 - logn))
118        + 2 * (128 >> (10 - logn))
119        + 3 * (64 >> (10 - logn))
120        + 2 * (16 >> (10 - logn))
121        - 2 * (2 >> (10 - logn))
122        - 8 * (1 >> (10 - logn))
123}
124
125/// Signature size for degree 512 (`logn = 9`).
126pub const SIGNATURE_SIZE_512: usize = signature_size_inner(FN_DSA_LOGN_512);
127
128/// Signature size for degree 1024 (`logn = 10`).
129pub const SIGNATURE_SIZE_1024: usize = signature_size_inner(FN_DSA_LOGN_1024);
130
131/// Get the size (in bytes) of a signature for the provided degree
132/// (degree is `n = 2^logn`, with `2 <= logn <= 10`).
133pub const fn signature_size(logn: u32) -> Result<usize, LogNError> {
134    // logn   n      size
135    //   2      4      47
136    //   3      8      52
137    //   4     16      63
138    //   5     32      82
139    //   6     64     122
140    //   7    128     200
141    //   8    256     356
142    //   9    512     666
143    //  10   1024    1280
144    if let Err(err) = check_logn(logn) {
145        Err(err)
146    } else {
147        Ok(signature_size_inner(logn))
148    }
149}
150
151/// Falcon-compatible raw-message profile.
152#[derive(Copy, Clone, Debug, Eq, PartialEq)]
153pub enum FalconProfile {
154    /// Falcon/PQClean raw-message mode, including padded signature verification.
155    /// Use `TidecoinStrict` for the node's exact-consumption strict rules.
156    PqClean,
157
158    /// Tidecoin rc3 strict Falcon-512/1024: canonical, exactly consumed signatures.
159    /// Unlike `PqClean`, verification never accepts appended zero padding.
160    TidecoinStrict,
161
162    /// Historical Tidecoin Falcon-512 verification, including negative zero and
163    /// unused final bits. Signing still produces canonical encodings.
164    TidecoinLegacyFalcon512,
165}
166
167impl fmt::Display for FalconProfile {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        match *self {
170            Self::PqClean => write!(f, "FalconPqClean"),
171            Self::TidecoinStrict => write!(f, "TidecoinStrict"),
172            Self::TidecoinLegacyFalcon512 => {
173                write!(f, "TidecoinLegacyFalcon512")
174            }
175        }
176    }
177}
178
179/// Falcon nonce length in bytes.
180pub const FALCON_NONCE_LEN: usize = 40;
181
182/// Historical Falcon-512 signer body capacity; not a verification limit.
183pub const TIDECOIN_LEGACY_FALCON512_SIG_BODY_MAX: usize = 647;
184
185/// Historical Falcon-512 signer capacity; not the node wallet signing bound
186/// (666 bytes) and not a verification limit.
187pub const TIDECOIN_LEGACY_FALCON512_SIG_MAX: usize =
188    1 + FALCON_NONCE_LEN + TIDECOIN_LEGACY_FALCON512_SIG_BODY_MAX;
189
190/// The message for which a signature is to be generated or verified is
191/// pre-hashed by the caller and provided as a hash value along with
192/// an identifier of the used hash function. The identifier is normally
193/// an encoded ASN.1 OID. A special identifier is used for "raw" messages
194/// (i.e. not pre-hashed at all); it uses a single byte of value 0x00.
195#[derive(Copy, Clone, Debug, Eq, PartialEq)]
196pub struct HashIdentifier<'a>(&'a [u8]);
197
198/// Error type for hash identifiers.
199#[derive(Copy, Clone, Debug, Eq, PartialEq)]
200pub enum HashIdentifierError {
201    /// Hash identifiers must not be empty.
202    Empty,
203
204    /// One-byte identifiers are reserved for internal special values.
205    InvalidSingleByteValue { actual: u8 },
206}
207
208impl fmt::Display for HashIdentifierError {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        match *self {
211            Self::Empty => write!(f, "hash identifier must not be empty"),
212            Self::InvalidSingleByteValue { actual } => {
213                write!(f, "invalid one-byte hash identifier value: 0x{actual:02X}")
214            }
215        }
216    }
217}
218
219impl<'a> HashIdentifier<'a> {
220    /// Create a validated hash identifier.
221    pub fn new(bytes: &'a [u8]) -> Result<Self, HashIdentifierError> {
222        if bytes.is_empty() {
223            return Err(HashIdentifierError::Empty);
224        }
225        if bytes.len() == 1 && bytes[0] != 0x00 {
226            return Err(HashIdentifierError::InvalidSingleByteValue { actual: bytes[0] });
227        }
228        Ok(Self(bytes))
229    }
230
231    /// Get the raw identifier bytes.
232    pub const fn as_bytes(&self) -> &'a [u8] {
233        self.0
234    }
235
236    /// Test whether this is the raw-message identifier.
237    pub const fn is_raw(&self) -> bool {
238        self.0.len() == 1 && self.0[0] == 0x00
239    }
240}
241
242/// Hash function identifier: none.
243///
244/// This is the identifier used internally to specify that signature
245/// generation and verification are performed over a raw message, without
246/// pre-hashing.
247pub const HASH_ID_RAW: HashIdentifier = HashIdentifier(&[0x00]);
248
249/// Hash function identifier: SHA-256
250pub const HASH_ID_SHA256: HashIdentifier = HashIdentifier(&[
251    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
252]);
253
254/// Hash function identifier: SHA-384
255pub const HASH_ID_SHA384: HashIdentifier = HashIdentifier(&[
256    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
257]);
258
259/// Hash function identifier: SHA-512
260pub const HASH_ID_SHA512: HashIdentifier = HashIdentifier(&[
261    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
262]);
263
264/// Hash function identifier: SHA-512-256
265pub const HASH_ID_SHA512_256: HashIdentifier = HashIdentifier(&[
266    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06,
267]);
268
269/// Hash function identifier: SHA3-256
270pub const HASH_ID_SHA3_256: HashIdentifier = HashIdentifier(&[
271    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08,
272]);
273
274/// Hash function identifier: SHA3-384
275pub const HASH_ID_SHA3_384: HashIdentifier = HashIdentifier(&[
276    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x09,
277]);
278
279/// Hash function identifier: SHA3-512
280pub const HASH_ID_SHA3_512: HashIdentifier = HashIdentifier(&[
281    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0A,
282]);
283
284/// Hash function identifier: SHAKE128
285pub const HASH_ID_SHAKE128: HashIdentifier = HashIdentifier(&[
286    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0B,
287]);
288
289/// Hash function identifier: SHAKE256
290pub const HASH_ID_SHAKE256: HashIdentifier = HashIdentifier(&[
291    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0C,
292]);
293
294/// When a message is signed or verified, it is accompanied with a domain
295/// separation context, which is an arbitrary sequence of bytes of length
296/// at most 255. Such a context is wrapped in a `DomainContext` structure.
297#[derive(Copy, Clone, Debug, Eq, PartialEq)]
298pub struct DomainContext<'a>(&'a [u8]);
299
300/// Error type for domain-separation contexts.
301#[derive(Copy, Clone, Debug, Eq, PartialEq)]
302pub enum DomainContextError {
303    /// Domain-separation contexts are limited to 255 bytes.
304    Oversized { actual: usize },
305}
306
307impl fmt::Display for DomainContextError {
308    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309        match *self {
310            Self::Oversized { actual } => write!(
311                f,
312                "invalid domain context length: expected at most 255 bytes, got {actual}"
313            ),
314        }
315    }
316}
317
318impl<'a> DomainContext<'a> {
319    /// Create a validated domain-separation context.
320    pub fn new(bytes: &'a [u8]) -> Result<Self, DomainContextError> {
321        if bytes.len() > 255 {
322            return Err(DomainContextError::Oversized {
323                actual: bytes.len(),
324            });
325        }
326        Ok(Self(bytes))
327    }
328
329    /// Create an empty domain-separation context.
330    pub const fn empty() -> Self {
331        Self(b"")
332    }
333
334    /// Get the raw bytes for this context.
335    pub const fn as_bytes(&self) -> &'a [u8] {
336        self.0
337    }
338
339    /// Test whether the context is empty.
340    pub const fn is_empty(&self) -> bool {
341        self.0.is_empty()
342    }
343
344    /// Get the context length in bytes.
345    pub const fn len(&self) -> usize {
346        self.0.len()
347    }
348}
349
350/// Empty domain separation context.
351pub const DOMAIN_NONE: DomainContext = DomainContext::empty();
352
353/// Error type for message hashing into a point.
354#[derive(Copy, Clone, Debug, Eq, PartialEq)]
355pub enum HashToPointError {
356    /// The nonce must contain exactly 40 bytes.
357    InvalidNonceLength { actual: usize },
358
359    /// The hashed verifying key must contain exactly 64 bytes.
360    InvalidHashedVerifyingKeyLength { actual: usize },
361}
362
363impl fmt::Display for HashToPointError {
364    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
365        match *self {
366            Self::InvalidNonceLength { actual } => {
367                write!(f, "invalid nonce length: expected 40 bytes, got {actual}")
368            }
369            Self::InvalidHashedVerifyingKeyLength { actual } => write!(
370                f,
371                "invalid hashed verifying key length: expected 64 bytes, got {actual}"
372            ),
373        }
374    }
375}
376
377/// Hash a message into a polynomial modulo q = 12289.
378///
379/// Parameters are:
380///
381///  - `nonce`:            40-byte random nonce
382///  - `hashed_vrfy_key`:  SHAKE256 hash of public (verifying) key (64 bytes)
383///  - `ctx`:              domain separation context
384///  - `id`:               identifier for pre-hash function
385///  - `hv`:               message (pre-hashed)
386///  - `c`:                output polynomial
387///
388/// If `id` is `HASH_ID_RAW`, then no-prehashing is applied and the message
389/// itself should be provided as `hv`. Otherwise, the caller is responsible
390/// for applying the pre-hashing, and `hv` shall be the hashed message.
391pub fn hash_to_point(
392    nonce: &[u8],
393    hashed_vrfy_key: &[u8],
394    ctx: &DomainContext,
395    id: &HashIdentifier,
396    hv: &[u8],
397    c: &mut [u16],
398) -> Result<(), HashToPointError> {
399    if nonce.len() != FALCON_NONCE_LEN {
400        return Err(HashToPointError::InvalidNonceLength {
401            actual: nonce.len(),
402        });
403    }
404    if hashed_vrfy_key.len() != 64 {
405        return Err(HashToPointError::InvalidHashedVerifyingKeyLength {
406            actual: hashed_vrfy_key.len(),
407        });
408    }
409    hash_to_point_inner(nonce, hashed_vrfy_key, ctx, id, hv, c);
410    Ok(())
411}
412
413/// Hash a raw Falcon/PQClean message into a polynomial modulo q = 12289.
414///
415/// Parameters are:
416///
417///  - `nonce`:    40-byte random nonce
418///  - `message`:  raw message bytes
419///  - `c`:        output polynomial
420pub fn hash_to_point_falcon(
421    nonce: &[u8],
422    message: &[u8],
423    c: &mut [u16],
424) -> Result<(), HashToPointError> {
425    if nonce.len() != FALCON_NONCE_LEN {
426        return Err(HashToPointError::InvalidNonceLength {
427            actual: nonce.len(),
428        });
429    }
430    hash_to_point_falcon_inner(nonce, message, c);
431    Ok(())
432}
433
434fn hash_to_point_inner(
435    nonce: &[u8],
436    hashed_vrfy_key: &[u8],
437    ctx: &DomainContext,
438    id: &HashIdentifier,
439    hv: &[u8],
440    c: &mut [u16],
441) {
442    debug_assert!(ctx.len() <= 255);
443    debug_assert!(!id.as_bytes().is_empty());
444    debug_assert!(id.as_bytes().len() != 1 || id.is_raw());
445
446    // Input order:
447    //   With pre-hashing:
448    //     nonce || hashed_vrfy_key || 0x01 || len(ctx) || ctx || id || hv
449    //   Without pre-hashing:
450    //     nonce || hashed_vrfy_key || 0x00 || len(ctx) || ctx || message
451    // 'len(ctx)' is the length of the context over one byte (0 to 255).
452    let raw_message = id.is_raw();
453    let mut sh = shake::SHAKE256::new();
454    sh.inject(nonce).unwrap();
455    sh.inject(hashed_vrfy_key).unwrap();
456    sh.inject(&[if raw_message { 0u8 } else { 1u8 }]).unwrap();
457    sh.inject(&[ctx.len() as u8]).unwrap();
458    sh.inject(ctx.as_bytes()).unwrap();
459    if !raw_message {
460        sh.inject(id.as_bytes()).unwrap();
461    }
462    sh.inject(hv).unwrap();
463    sh.flip().unwrap();
464    let mut i = 0;
465    while i < c.len() {
466        let mut v = [0u8; 2];
467        sh.extract(&mut v).unwrap();
468        let mut w = ((v[0] as u16) << 8) | (v[1] as u16);
469        if w < 61445 {
470            while w >= 12289 {
471                w -= 12289;
472            }
473            c[i] = w;
474            i += 1;
475        }
476    }
477}
478
479fn hash_to_point_falcon_inner(nonce: &[u8], message: &[u8], c: &mut [u16]) {
480    let mut sh = shake::SHAKE256::new();
481    sh.inject(nonce).unwrap();
482    sh.inject(message).unwrap();
483    sh.flip().unwrap();
484    let mut i = 0;
485    while i < c.len() {
486        let mut v = [0u8; 2];
487        sh.extract(&mut v).unwrap();
488        let mut w = ((v[0] as u16) << 8) | (v[1] as u16);
489        if w < 61445 {
490            while w >= 12289 {
491                w -= 12289;
492            }
493            c[i] = w;
494            i += 1;
495        }
496    }
497}
498
499/// Trait for a deterministic pseudorandom generator.
500///
501/// The trait `PRNG` characterizes a stateful object that produces
502/// pseudorandom bytes (and larger values) in a cryptographically secure
503/// way; the object is created with a source seed, and the output is
504/// indistinguishable from uniform randomness up to exhaustive enumeration
505/// of the possible values of the seed.
506///
507/// `PRNG` instances must implement `Zeroize` so owners can clear secret state.
508/// They also implement `Copy` and `Clone` so that they
509/// may be embedded in clonable structures. This implies that copying a
510/// `PRNG` instance is supposed to clone its internal state, and the copy
511/// will output the same values as the original.
512pub trait PRNG: Copy + Clone + zeroize::Zeroize {
513    /// Create a new instance over the provided seed.
514    fn new(seed: &[u8]) -> Self;
515    /// Get the next byte from the PRNG.
516    fn next_u8(&mut self) -> u8;
517    /// Get the 16-bit value from the PRNG.
518    fn next_u16(&mut self) -> u16;
519    /// Get the 64-bit value from the PRNG.
520    fn next_u64(&mut self) -> u64;
521}
522
523#[cfg(all(
524    not(feature = "no_avx2"),
525    any(target_arch = "x86_64", target_arch = "x86")
526))]
527cpufeatures::new!(cpuid_avx2, "avx2");
528
529/// Do a rutime check for AVX2 support (x86 and x86_64 only).
530///
531/// This is a specialized subcase of the is_x86_feature_detected macro,
532/// except that this function is compatible with `no_std` builds.
533#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
534pub fn has_avx2() -> bool {
535    #[cfg(feature = "no_avx2")]
536    {
537        false
538    }
539    #[cfg(not(feature = "no_avx2"))]
540    {
541        cpuid_avx2::get()
542    }
543}
544
545/// Borrowed secret workspace cleared on normal return or unwinding.
546/// It does not own or clear caller output buffers.
547#[doc(hidden)]
548pub struct ClearOnDrop<'a, T: zeroize::Zeroize + ?Sized>(&'a mut T);
549
550impl<'a, T: zeroize::Zeroize + ?Sized> ClearOnDrop<'a, T> {
551    /// Borrow a workspace until this guard is dropped.
552    pub fn new(value: &'a mut T) -> Self {
553        Self(value)
554    }
555}
556impl<T: zeroize::Zeroize + ?Sized> core::ops::Deref for ClearOnDrop<'_, T> {
557    type Target = T;
558    fn deref(&self) -> &T {
559        self.0
560    }
561}
562impl<T: zeroize::Zeroize + ?Sized> core::ops::DerefMut for ClearOnDrop<'_, T> {
563    fn deref_mut(&mut self) -> &mut T {
564        self.0
565    }
566}
567impl<T: zeroize::Zeroize + ?Sized> Drop for ClearOnDrop<'_, T> {
568    fn drop(&mut self) {
569        self.0.zeroize();
570    }
571}
572
573#[cfg(test)]
574mod cleanup_tests {
575    extern crate std;
576    use super::ClearOnDrop;
577    #[test]
578    fn borrowed_workspace_cleared_on_return_and_unwind() {
579        let mut bytes = [0x5au8; 32];
580        {
581            let mut guard = ClearOnDrop::new(&mut bytes);
582            guard[0] = 1;
583        }
584        assert_eq!(bytes, [0; 32]);
585        bytes.fill(0xa5);
586        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
587            let _guard = ClearOnDrop::new(&mut bytes);
588            panic!("unwind cleanup");
589        }));
590        assert!(result.is_err());
591        assert_eq!(bytes, [0; 32]);
592    }
593}