1#![no_std]
2
3use core::fmt;
14
15#[doc(hidden)]
17pub mod codec;
18
19#[doc(hidden)]
21pub mod mq;
22
23#[doc(hidden)]
25pub mod shake;
26
27#[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
31#[doc(hidden)]
32pub mod mq_avx2;
33
34pub use rand_core::{CryptoRng, Error as RngError, RngCore};
36
37pub const FN_DSA_LOGN_512: u32 = 9;
39
40pub const FN_DSA_LOGN_1024: u32 = 10;
42
43#[derive(Copy, Clone, Debug, Eq, PartialEq)]
45pub enum LogNError {
46 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
60pub 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
80pub const SIGN_KEY_SIZE_512: usize = sign_key_size_inner(FN_DSA_LOGN_512);
82
83pub const SIGN_KEY_SIZE_1024: usize = sign_key_size_inner(FN_DSA_LOGN_1024);
85
86pub 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
100pub const VRFY_KEY_SIZE_512: usize = vrfy_key_size_inner(FN_DSA_LOGN_512);
102
103pub const VRFY_KEY_SIZE_1024: usize = vrfy_key_size_inner(FN_DSA_LOGN_1024);
105
106pub 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
125pub const SIGNATURE_SIZE_512: usize = signature_size_inner(FN_DSA_LOGN_512);
127
128pub const SIGNATURE_SIZE_1024: usize = signature_size_inner(FN_DSA_LOGN_1024);
130
131pub const fn signature_size(logn: u32) -> Result<usize, LogNError> {
134 if let Err(err) = check_logn(logn) {
145 Err(err)
146 } else {
147 Ok(signature_size_inner(logn))
148 }
149}
150
151#[derive(Copy, Clone, Debug, Eq, PartialEq)]
153pub enum FalconProfile {
154 PqClean,
157
158 TidecoinStrict,
161
162 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
179pub const FALCON_NONCE_LEN: usize = 40;
181
182pub const TIDECOIN_LEGACY_FALCON512_SIG_BODY_MAX: usize = 647;
184
185pub const TIDECOIN_LEGACY_FALCON512_SIG_MAX: usize =
188 1 + FALCON_NONCE_LEN + TIDECOIN_LEGACY_FALCON512_SIG_BODY_MAX;
189
190#[derive(Copy, Clone, Debug, Eq, PartialEq)]
196pub struct HashIdentifier<'a>(&'a [u8]);
197
198#[derive(Copy, Clone, Debug, Eq, PartialEq)]
200pub enum HashIdentifierError {
201 Empty,
203
204 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 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 pub const fn as_bytes(&self) -> &'a [u8] {
233 self.0
234 }
235
236 pub const fn is_raw(&self) -> bool {
238 self.0.len() == 1 && self.0[0] == 0x00
239 }
240}
241
242pub const HASH_ID_RAW: HashIdentifier = HashIdentifier(&[0x00]);
248
249pub const HASH_ID_SHA256: HashIdentifier = HashIdentifier(&[
251 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
252]);
253
254pub const HASH_ID_SHA384: HashIdentifier = HashIdentifier(&[
256 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
257]);
258
259pub const HASH_ID_SHA512: HashIdentifier = HashIdentifier(&[
261 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
262]);
263
264pub const HASH_ID_SHA512_256: HashIdentifier = HashIdentifier(&[
266 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06,
267]);
268
269pub const HASH_ID_SHA3_256: HashIdentifier = HashIdentifier(&[
271 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08,
272]);
273
274pub const HASH_ID_SHA3_384: HashIdentifier = HashIdentifier(&[
276 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x09,
277]);
278
279pub const HASH_ID_SHA3_512: HashIdentifier = HashIdentifier(&[
281 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0A,
282]);
283
284pub const HASH_ID_SHAKE128: HashIdentifier = HashIdentifier(&[
286 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0B,
287]);
288
289pub const HASH_ID_SHAKE256: HashIdentifier = HashIdentifier(&[
291 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0C,
292]);
293
294#[derive(Copy, Clone, Debug, Eq, PartialEq)]
298pub struct DomainContext<'a>(&'a [u8]);
299
300#[derive(Copy, Clone, Debug, Eq, PartialEq)]
302pub enum DomainContextError {
303 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 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 pub const fn empty() -> Self {
331 Self(b"")
332 }
333
334 pub const fn as_bytes(&self) -> &'a [u8] {
336 self.0
337 }
338
339 pub const fn is_empty(&self) -> bool {
341 self.0.is_empty()
342 }
343
344 pub const fn len(&self) -> usize {
346 self.0.len()
347 }
348}
349
350pub const DOMAIN_NONE: DomainContext = DomainContext::empty();
352
353#[derive(Copy, Clone, Debug, Eq, PartialEq)]
355pub enum HashToPointError {
356 InvalidNonceLength { actual: usize },
358
359 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
377pub 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
413pub 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 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
499pub trait PRNG: Copy + Clone + zeroize::Zeroize {
513 fn new(seed: &[u8]) -> Self;
515 fn next_u8(&mut self) -> u8;
517 fn next_u16(&mut self) -> u16;
519 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#[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#[doc(hidden)]
548pub struct ClearOnDrop<'a, T: zeroize::Zeroize + ?Sized>(&'a mut T);
549
550impl<'a, T: zeroize::Zeroize + ?Sized> ClearOnDrop<'a, T> {
551 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}