-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathmulti_message_id.rs
More file actions
387 lines (354 loc) · 12.8 KB
/
multi_message_id.rs
File metadata and controls
387 lines (354 loc) · 12.8 KB
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
#![cfg(feature = "multi-message-id")]
use std::{
collections::HashMap,
fs::File,
io::{stdin, stdout, Read, Write},
path::{Path, PathBuf},
};
use clap::{Parser, Subcommand};
use rln::prelude::{
hash_to_field_le, keygen, poseidon_hash, recover_id_secret, Fr, IdSecret, PmtreeConfigBuilder,
RLNProofValues, RLNWitnessInput, DEFAULT_MAX_OUT, DEFAULT_TREE_DEPTH, RLN,
};
use zerokit_utils::pm_tree::Mode;
const MESSAGE_LIMIT: u32 = 4;
const TREE_DEPTH: usize = DEFAULT_TREE_DEPTH;
const MAX_OUT: usize = DEFAULT_MAX_OUT;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
List,
Register,
Send {
#[arg(short, long)]
user_index: usize,
#[arg(short, long)]
message_ids: String,
#[arg(long)]
selector: String,
#[arg(short, long)]
signal: String,
},
Clear,
Exit,
}
#[derive(Debug, Clone)]
struct Identity {
identity_secret: IdSecret,
id_commitment: Fr,
}
impl Identity {
fn new() -> Self {
let (identity_secret, id_commitment) = keygen();
Identity {
identity_secret,
id_commitment,
}
}
}
struct RLNSystem {
rln: RLN,
used_nullifiers: HashMap<Fr, RLNProofValues>,
local_identities: HashMap<usize, Identity>,
}
impl RLNSystem {
fn new() -> Result<Self> {
let mut resources: Vec<Vec<u8>> = Vec::new();
let resources_path: PathBuf =
format!("../rln/resources/tree_depth_{TREE_DEPTH}/multi_message_id/max_out_4").into();
let filenames = ["rln_final.arkzkey", "graph.bin"];
for filename in filenames {
let fullpath = resources_path.join(Path::new(filename));
let mut file = File::open(&fullpath)?;
let metadata = std::fs::metadata(&fullpath)?;
let mut output_buffer = vec![0; metadata.len() as usize];
file.read_exact(&mut output_buffer)?;
resources.push(output_buffer);
}
let tree_config = PmtreeConfigBuilder::new()
.path("./database")
.temporary(false)
.cache_capacity(1073741824)
.flush_every_ms(500)
.mode(Mode::HighThroughput)
.use_compression(false)
.build()?;
let rln = RLN::new_with_params(
TREE_DEPTH,
MAX_OUT,
resources[0].clone(),
resources[1].clone(),
tree_config,
)?;
println!("RLN multi-message-id instance initialized successfully");
Ok(RLNSystem {
rln,
used_nullifiers: HashMap::new(),
local_identities: HashMap::new(),
})
}
fn list_users(&self) {
if self.local_identities.is_empty() {
println!("No users registered yet.");
return;
}
println!("Registered users:");
for (index, identity) in &self.local_identities {
println!("User: {index}");
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
println!();
}
}
fn register_user(&mut self) -> Result<usize> {
let index = self.rln.leaves_set();
let identity = Identity::new();
let rate_commitment = poseidon_hash(&[identity.id_commitment, Fr::from(MESSAGE_LIMIT)]);
match self.rln.set_next_leaf(rate_commitment) {
Ok(_) => {
println!("Registered user: {index}");
println!("+ Identity secret: {}", *identity.identity_secret);
println!("+ Identity commitment: {}", identity.id_commitment);
self.local_identities.insert(index, identity);
}
Err(_) => {
println!("Maximum user limit reached: 2^{TREE_DEPTH}");
}
};
Ok(index)
}
fn parse_message_ids(&self, input: &str) -> Result<Vec<Fr>> {
let ids: Vec<Fr> = input
.split(',')
.map(|s| {
let id: u32 = s.trim().parse()?;
Ok(Fr::from(id))
})
.collect::<Result<Vec<Fr>>>()?;
if ids.len() != self.rln.max_out() {
return Err(format!(
"expected {} message IDs, got {}",
self.rln.max_out(),
ids.len()
)
.into());
}
Ok(ids)
}
fn parse_selector(&self, input: &str) -> Result<Vec<bool>> {
let selector: Vec<bool> = input
.split(',')
.map(|s| match s.trim() {
"true" | "1" => Ok(true),
"false" | "0" => Ok(false),
other => Err(format!("invalid selector value: '{other}'")),
})
.collect::<std::result::Result<Vec<bool>, String>>()?;
if selector.len() != self.rln.max_out() {
return Err(format!(
"expected {} selector values, got {}",
self.rln.max_out(),
selector.len()
)
.into());
}
Ok(selector)
}
fn generate_and_verify_proof(
&mut self,
user_index: usize,
message_ids: Vec<Fr>,
selector_used: Vec<bool>,
signal: &str,
external_nullifier: Fr,
) -> Result<RLNProofValues> {
let identity = match self.local_identities.get(&user_index) {
Some(identity) => identity,
None => return Err(format!("User {user_index} not found").into()),
};
let (path_elements, identity_path_index) = self.rln.get_merkle_proof(user_index)?;
let x = hash_to_field_le(signal.as_bytes());
let witness = RLNWitnessInput::new(
identity.identity_secret.clone(),
Fr::from(MESSAGE_LIMIT),
message_ids.clone(),
path_elements,
identity_path_index,
x,
external_nullifier,
selector_used.clone(),
)?;
let (proof, proof_values) = self.rln.generate_rln_proof(&witness)?;
let active_count = selector_used.iter().filter(|&&s| s).count();
println!("Proof generated successfully:");
println!("+ User: {user_index}");
println!(
"+ Active message slots: {active_count}/{}",
self.rln.max_out()
);
println!("+ Signal: {signal}");
let verified = self.rln.verify_rln_proof(&proof, &proof_values, &x)?;
if verified {
println!("Proof verified successfully");
}
Ok(proof_values)
}
fn check_nullifier(&mut self, proof_values: RLNProofValues) -> Result<()> {
let nullifiers: Vec<Fr> = proof_values.nullifiers().to_vec();
let selector: Vec<bool> = proof_values.selector_used().to_vec();
for (i, (nullifier, active)) in nullifiers.iter().zip(selector.iter()).enumerate() {
if !active {
continue;
}
if let Some(previous_proof_values) = self.used_nullifiers.get(nullifier) {
self.handle_duplicate_nullifier(previous_proof_values.clone(), proof_values, i)?;
return Ok(());
}
}
for (nullifier, active) in nullifiers.iter().zip(selector.iter()) {
if *active {
self.used_nullifiers
.insert(*nullifier, proof_values.clone());
}
}
println!("Message verified and accepted");
Ok(())
}
fn handle_duplicate_nullifier(
&mut self,
previous_proof_values: RLNProofValues,
current_proof_values: RLNProofValues,
duplicated_slot: usize,
) -> Result<()> {
match recover_id_secret(&previous_proof_values, ¤t_proof_values) {
Ok(leaked_identity_secret) => {
if let Some((user_index, identity)) = self
.local_identities
.iter()
.find(|(_, identity)| identity.identity_secret == leaked_identity_secret)
.map(|(index, identity)| (*index, identity))
{
let real_identity_secret = identity.identity_secret.clone();
if leaked_identity_secret != real_identity_secret {
Err("Identity secret mismatch: leaked_identity_secret != real_identity_secret".into())
} else {
println!(
"DUPLICATE nullifier detected at slot {}! Reveal identity secret: {}",
duplicated_slot, *leaked_identity_secret
);
self.local_identities.remove(&user_index);
self.rln.delete_leaf(user_index)?;
println!("User {user_index} has been SLASHED");
Ok(())
}
} else {
Err("user identity secret ******** not found".into())
}
}
Err(err) => Err(format!("Failed to recover identity secret: {err}").into()),
}
}
}
fn main() -> Result<()> {
println!("Initializing RLN multi-message-id instance...");
print!("\x1B[2J\x1B[1;1H");
let mut rln_system = RLNSystem::new()?;
let rln_epoch = hash_to_field_le(b"epoch");
let rln_identifier = hash_to_field_le(b"rln-identifier");
let external_nullifier = poseidon_hash(&[rln_epoch, rln_identifier]);
println!("RLN Multi-Message-ID Example:");
println!("Message Limit: {MESSAGE_LIMIT}");
println!("Message Slots: {} - MAX_OUT", rln_system.rln.max_out());
println!("----------------------------------");
println!();
show_commands();
loop {
print!("\n> ");
stdout().flush()?;
let mut input = String::new();
stdin().read_line(&mut input)?;
let trimmed = input.trim();
let args = std::iter::once("").chain(trimmed.split_whitespace());
match Cli::try_parse_from(args) {
Ok(cli) => match cli.command {
Commands::List => {
rln_system.list_users();
}
Commands::Register => {
rln_system.register_user()?;
}
Commands::Send {
user_index,
message_ids,
selector,
signal,
} => {
let message_ids = match rln_system.parse_message_ids(&message_ids) {
Ok(ids) => ids,
Err(err) => {
println!("Invalid message_ids: {err}");
continue;
}
};
let selector_used = match rln_system.parse_selector(&selector) {
Ok(sel) => sel,
Err(err) => {
println!("Invalid selector: {err}");
continue;
}
};
match rln_system.generate_and_verify_proof(
user_index,
message_ids,
selector_used,
&signal,
external_nullifier,
) {
Ok(proof_values) => {
if let Err(err) = rln_system.check_nullifier(proof_values) {
println!("Check nullifier error: {err}");
};
}
Err(err) => {
println!("Proof generation error: {err}");
}
}
}
Commands::Clear => {
print!("\x1B[2J\x1B[1;1H");
show_commands();
}
Commands::Exit => {
break;
}
},
Err(err) => {
eprintln!("Command error: {err}");
}
}
}
Ok(())
}
fn show_commands() {
println!("Available commands:");
println!(
" list - List registered users"
);
println!(
" register - Register a new user"
);
println!(" send -u <index> -m <message_ids> --selector <bools> -s <signal> - Send a message with proof");
println!(" (example: send -u 0 -m 0,1,2,3 --selector 1,1,0,0 -s \"hello\")");
println!(
" clear - Clear the screen"
);
println!(
" exit - Exit the program"
);
}