Debian Codegraph @

ML-DSA/accumulated/src/main.rs

raw symbols SCIP
1 use clap::{Parser, ValueEnum};
2 use libcrux_ml_dsa::{ml_dsa_44, ml_dsa_65, ml_dsa_87};
3 use sha3::Shake128;
4 use sha3::digest::{ExtendableOutput, Update, XofReader};
5 use std::io::Write;
6 use std::time::Instant;
7 use rayon::prelude::*;
8
9 #[derive(Parser)]
10 #[command(name = "ml-dsa-accumulated")]
11 #[command(about = "Generate accumulated test vectors for ML-DSA", long_about = None)]
12 struct Cli {
13 /// Number of iterations
14 #[arg(short, long)]
15 iterations: usize,
16
17 /// ML-DSA parameter set
18 #[arg(short, long, value_enum)]
19 params: MLDSAParams,
20 }
21
22 #[derive(Clone, Copy, Debug, ValueEnum)]
23 enum MLDSAParams {
24 #[value(name = "44")]
25 MLDSA44,
26 #[value(name = "65")]
27 MLDSA65,
28 #[value(name = "87")]
29 MLDSA87,
30 }
31
32 fn main() {
33 let cli = Cli::parse();
34
35 // Initialize SHAKE128 for input generation
36 let mut shake_source = Shake128::default().finalize_xof();
37
38 // Initialize SHAKE128 as accumulator
39 let mut accumulator = Shake128::default();
40
41 println!("Generating accumulated test vectors for ML-DSA-{}",
42 match cli.params {
43 MLDSAParams::MLDSA44 => "44",
44 MLDSAParams::MLDSA65 => "65",
45 MLDSAParams::MLDSA87 => "87",
46 });
47 println!("Iterations: {}", cli.iterations);
48
49 let start_time = Instant::now();
50 let mut last_checkpoint = start_time;
51 let mut processed = 0;
52
53 const BATCH_SIZE: usize = 20;
54
55 while processed < cli.iterations {
56 // Determine how many to process in this batch
57 let batch_end = std::cmp::min(processed + BATCH_SIZE, cli.iterations);
58 let batch_count = batch_end - processed;
59
60 // Read seeds for this batch
61 let mut seeds = Vec::with_capacity(batch_count);
62 for _ in 0..batch_count {
63 let mut seed = [0u8; 32];
64 shake_source.read(&mut seed);
65 seeds.push(seed);
66 }
67
68 // Process batch in parallel and collect results in order
69 let results: Vec<(Vec<u8>, Vec<u8>)> = seeds
70 .par_iter()
71 .map(|&seed| process_iteration_collect(seed, cli.params))
72 .collect();
73
74 // Accumulate results in order
75 for (public_key, signature) in results {
76 accumulator.update(&public_key);
77 accumulator.update(&signature);
78 }
79
80 processed = batch_end;
81
82 // Update progress display
83 if processed % 10000 == 0 && processed > 0 {
84 let now = Instant::now();
85 let elapsed_since_checkpoint = now - last_checkpoint;
86 let total_elapsed = now - start_time;
87
88 // Calculate rate and estimate remaining time
89 let iterations_remaining = cli.iterations - processed;
90 let iterations_per_second = 10000.0 / elapsed_since_checkpoint.as_secs_f64();
91 let estimated_seconds_remaining = iterations_remaining as f64 / iterations_per_second;
92
93 let percentage = (processed as f64 / cli.iterations as f64) * 100.0;
94
95 // Clear line and print progress on single line
96 print!("\r{:120}", " "); // Clear with spaces
97 print!("\rProgress: {:.1}% ({}/{}) | Elapsed: {} | Rate: {:.0} it/s | ETA: {}",
98 percentage, processed, cli.iterations,
99 format_duration(total_elapsed.as_secs()),
100 iterations_per_second,
101 format_duration(estimated_seconds_remaining as u64));
102 std::io::stdout().flush().unwrap();
103
104 last_checkpoint = now;
105 }
106 }
107
108 // Get final hash from SHAKE128 (32 bytes)
109 let mut result = [0u8; 32];
110 let mut accumulator_reader = accumulator.finalize_xof();
111 accumulator_reader.read(&mut result);
112
113 // Clear the progress line and print completion
114 print!("\r{:120}", " "); // Clear line
115 let final_duration = start_time.elapsed();
116 println!("\rCompleted {} iterations in {}", cli.iterations, format_duration(final_duration.as_secs()));
117 println!("Accumulated hash: {}", hex::encode(result));
118 }
119
120 fn format_duration(seconds: u64) -> String {
121 let hours = seconds / 3600;
122 let minutes = (seconds % 3600) / 60;
123 let secs = seconds % 60;
124
125 if hours > 0 {
126 format!("{}h {}m {}s", hours, minutes, secs)
127 } else if minutes > 0 {
128 format!("{}m {}s", minutes, secs)
129 } else {
130 format!("{}s", secs)
131 }
132 }
133
134 fn process_iteration_collect(
135 seed: [u8; 32],
136 params: MLDSAParams,
137 ) -> (Vec<u8>, Vec<u8>) {
138 // Sign empty message deterministically
139 let empty_message = &[];
140 let context = &[]; // Empty context
141 let randomness = [0u8; 32];
142
143 match params {
144 MLDSAParams::MLDSA44 => {
145 let kp = ml_dsa_44::generate_key_pair(seed);
146 let signature = ml_dsa_44::sign(&kp.signing_key, empty_message, context, randomness).unwrap();
147 (kp.verification_key.as_ref().to_vec(), signature.as_ref().to_vec())
148 }
149 MLDSAParams::MLDSA65 => {
150 let kp = ml_dsa_65::generate_key_pair(seed);
151 let signature = ml_dsa_65::sign(&kp.signing_key, empty_message, context, randomness).unwrap();
152 (kp.verification_key.as_ref().to_vec(), signature.as_ref().to_vec())
153 }
154 MLDSAParams::MLDSA87 => {
155 let kp = ml_dsa_87::generate_key_pair(seed);
156 let signature = ml_dsa_87::sign(&kp.signing_key, empty_message, context, randomness).unwrap();
157 (kp.verification_key.as_ref().to_vec(), signature.as_ref().to_vec())
158 }
159 }
160 }