stoffel-vm 0.1.3

Register-based virtual machine runtime and MPC execution engine for Stoffel programs
Documentation
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
use super::HoneyBadgerMpcEngine;
use crate::net::curve::SupportedMpcField;
use crate::net::mpc_engine::MpcEngine;
use crate::net::open_registry::{ExpOpenRegistryKind, ExpOpenRequest};
use ark_ec::{CurveGroup, PrimeGroup};
use ark_poly::{EvaluationDomain, GeneralEvaluationDomain};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use std::any::TypeId;
use std::time::Instant;
use stoffel_vm_types::core_types::{ClearShareValue, ShareData, ShareType};
use stoffelmpc_mpc::common::types::fixed::{
    ClearFixedPoint, FixedPointPrecision, SecretFixedPoint,
};
use stoffelmpc_mpc::common::{MPCProtocol, MPCTypeOps, SecretSharingScheme};
use stoffelmpc_mpc::honeybadger::robust_interpolate::robust_interpolate::RobustShare;

/// Env var overriding how many secret-pair multiply operands are fed to a
/// single HoneyBadger `mul()` session. See [`max_honeybadger_mul_pairs_per_session`].
const STOFFEL_HB_MUL_MAX_PAIRS_PER_SESSION_ENV: &str = "STOFFEL_HB_MUL_MAX_PAIRS_PER_SESSION";

/// Default multiplier on `(threshold + 1)` for the pairs fed to one `mul()`
/// session. Matches `mpc-protocols`' own per-session deserialization bound
/// (`128 * (t+1)`), so the default stays within what the protocol already
/// supports without a change. See [`max_honeybadger_mul_pairs_per_session`].
const DEFAULT_MAX_HONEYBADGER_MUL_BATCH_RECON_CHUNKS: usize = 128;

/// Maximum secret-pair multiply operands fed to a single HoneyBadger `mul()`
/// session.
///
/// `batch_multiply_share_async` calls `node.mul()` once per chunk of this size
/// and *awaits each call before starting the next*, so each chunk is a
/// sequential communication round. Raising this packs more same-depth
/// multiplications into one round and directly cuts the round count for wide
/// depth-levels (e.g. a layer with 144 independent muls is 1 round at the
/// default `256` but 3 rounds at a cap of `64`).
///
/// The protocol itself imposes no fixed width here: `batch_recon` packs any
/// number of `(t+1)`-groups into a single send + broadcast, and `mpc-protocols`'s
/// own `node.mul` further chunks into independent sessions whose rounds overlap.
/// The only hard ceiling is the deserialization bound on one opened-values
/// message, `128 * (t+1)` in `mpc-protocols::honeybadger::max_mul_pairs_per_session`.
/// The default matches that bound, so it is the highest value that needs no
/// protocol change; going beyond `128*(t+1)` requires raising that mpc-protocols
/// cap (and the matching `deser_bounded_vec` bound). Measured on the AES-128
/// circuit (t=1): raising the cap `64 -> 256` cut online rounds 702 -> 426
/// (−39%) and online time ~1.11s -> ~0.96s with identical NIST output.
///
/// The `(t+1)` factor only keeps the count a clean multiple so there is no RBC
/// remainder; an explicit override (below) is used as-is.
pub(crate) fn max_honeybadger_mul_pairs_per_session(threshold: usize) -> usize {
    let from_env = std::env::var(STOFFEL_HB_MUL_MAX_PAIRS_PER_SESSION_ENV)
        .ok()
        .and_then(|raw| raw.parse::<usize>().ok().map(|v| v.max(1)));
    from_env.unwrap_or_else(|| max_honeybadger_mul_pairs_per_session_with(threshold, None))
}

/// Pure (env-free) core of [`max_honeybadger_mul_pairs_per_session`], factored
/// out so the default formula is unit-testable without touching process-global
/// environment state. `override_pairs = Some(n)` forces the result to `n`.
pub(crate) fn max_honeybadger_mul_pairs_per_session_with(
    threshold: usize,
    override_pairs: Option<usize>,
) -> usize {
    if let Some(value) = override_pairs {
        return value.max(1);
    }
    DEFAULT_MAX_HONEYBADGER_MUL_BATCH_RECON_CHUNKS.saturating_mul(threshold.saturating_add(1))
}

impl<F, G> HoneyBadgerMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + PrimeGroup + Send + Sync + 'static,
{
    fn trace_multiply_enabled() -> bool {
        std::env::var("STOFFEL_HB_MULTIPLY_TRACE")
            .is_ok_and(|value| matches!(value.as_str(), "1" | "true" | "TRUE" | "yes" | "YES"))
    }

    pub async fn multiply_share_async(
        &self,
        ty: ShareType,
        left: &[u8],
        right: &[u8],
    ) -> Result<ShareData, String> {
        if !self.is_ready() {
            return Err("MPC engine not ready".into());
        }

        // Secret fixed-point multiplication needs the truncating fixed-point
        // multiply (the raw integer multiply would leave the product with 2f
        // fractional bits) plus the same probabilistic-truncation preprocessing
        // the fixed-point division path provisions. Route it through `mul_fixed`
        // and provision a pool of prandbit/prandint (and the triples/randoms
        // their generation consumes) so it is self-sufficient without a protocol
        // change, mirroring `divide_fixed_by_constant_async`.
        if let ShareType::SecretFixedPoint { precision } = ty {
            let left_share = Self::decode_share(left)?;
            let right_share = Self::decode_share(right)?;
            let proto_precision =
                FixedPointPrecision::new(precision.total_bits(), precision.fractional_bits());
            let x = SecretFixedPoint::new_with_precision(left_share, proto_precision);
            let y = SecretFixedPoint::new_with_precision(right_share, proto_precision);

            let mut node = self.clone_node().await;
            const PRANDBIT_POOL_MULS: usize = 16;
            let f = precision.fractional_bits();
            let pool = f.saturating_mul(PRANDBIT_POOL_MULS);
            node.params.n_prandbit = node.params.n_prandbit.max(pool);
            node.params.n_prandint = node.params.n_prandint.max(PRANDBIT_POOL_MULS);
            node.params.n_triples = node.params.n_triples.saturating_add(pool);
            node.params.n_random_shares = node.params.n_random_shares.saturating_add(pool);

            let result = node
                .mul_fixed(x, y, self.net.clone())
                .await
                .map_err(|e| format!("MPC fixed-point multiply failed: {:?}", e))?;
            return Self::encode_share(result.value()).map(|v| ShareData::Opaque(v.into()));
        }

        match ty {
            ShareType::SecretInt { .. }
            | ShareType::SecretUInt { .. }
            | ShareType::SecretFixedPoint { .. } => {
                let left_share = Self::decode_share(left)?;
                let right_share = Self::decode_share(right)?;

                let mut node = self.clone_node().await;
                // Provision a triple pool so a secret*secret multiply is
                // self-sufficient even when the program's static preprocessing
                // estimate was 0 (e.g. operands produced by `Share.from_clear*`,
                // whose opaque type the demand analysis doesn't count). node.mul
                // regenerates from params on demand; `.max` never shrinks an
                // already-sized estimate (e.g. AES/CBC). Triple generation pulls
                // 2 randoms each, which run_preprocessing adds automatically.
                const TRIPLE_POOL_MULS: usize = 64;
                node.params.n_triples = node.params.n_triples.max(TRIPLE_POOL_MULS);
                let trace = Self::trace_multiply_enabled();
                let started_at = Instant::now();
                if trace {
                    let _m = node.preprocessing_material.lock().await.length();
                    let (triples, randoms, bits, exp_points) =
                        (_m.beaver_triples, _m.random_shr, _m.prandbit, _m.prandint);
                    eprintln!(
                        "[hb multiply start] party={} items=1 ty={:?} material=triples:{} randoms:{} bits:{} exp_points:{}",
                        self.topology.party_id(),
                        ty,
                        triples,
                        randoms,
                        bits,
                        exp_points
                    );
                }
                let result_shares = node
                    .mul(vec![left_share], vec![right_share], self.net.clone())
                    .await
                    .map_err(|e| format!("MPC multiplication failed: {:?}", e))?;
                if trace {
                    let _m = node.preprocessing_material.lock().await.length();
                    let (triples, randoms, bits, exp_points) =
                        (_m.beaver_triples, _m.random_shr, _m.prandbit, _m.prandint);
                    eprintln!(
                        "[hb multiply done] party={} items=1 elapsed_ms={} material=triples:{} randoms:{} bits:{} exp_points:{}",
                        self.topology.party_id(),
                        started_at.elapsed().as_millis(),
                        triples,
                        randoms,
                        bits,
                        exp_points
                    );
                }

                let result_share = result_shares
                    .into_iter()
                    .next()
                    .ok_or_else(|| "Multiplication returned no shares".to_string())?;

                Self::encode_share(&result_share).map(|v| ShareData::Opaque(v.into()))
            }
        }
    }

    /// Divide a secret fixed-point share by a public positive constant using the
    /// HoneyBadger fixed-point division protocol (reciprocal + probabilistic
    /// truncation). `divisor_scaled` is `round(divisor * 2^f)`, i.e. the divisor
    /// in the same fixed-point scale as the share. The protocol node pulls (and,
    /// if depleted, regenerates) the truncation randomness it needs internally.
    pub async fn divide_fixed_by_constant_async(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
        divisor_scaled: i64,
    ) -> Result<ShareData, String> {
        if !self.is_ready() {
            return Err("MPC engine not ready".into());
        }

        let precision = match ty {
            ShareType::SecretFixedPoint { precision } => precision,
            _ => {
                return Err(
                    "fixed-point division requires a secret fix64 (SecretFixedPoint) share".into(),
                )
            }
        };
        if divisor_scaled <= 0 {
            return Err("fixed-point division by a non-positive constant is not supported".into());
        }

        let dividend = Self::decode_share(share_bytes)?;
        let proto_precision =
            FixedPointPrecision::new(precision.total_bits(), precision.fractional_bits());
        let x = SecretFixedPoint::new_with_precision(dividend, proto_precision);
        let divisor_field = crate::net::curve::field_from_i64::<F>(divisor_scaled);
        let y = ClearFixedPoint::new_with_precision(divisor_field, proto_precision);

        let mut node = self.clone_node().await;
        // Each division's truncation consumes `f` random bits and one random
        // integer, which the VM's baseline preprocessing does not generate
        // (`honeybadger_node_opts` requests zero prandbit/prandint). The
        // protocol regenerates them on demand, but re-running that per division
        // collides across parties; so on the first division (empty pool) we
        // provision a pool covering several divisions in one preprocessing pass.
        // The preprocessing-material store is shared across node clones, so
        // later divisions consume from the pool and skip regeneration.
        //
        // Crucially, prandbit generation itself consumes one beaver triple and
        // one random share per bit, and the protocol's preprocessing budget does
        // NOT account for that. So we must also grow the triple/random targets
        // by the pool size; otherwise prandbit generation exhausts the triples
        // the computation needs (or fails outright). Configuring the demand here
        // is what makes division self-sufficient without any protocol change.
        const PRANDBIT_POOL_DIVS: usize = 16;
        let f = precision.fractional_bits();
        let pool = f.saturating_mul(PRANDBIT_POOL_DIVS);
        node.params.n_prandbit = node.params.n_prandbit.max(pool);
        node.params.n_prandint = node.params.n_prandint.max(PRANDBIT_POOL_DIVS);
        node.params.n_triples = node.params.n_triples.saturating_add(pool);
        node.params.n_random_shares = node.params.n_random_shares.saturating_add(pool);
        let result = node
            .div_with_const_fixed(x, y, self.net.clone())
            .await
            .map_err(|e| format!("MPC fixed-point division failed: {:?}", e))?;

        Self::encode_share(result.value()).map(|v| ShareData::Opaque(v.into()))
    }

    pub async fn batch_multiply_share_async(
        &self,
        ty: ShareType,
        pairs: &[(Vec<u8>, Vec<u8>)],
    ) -> Result<Vec<ShareData>, String> {
        if !self.is_ready() {
            return Err("MPC engine not ready".into());
        }

        if pairs.is_empty() {
            return Ok(Vec::new());
        }

        match ty {
            ShareType::SecretInt { .. }
            | ShareType::SecretUInt { .. }
            | ShareType::SecretFixedPoint { .. } => {
                let max_pairs_per_session =
                    max_honeybadger_mul_pairs_per_session(self.topology.threshold()).max(1);
                let trace = Self::trace_multiply_enabled();
                let started_at = Instant::now();
                if trace {
                    eprintln!(
                        "[hb batch_multiply start] party={} items={} ty={:?}",
                        self.topology.party_id(),
                        pairs.len(),
                        ty
                    );
                }

                let mut encoded_results = Vec::with_capacity(pairs.len());
                let mut node = self.clone_node().await;
                node.params.n_triples = node.params.n_triples.max(max_pairs_per_session);
                for (chunk_index, chunk) in pairs.chunks(max_pairs_per_session).enumerate() {
                    let mut left_shares = Vec::with_capacity(chunk.len());
                    let mut right_shares = Vec::with_capacity(chunk.len());

                    for (left, right) in chunk {
                        left_shares.push(Self::decode_share(left)?);
                        right_shares.push(Self::decode_share(right)?);
                    }

                    let chunk_started_at = Instant::now();
                    if trace {
                        let _m = node.preprocessing_material.lock().await.length();
                        let (triples, randoms, bits, exp_points) =
                            (_m.beaver_triples, _m.random_shr, _m.prandbit, _m.prandint);
                        eprintln!(
                            "[hb batch_multiply chunk start] party={} chunk={} items={} material=triples:{} randoms:{} bits:{} exp_points:{}",
                            self.topology.party_id(),
                            chunk_index,
                            chunk.len(),
                            triples,
                            randoms,
                            bits,
                            exp_points
                        );
                    }

                    let result_shares = node
                        .mul(left_shares, right_shares, self.net.clone())
                        .await
                        .map_err(|e| format!("MPC batch multiplication failed: {:?}", e))?;
                    if trace {
                        let _m = node.preprocessing_material.lock().await.length();
                        let (triples, randoms, bits, exp_points) =
                            (_m.beaver_triples, _m.random_shr, _m.prandbit, _m.prandint);
                        eprintln!(
                            "[hb batch_multiply chunk done] party={} chunk={} items={} elapsed_ms={} material=triples:{} randoms:{} bits:{} exp_points:{}",
                            self.topology.party_id(),
                            chunk_index,
                            chunk.len(),
                            chunk_started_at.elapsed().as_millis(),
                            triples,
                            randoms,
                            bits,
                            exp_points
                        );
                    }

                    if result_shares.len() != chunk.len() {
                        return Err(format!(
                            "Batch multiplication returned {} shares for {} inputs",
                            result_shares.len(),
                            chunk.len()
                        ));
                    }

                    for share in result_shares {
                        encoded_results
                            .push(Self::encode_share(&share).map(|v| ShareData::Opaque(v.into()))?);
                    }
                }
                if trace {
                    eprintln!(
                        "[hb batch_multiply done] party={} items={} chunks={} elapsed_ms={}",
                        self.topology.party_id(),
                        pairs.len(),
                        pairs.len().div_ceil(max_pairs_per_session),
                        started_at.elapsed().as_millis()
                    );
                }

                Ok(encoded_results)
            }
        }
    }

    pub async fn open_share_async_impl(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
    ) -> Result<ClearShareValue, String> {
        let type_key = match ty {
            ShareType::SecretInt { bit_length } => format!("hb-int-{bit_length}"),
            ShareType::SecretUInt { bit_length } => format!("hb-uint-{bit_length}"),
            ShareType::SecretFixedPoint { precision } => {
                format!("hb-fixed-{}-{}", precision.k(), precision.f())
            }
        };

        let seq = self.open_registry.insert_single_next(
            &type_key,
            self.topology.party_id(),
            share_bytes.to_vec(),
        )?;
        let wire_message = crate::net::open_registry::encode_single_share_wire_message(
            self.topology.instance_id(),
            seq,
            &type_key,
            self.topology.party_id(),
            share_bytes,
        )?;
        self.broadcast_open_registry_payload(wire_message).await?;

        let required = Self::robust_open_required_contributions(self.topology.threshold());
        let n = self.topology.n_parties();
        let t = self.topology.threshold();

        self.open_registry
            .open_share_at_async(
                self.topology.party_id(),
                type_key,
                seq,
                share_bytes.to_vec(),
                required,
                |collected| {
                    let mut shares: Vec<RobustShare<F>> = Vec::with_capacity(collected.len());
                    for bytes in collected {
                        shares.push(Self::decode_share(bytes)?);
                    }

                    let (_deg, secret) = RobustShare::recover_secret(&shares, n, t)
                        .map_err(|e| format!("recover_secret: {:?}", e))?;
                    Self::field_to_clear_share_value(ty, secret)
                },
            )
            .await
    }

    /// Reveal a share as its raw field element (rather than decoding it back to
    /// an integer/fixed-point clear value). Backs `Share.open_field`, which lets
    /// StoffelLang programs do public field arithmetic on opened values (e.g.
    /// the joint random-bit protocol opens `r^2` and takes its field sqrt).
    ///
    /// Reconstruction is identical to `open_share` — collect `3t+1` robust
    /// shares and recover the secret — but the result is the canonically
    /// serialized field element. A distinct `hb-field-*` type key keeps this
    /// opening's broadcast namespace separate from the integer `open` path.
    pub async fn open_share_as_field_async_impl(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        let type_key = match ty {
            ShareType::SecretInt { bit_length } => format!("hb-field-int-{bit_length}"),
            ShareType::SecretUInt { bit_length } => format!("hb-field-uint-{bit_length}"),
            ShareType::SecretFixedPoint { precision } => {
                format!("hb-field-fixed-{}-{}", precision.k(), precision.f())
            }
        };

        let seq = self.open_registry.insert_single_next(
            &type_key,
            self.topology.party_id(),
            share_bytes.to_vec(),
        )?;
        let wire_message = crate::net::open_registry::encode_single_share_wire_message(
            self.topology.instance_id(),
            seq,
            &type_key,
            self.topology.party_id(),
            share_bytes,
        )?;
        self.broadcast_open_registry_payload(wire_message).await?;

        let required = Self::robust_open_required_contributions(self.topology.threshold());
        let n = self.topology.n_parties();
        let t = self.topology.threshold();

        self.open_registry
            .open_bytes_at_async(
                self.topology.party_id(),
                type_key,
                seq,
                share_bytes.to_vec(),
                required,
                |collected| {
                    let mut shares: Vec<RobustShare<F>> = Vec::with_capacity(collected.len());
                    for bytes in collected {
                        shares.push(Self::decode_share(bytes)?);
                    }

                    let (_deg, secret) = RobustShare::recover_secret(&shares, n, t)
                        .map_err(|e| format!("recover_secret: {:?}", e))?;
                    let mut out = Vec::new();
                    secret
                        .serialize_compressed(&mut out)
                        .map_err(|e| format!("serialize field element: {}", e))?;
                    Ok(out)
                },
            )
            .await
    }

    pub async fn batch_open_shares_async_impl(
        &self,
        ty: ShareType,
        shares: &[Vec<u8>],
    ) -> Result<Vec<ClearShareValue>, String> {
        if shares.is_empty() {
            return Ok(Vec::new());
        }

        let type_key = match ty {
            ShareType::SecretInt { bit_length } => format!("hb-batch-int-{bit_length}"),
            ShareType::SecretUInt { bit_length } => format!("hb-batch-uint-{bit_length}"),
            ShareType::SecretFixedPoint { precision } => {
                format!("hb-batch-fixed-{}-{}", precision.k(), precision.f())
            }
        };

        let seq = self.open_registry.insert_batch_next(
            &type_key,
            self.topology.party_id(),
            shares.to_vec(),
        )?;
        let wire_message = crate::net::open_registry::encode_batch_share_wire_message(
            self.topology.instance_id(),
            seq,
            &type_key,
            self.topology.party_id(),
            shares,
        )?;
        self.broadcast_open_registry_payload(wire_message).await?;

        let required = Self::robust_open_required_contributions(self.topology.threshold());
        let n = self.topology.n_parties();
        let t = self.topology.threshold();

        self.open_registry
            .batch_open_at_async(
                self.topology.party_id(),
                type_key,
                Some(seq),
                shares.to_vec(),
                required,
                |collected, pos| {
                    let mut decoded_shares: Vec<RobustShare<F>> =
                        Vec::with_capacity(collected.len());
                    for bytes in collected {
                        decoded_shares.push(Self::decode_share(bytes)?);
                    }

                    let (_deg, secret) = RobustShare::recover_secret(&decoded_shares, n, t)
                        .map_err(|e| format!("batch recover_secret pos {}: {:?}", pos, e))?;
                    Self::field_to_clear_share_value(ty, secret)
                },
            )
            .await
    }

    async fn broadcast_open_exp_payload(&self, payload: Vec<u8>) -> Result<(), String> {
        crate::net::broadcast::broadcast_to_other_parties(
            self.net.as_ref(),
            self.topology.n_parties(),
            self.topology.party_id(),
            &payload,
            "Failed to send open-exp payload to party",
        )
        .await
    }

    fn broadcast_open_exp_payload_sync(&self, payload: Vec<u8>) -> Result<(), String> {
        crate::net::block_on_current(self.broadcast_open_exp_payload(payload))
    }

    pub(super) async fn broadcast_open_registry_payload(
        &self,
        payload: Vec<u8>,
    ) -> Result<(), String> {
        crate::net::broadcast::broadcast_to_other_parties(
            self.net.as_ref(),
            self.topology.n_parties(),
            self.topology.party_id(),
            &payload,
            "Failed to send open payload to party",
        )
        .await
    }

    pub(super) fn broadcast_open_registry_payload_sync(
        &self,
        payload: Vec<u8>,
    ) -> Result<(), String> {
        crate::net::block_on_current(self.broadcast_open_registry_payload(payload))
    }

    /// Reveal a share in the exponent using transport-backed contribution exchange.
    ///
    /// Each party computes `share_value * generator`, broadcasts its partial point,
    /// and reconstructs `[secret] * generator` once `2t+1` contributions are available.
    pub fn open_share_in_exp_impl(
        &self,
        _ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        let share = Self::decode_share(share_bytes)?;
        let generator = G::deserialize_compressed(generator_bytes)
            .map_err(|e| format!("deserialize generator: {}", e))?;
        let partial_point = generator * share.share[0];

        let mut partial_bytes = Vec::new();
        partial_point
            .into_affine()
            .serialize_compressed(&mut partial_bytes)
            .map_err(|e| format!("serialize partial point: {}", e))?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G1,
            self.topology.party_id(),
            share.id,
            partial_bytes.clone(),
        )?;
        let wire_message = crate::net::open_registry::encode_hb_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share.id,
            &partial_bytes,
        )?;
        self.broadcast_open_exp_payload_sync(wire_message)?;

        let required = 2 * self.topology.threshold() + 1;
        let n = self.topology.n_parties();
        let domain = GeneralEvaluationDomain::<F>::new(n)
            .ok_or_else(|| "No suitable FFT domain".to_string())?;

        self.open_registry.exp_open_wait(
            ExpOpenRequest {
                kind: ExpOpenRegistryKind::G1,
                sequence: Some(seq),
                party_id: self.topology.party_id(),
                share_id: share.id,
                partial_point: &partial_bytes,
                required,
                timeout_message: "Timeout waiting for open_share_in_exp contributions",
            },
            |partial_points| {
                crate::net::group_interpolation::interpolate_compressed_group_points::<F, G, _>(
                    partial_points,
                    |id| Ok(domain.element(id)),
                    "deserialize partial point",
                    "zero denominator in Lagrange",
                    "serialize result",
                )
            },
        )
    }

    pub async fn open_share_in_exp_async_impl(
        &self,
        _ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        let share = Self::decode_share(share_bytes)?;
        let generator = G::deserialize_compressed(generator_bytes)
            .map_err(|e| format!("deserialize generator: {}", e))?;
        let partial_point = generator * share.share[0];

        let mut partial_bytes = Vec::new();
        partial_point
            .into_affine()
            .serialize_compressed(&mut partial_bytes)
            .map_err(|e| format!("serialize partial point: {}", e))?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G1,
            self.topology.party_id(),
            share.id,
            partial_bytes.clone(),
        )?;
        let wire_message = crate::net::open_registry::encode_hb_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share.id,
            &partial_bytes,
        )?;
        self.broadcast_open_exp_payload(wire_message).await?;

        let required = 2 * self.topology.threshold() + 1;
        let n = self.topology.n_parties();
        let domain = GeneralEvaluationDomain::<F>::new(n)
            .ok_or_else(|| "No suitable FFT domain".to_string())?;

        self.open_registry
            .exp_open_async(
                ExpOpenRequest {
                    kind: ExpOpenRegistryKind::G1,
                    sequence: Some(seq),
                    party_id: self.topology.party_id(),
                    share_id: share.id,
                    partial_point: &partial_bytes,
                    required,
                    timeout_message: "Timeout waiting for open_share_in_exp contributions",
                },
                |partial_points| {
                    crate::net::group_interpolation::interpolate_compressed_group_points::<F, G, _>(
                        partial_points,
                        |id| Ok(domain.element(id)),
                        "deserialize partial point",
                        "zero denominator in Lagrange",
                        "serialize result",
                    )
                },
            )
            .await
    }

    pub fn open_share_in_exp_bls12381_g2_impl(
        &self,
        share_bytes: &[u8],
        generator_g2_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        use ark_bls12_381::{Fr, G2Projective};

        if TypeId::of::<F>() != TypeId::of::<Fr>() {
            return Err(format!(
                "MPC backend '{}' uses {:?}, which cannot open shares in bls12-381-g2",
                self.protocol_name(),
                F::CURVE_CONFIG
            ));
        }

        let share = Self::decode_share(share_bytes)?;
        let generator = G2Projective::deserialize_compressed(generator_g2_bytes)
            .map_err(|e| format!("deserialize G2 generator: {}", e))?;

        let mut share_value_bytes = Vec::new();
        share.share[0]
            .serialize_compressed(&mut share_value_bytes)
            .map_err(|e| format!("serialize BLS12-381 scalar share: {}", e))?;
        let share_value = Fr::deserialize_compressed(&share_value_bytes[..])
            .map_err(|e| format!("deserialize BLS12-381 scalar share: {}", e))?;

        let partial_point = generator * share_value;
        let mut partial_bytes = Vec::new();
        partial_point
            .into_affine()
            .serialize_compressed(&mut partial_bytes)
            .map_err(|e| format!("serialize G2 partial point: {}", e))?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G1,
            self.topology.party_id(),
            share.id,
            partial_bytes.clone(),
        )?;
        let wire_message = crate::net::open_registry::encode_hb_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share.id,
            &partial_bytes,
        )?;
        self.broadcast_open_exp_payload_sync(wire_message)?;

        let required = 2 * self.topology.threshold() + 1;
        let n = self.topology.n_parties();
        let domain = GeneralEvaluationDomain::<Fr>::new(n)
            .ok_or_else(|| "No suitable FFT domain".to_string())?;

        self.open_registry.exp_open_wait(
            ExpOpenRequest {
                kind: ExpOpenRegistryKind::G1,
                sequence: Some(seq),
                party_id: self.topology.party_id(),
                share_id: share.id,
                partial_point: &partial_bytes,
                required,
                timeout_message: "Timeout waiting for BLS12-381 G2 open_share_in_exp contributions",
            },
            |partial_points| {
                crate::net::group_interpolation::interpolate_compressed_group_points::<
                    Fr,
                    G2Projective,
                    _,
                >(
                    partial_points,
                    |id| Ok(domain.element(id)),
                    "deserialize G2 partial point",
                    "zero denominator in BLS12-381 G2 Lagrange",
                    "serialize G2 result",
                )
            },
        )
    }

    pub async fn open_share_in_exp_bls12381_g2_async_impl(
        &self,
        share_bytes: &[u8],
        generator_g2_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        use ark_bls12_381::{Fr, G2Projective};

        if TypeId::of::<F>() != TypeId::of::<Fr>() {
            return Err(format!(
                "MPC backend '{}' uses {:?}, which cannot open shares in bls12-381-g2",
                self.protocol_name(),
                F::CURVE_CONFIG
            ));
        }

        let share = Self::decode_share(share_bytes)?;
        let generator = G2Projective::deserialize_compressed(generator_g2_bytes)
            .map_err(|e| format!("deserialize G2 generator: {}", e))?;

        let mut share_value_bytes = Vec::new();
        share.share[0]
            .serialize_compressed(&mut share_value_bytes)
            .map_err(|e| format!("serialize BLS12-381 scalar share: {}", e))?;
        let share_value = Fr::deserialize_compressed(&share_value_bytes[..])
            .map_err(|e| format!("deserialize BLS12-381 scalar share: {}", e))?;

        let partial_point = generator * share_value;
        let mut partial_bytes = Vec::new();
        partial_point
            .into_affine()
            .serialize_compressed(&mut partial_bytes)
            .map_err(|e| format!("serialize G2 partial point: {}", e))?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G1,
            self.topology.party_id(),
            share.id,
            partial_bytes.clone(),
        )?;
        let wire_message = crate::net::open_registry::encode_hb_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share.id,
            &partial_bytes,
        )?;
        self.broadcast_open_exp_payload(wire_message).await?;

        let required = 2 * self.topology.threshold() + 1;
        let n = self.topology.n_parties();
        let domain = GeneralEvaluationDomain::<Fr>::new(n)
            .ok_or_else(|| "No suitable FFT domain".to_string())?;

        self.open_registry
            .exp_open_async(
                ExpOpenRequest {
                    kind: ExpOpenRegistryKind::G1,
                    sequence: Some(seq),
                    party_id: self.topology.party_id(),
                    share_id: share.id,
                    partial_point: &partial_bytes,
                    required,
                    timeout_message:
                        "Timeout waiting for BLS12-381 G2 open_share_in_exp contributions",
                },
                |partial_points| {
                    crate::net::group_interpolation::interpolate_compressed_group_points::<
                        Fr,
                        G2Projective,
                        _,
                    >(
                        partial_points,
                        |id| Ok(domain.element(id)),
                        "deserialize G2 partial point",
                        "zero denominator in BLS12-381 G2 Lagrange",
                        "serialize G2 result",
                    )
                },
            )
            .await
    }

    pub(super) fn field_to_clear_share_value(
        ty: ShareType,
        secret: F,
    ) -> Result<ClearShareValue, String> {
        crate::net::curve::field_to_clear_share_value(ty, secret).map_err(Into::into)
    }

    pub(super) fn encode_share(share: &RobustShare<F>) -> Result<Vec<u8>, String> {
        let mut out = Vec::new();
        share
            .serialize_compressed(&mut out)
            .map_err(|e| format!("serialize share: {}", e))?;
        Ok(out)
    }

    pub(super) fn decode_share(bytes: &[u8]) -> Result<RobustShare<F>, String> {
        RobustShare::<F>::deserialize_compressed(bytes)
            .map_err(|e| format!("deserialize share: {}", e))
    }
}

#[cfg(test)]
mod tests {
    use super::max_honeybadger_mul_pairs_per_session_with;

    #[test]
    fn default_max_mul_pairs_per_session_matches_protocol_deserialization_bound() {
        // Default (no override): 128 * (t+1), matching mpc-protocols' own
        // per-session deserialization bound — one `mul()` session opens all its
        // (t+1)-groups through a single batch_recon, so the width is bounded by
        // that deser limit, not by child-session id space.
        assert_eq!(max_honeybadger_mul_pairs_per_session_with(0, None), 128);
        assert_eq!(max_honeybadger_mul_pairs_per_session_with(1, None), 256);
        assert_eq!(max_honeybadger_mul_pairs_per_session_with(3, None), 512);
    }

    #[test]
    fn override_forces_pairs_per_session_directly() {
        // An explicit override is used as-is (not forced to a multiple of t+1).
        assert_eq!(
            max_honeybadger_mul_pairs_per_session_with(1, Some(256)),
            256
        );
        // A floor of 1 keeps an accidental 0 from starving every multiply.
        assert_eq!(max_honeybadger_mul_pairs_per_session_with(1, Some(0)), 1);
    }
}