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
use super::*;
use crate::{
common::{
share::{apply_vandermonde, make_vandermonde},
utils::deser_bounded_vec,
SecretSharingScheme,
},
honeybadger::{
robust_interpolate::robust_interpolate::{batch_recover_secret, RobustShare},
WrappedMessage,
},
};
use ark_ff::FftField;
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use futures::lock::Mutex;
use std::sync::Arc;
use std::{collections::HashMap, marker::PhantomData};
use stoffelnet::network_utils::Network;
use tokio::sync::mpsc::Sender;
use tracing::{debug, error, info, warn};
/// --------------------------BatchRecPub--------------------------
///
/// Goal: Publicly reconstruct t+1 secret-shared values [x₁, ..., x_{t+1}]
/// in a robust way, tolerating up to t faulty parties.
///
/// 1. Encode the secret shares into n public shares [y₁, ..., yₙ]
/// using a Vandermonde matrix.
///
/// 2. Each party sends its share yᵢ to all others (Round 1).
///
/// 3. Parties robustly interpolate the received y-values
/// to reconstruct the clear yᵢ, then broadcast them (Round 2).
///
/// 4. Using the reconstructed y-values, parties robustly
/// interpolate to recover the original secrets [x₁, ..., x_{t+1}].
#[derive(Clone, Debug)]
pub struct BatchReconNode<F: FftField> {
pub id: usize, // This node's unique identifier
pub n: usize, // Total number of nodes/shares
pub t: usize,
pub degree: usize,
pub store: Arc<Mutex<HashMap<SessionId, (usize, Arc<Mutex<BatchReconStore<F>>>)>>>, // Number of malicious parties
pub output_sender: Sender<SessionId>,
}
impl<F: FftField> BatchReconNode<F> {
/// Creates a new `Node` instance.
pub fn new(
id: usize,
n: usize,
t: usize,
degree: usize,
output_sender: Sender<SessionId>,
) -> Result<Self, BatchReconError> {
let store = Arc::new(Mutex::new(HashMap::new()));
Ok(Self {
id,
n,
t,
degree,
store,
output_sender,
})
}
pub async fn clear_entire_store(&self) {
let mut store = self.store.lock().await;
store.clear();
}
pub async fn clear_store(&self, session_id: SessionId) -> bool {
let mut store = self.store.lock().await;
store.remove(&session_id).is_some()
}
pub async fn store_len(&self) -> usize {
self.store.lock().await.len()
}
pub async fn get_store(&self, session_id: SessionId) -> Result<Vec<u8>, BatchReconError> {
let store = self.store.lock().await;
let (_, output_arc) = store.get(&session_id).ok_or_else(|| {
BatchReconError::InvalidInput("Session ID does not exist".to_string())
})?;
let store_lock = output_arc.lock().await;
if store_lock.secrets.is_none() {
return Err(BatchReconError::InvalidInput(
"Batch reconstruction has not terminated".to_string(),
));
}
Ok(store_lock.secrets.clone().unwrap())
}
/// Initiates the batch reconstruction protocol for a given node.
///
/// Each party computes its `y_j_share` for all `j` and sends it to party `P_j`.
pub async fn init_batch_reconstruct<N: Network>(
&self,
shares: &[RobustShare<F>], // this party's shares of x_0 to x_t
session_id: SessionId,
net: Arc<N>,
) -> Result<(), BatchReconError> {
if shares.len() < self.degree + 1 {
return Err(BatchReconError::InvalidInput(
"too little shares to start batch reconstruct".to_string(),
));
}
let vandermonde = make_vandermonde::<F>(self.n, self.degree)?;
let y_shares = apply_vandermonde(&vandermonde, &shares[..(self.degree + 1)])?;
info!(
id = self.id,
"initialized batch reconstruction with Vandermonde transform"
);
for (j, y_j_share) in y_shares.into_iter().enumerate() {
info!(from = self.id, to = j, "Sending y_j shares ");
let mut payload = Vec::new();
y_j_share.share[0].serialize_compressed(&mut payload)?;
let msg = BatchReconMsg::new(self.id, session_id, BatchReconMsgType::Eval, payload);
//Wrap the msg in global enum
let wrapped = WrappedMessage::BatchRecon(msg);
//Send share y_j to each Party j
let encoded_msg =
bincode::serialize(&wrapped).map_err(BatchReconError::SerializationError)?;
let _ = net.send(j, &encoded_msg).await?;
}
Ok(())
}
/// Initiates multiple independent batch reconstructions under one protocol session.
///
/// `shares` is interpreted as consecutive chunks of `degree + 1` secrets. Each chunk uses the
/// same Vandermonde transform as `init_batch_reconstruct`, but all evaluations for a recipient
/// are sent in a single message and all reveals are broadcast in a single message.
pub async fn init_batch_reconstruct_many<N: Network>(
&self,
shares: &[RobustShare<F>],
session_id: SessionId,
net: Arc<N>,
) -> Result<(), BatchReconError> {
let batch_width = self.degree + 1;
if shares.is_empty() || shares.len() % batch_width != 0 {
return Err(BatchReconError::InvalidInput(
"batched shares must be a non-empty multiple of degree + 1".to_string(),
));
}
let vandermonde = make_vandermonde::<F>(self.n, self.degree)?;
let mut y_shares_by_recipient = vec![Vec::new(); self.n];
for chunk in shares.chunks_exact(batch_width) {
let y_shares = apply_vandermonde(&vandermonde, chunk)?;
for (recipient, y_j_share) in y_shares.into_iter().enumerate() {
y_shares_by_recipient[recipient].push(y_j_share.share[0]);
}
}
info!(
id = self.id,
groups = shares.len() / batch_width,
"initialized batched batch reconstruction with Vandermonde transform"
);
for (j, values) in y_shares_by_recipient.into_iter().enumerate() {
let mut payload = Vec::new();
values.serialize_compressed(&mut payload)?;
let msg =
BatchReconMsg::new(self.id, session_id, BatchReconMsgType::EvalBatch, payload);
let wrapped = WrappedMessage::BatchRecon(msg);
let encoded_msg =
bincode::serialize(&wrapped).map_err(BatchReconError::SerializationError)?;
let _ = net.send(j, &encoded_msg).await?;
}
Ok(())
}
/// Handles incoming `Msg`s for the batch reconstruction protocol.
///
/// This function processes `Eval` messages (first round) and `Reveal` messages (second round)
/// to collectively reconstruct the original secrets.
pub async fn batch_recon_handler<N: Network>(
&mut self,
msg: BatchReconMsg,
net: Arc<N>,
) -> Result<(), BatchReconError> {
match msg.msg_type {
BatchReconMsgType::Eval => {
debug!(
self_id = self.id,
from = msg.sender_id,
"Received Eval message"
);
let sender_id = msg.sender_id;
let val = F::deserialize_compressed(msg.payload.as_slice())
.map_err(|e| BatchReconError::ArkDeserialization(e))?;
// Lock the session store to update the session state.
let Some(session_store) =
self.get_or_create_store(msg.session_id, sender_id).await?
else {
return Ok(()); // late message for an already-terminated session — dropped
};
// Lock the session-specific store to access or update the session state.
let mut store = session_store.lock().await;
// Store the received evaluation share if it's from a new sender.
if !store.evals_received.iter().any(|s| s.id == sender_id) {
store
.evals_received
.push(RobustShare::new(val, sender_id, self.degree));
}
// Check if we have enough evaluation shares and haven't already computed our `y_j`.
if store.evals_received.len() >= self.degree + self.t + 1 && store.y_j.is_none() {
info!(
self_id = self.id,
"Enough Evals collected, interpolating y_j"
);
// Attempt to interpolate the polynomial and get our specific `y_j` value.
match RobustShare::recover_secret(&store.evals_received, self.n, self.t) {
Ok((_, value)) => {
store.y_j = Some(RobustShare {
share: [value],
id: self.id,
degree: self.degree,
_sharetype: PhantomData,
});
drop(store);
info!(node = self.id, "Broadcasting y_j value: {:?}", value);
let mut payload = Vec::new();
value
.serialize_compressed(&mut payload)
.map_err(|e| BatchReconError::ArkSerialization(e))?;
let new_msg = BatchReconMsg::new(
self.id,
msg.session_id,
BatchReconMsgType::Reveal,
payload,
);
//Wrap the msg in global enum
let wrapped = WrappedMessage::BatchRecon(new_msg);
// Broadcast our computed `y_j` to all other parties.
let encoded = bincode::serialize(&wrapped)
.map_err(BatchReconError::SerializationError)?;
let _ = net
.broadcast(&encoded)
.await
.map_err(|e| BatchReconError::NetworkError(e))?;
}
Err(e) => {
warn!(self_id = self.id, "Interpolation of y_j failed: {:?}", e);
return Err(BatchReconError::InterpolateError(e));
}
}
}
Ok(())
}
BatchReconMsgType::Reveal => {
debug!(
self_id = self.id,
from = msg.sender_id,
"Received Reveal message"
);
let sender_id = msg.sender_id;
let y_j = F::deserialize_compressed(msg.payload.as_slice())
.map_err(|e| BatchReconError::ArkDeserialization(e))?;
// Lock the session store to update the session state.
let Some(session_store) =
self.get_or_create_store(msg.session_id, sender_id).await?
else {
return Ok(()); // late message for an already-terminated session — dropped
};
// Lock the session-specific store to access or update the session state.
let mut store = session_store.lock().await;
// Store the received revealed `y_j` value if it's from a new sender.
if !store.reveals_received.iter().any(|s| s.id == sender_id) {
store
.reveals_received
.push(RobustShare::new(y_j, sender_id, self.degree));
}
// Check if we have enough revealed `y_j` values and haven't already reconstructed the secrets.
if store.reveals_received.len() >= self.degree + self.t + 1
&& store.secrets.is_none()
{
info!(
self_id = self.id,
"Enough Reveals collected, interpolating secrets"
);
// Attempt to interpolate the polynomial whose coefficients are the original secrets.
match RobustShare::recover_secret(&store.reveals_received, self.n, self.t) {
Ok((poly, _)) => {
let mut result = poly;
// Resize the coefficient vector to `t + 1` to get all secrets.
result.resize(self.degree + 1, F::zero());
let mut bytes_message = Vec::new();
result.serialize_compressed(&mut bytes_message)?;
store.secrets = Some(bytes_message);
drop(store);
info!(self_id = self.id, "Secrets successfully reconstructed");
self.output_sender
.send(msg.session_id)
.await
.map_err(|_| BatchReconError::SendError)?;
}
Err(e) => {
error!(
self_id = self.id, error = ?e,
"Final secrets interpolation failed "
);
return Err(BatchReconError::InterpolateError(e));
}
}
}
Ok(())
}
BatchReconMsgType::EvalBatch => {
debug!(
self_id = self.id,
from = msg.sender_id,
"Received EvalBatch message"
);
let sender_id = msg.sender_id;
let values = deser_bounded_vec(&mut msg.payload.as_slice(), msg.payload.len())
.map_err(BatchReconError::ArkDeserialization)?;
if values.is_empty() {
return Err(BatchReconError::InvalidInput(
"empty EvalBatch payload".to_string(),
));
}
let Some(session_store) =
self.get_or_create_store(msg.session_id, sender_id).await?
else {
return Ok(()); // late message for an already-terminated session — dropped
};
let mut store = session_store.lock().await;
if let Some((_, existing)) = store.batch_evals_received.first() {
if existing.len() != values.len() {
return Err(BatchReconError::InvalidInput(
"inconsistent EvalBatch width".to_string(),
));
}
}
if !store
.batch_evals_received
.iter()
.any(|(id, _)| *id == sender_id)
{
store.batch_evals_received.push((sender_id, values));
}
if store.batch_evals_received.len() >= self.degree + self.t + 1
&& store.y_j_batch.is_none()
{
// Decode all chunks in one shot: the Lagrange basis depends only on the sender
// ids (identical across every chunk), so build it once and reuse instead of
// rebuilding `A(x)` and the per-point divisions per chunk. Each chunk is still
// verified against all evaluations and falls back to robust `recover_secret`
// (OEC/Gao) on disagreement, so `t`-fault tolerance is unchanged.
//
// Borrow the received evaluations directly (no clone): `batch_recover_secret`
// only reads them through internal `&Vec<F>` references, and we hold the session
// lock for the whole call. The prior `.clone()` deep-copied every sender's
// evaluation vector on the threshold message of every round.
let decoded = batch_recover_secret(
&store.batch_evals_received,
self.n,
self.degree,
self.t,
)?;
// The opened value per chunk is the constant term P(0).
let y_j_values: Vec<F> = decoded.into_iter().map(|coeffs| coeffs[0]).collect();
store.y_j_batch = Some(y_j_values.clone());
drop(store);
let mut payload = Vec::new();
y_j_values.serialize_compressed(&mut payload)?;
let new_msg = BatchReconMsg::new(
self.id,
msg.session_id,
BatchReconMsgType::RevealBatch,
payload,
);
let wrapped = WrappedMessage::BatchRecon(new_msg);
let encoded = bincode::serialize(&wrapped)
.map_err(BatchReconError::SerializationError)?;
let _ = net.broadcast(&encoded).await?;
}
Ok(())
}
BatchReconMsgType::RevealBatch => {
debug!(
self_id = self.id,
from = msg.sender_id,
"Received RevealBatch message"
);
let sender_id = msg.sender_id;
let values = Vec::<F>::deserialize_compressed(msg.payload.as_slice())
.map_err(BatchReconError::ArkDeserialization)?;
if values.is_empty() {
return Err(BatchReconError::InvalidInput(
"empty RevealBatch payload".to_string(),
));
}
let Some(session_store) =
self.get_or_create_store(msg.session_id, sender_id).await?
else {
return Ok(()); // late message for an already-terminated session — dropped
};
let mut store = session_store.lock().await;
if let Some((_, existing)) = store.batch_reveals_received.first() {
if existing.len() != values.len() {
return Err(BatchReconError::InvalidInput(
"inconsistent RevealBatch width".to_string(),
));
}
}
if !store
.batch_reveals_received
.iter()
.any(|(id, _)| *id == sender_id)
{
store.batch_reveals_received.push((sender_id, values));
}
if store.batch_reveals_received.len() >= self.degree + self.t + 1
&& store.secrets.is_none()
{
// Batched decode (see the EvalBatch arm): one Lagrange basis for all chunks,
// verified per chunk with robust `recover_secret` (OEC/Gao) fallback. Borrow the
// received reveals directly (no clone) — same rationale as the EvalBatch arm.
let decoded = batch_recover_secret(
&store.batch_reveals_received,
self.n,
self.degree,
self.t,
)?;
let mut result = Vec::with_capacity(decoded.len() * (self.degree + 1));
for coeffs in decoded {
// `batch_recover_secret` already resizes each chunk to `degree + 1`.
result.extend(coeffs);
}
let mut bytes_message = Vec::new();
result.serialize_compressed(&mut bytes_message)?;
store.secrets = Some(bytes_message);
drop(store);
self.output_sender
.send(msg.session_id)
.await
.map_err(|_| BatchReconError::SendError)?;
}
Ok(())
}
}
}
pub async fn process<N: Network>(
&mut self,
msg: BatchReconMsg,
net: Arc<N>,
) -> Result<(), BatchReconError> {
self.batch_recon_handler(msg, net).await?;
Ok(())
}
pub async fn get_or_create_store(
&self,
session_id: SessionId,
sender_id: usize,
) -> Result<Option<Arc<Mutex<BatchReconStore<F>>>>, BatchReconError> {
let store_lock = {
let mut storage = self.store.lock().await;
// TODO: restore session limits
// if !storage.contains_key(&session_id) {
// if storage.len() >= MAX_BATCH_RECON_SESSIONS {
// return Err(BatchReconError::InvalidInput(
// "Session limit reached".into(),
// ));
// }
// let per_peer_limit = MAX_BATCH_RECON_SESSIONS / self.n;
// let peer_count = storage.values().filter(|(id, _)| *id == sender_id).count();
// if peer_count >= per_peer_limit {
// return Err(BatchReconError::InvalidInput(
// "Per-peer session limit reached".into(),
// ));
// }
// }
storage
.entry(session_id)
.or_insert_with(|| (sender_id, Arc::new(Mutex::new(BatchReconStore::empty()))))
.1
.clone()
};
{
let store_guard = store_lock.lock().await;
if store_guard.secrets.is_some() {
// Session already terminated: this is a late/duplicate message. Drop it — the
// reconstructed secrets are final, so a redundant message cannot change the result.
// Restores liveness that the hard-error path removed; does not alter reconstruction
// correctness or t-fault tolerance. (Wrapping/ID-reuse replay is a separate concern.)
debug!(
self_id = self.id,
?session_id,
"dropping late message for already-terminated batch-recon session"
);
return Ok(None);
}
}
Ok(Some(store_lock))
}
}