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
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
use super::{field_from_usize, usize_seed, AvssMpcEngine};
use crate::net::client_store::{
    ClientInputHydrationCount, ClientInputStore, ClientOutputShareCount,
};
use crate::net::curve::{MpcCurveConfig, SupportedMpcField};
use crate::net::mpc_engine::{
    AsyncMpcEngine, AsyncMpcEngineClientOps, MpcEngine, MpcEngineClientOps, MpcEngineClientOutput,
    MpcEngineError, MpcEngineFieldOpen, MpcEngineMultiplication, MpcEngineOpenInExponent,
    MpcEngineOperationResultExt, MpcEnginePreprocPersistence, MpcEngineRandomness, MpcEngineResult,
    MpcExponentGroup,
};
use crate::net::open_registry::{ExpOpenRegistryKind, ExpOpenRequest};
use crate::storage::preproc::PreprocStore;
use ark_ec::CurveGroup;
use ark_ff::UniformRand;
use std::any::TypeId;
use std::sync::Arc;
use stoffel_vm_types::core_types::{ClearShareInput, ClearShareValue, ShareData, ShareType};
use stoffelmpc_mpc::common::share::feldman::FeldmanShamirShare;
use stoffelmpc_mpc::common::MPCProtocol;
use stoffelnet::network_utils::ClientId;
use stoffelnet::transports::quic::QuicNetworkManager;

impl<F, G> AvssMpcEngine<F, G>
where
    F: SupportedMpcField + UniformRand,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    async fn broadcast_open_avss_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,
            "broadcast avss open-exp to",
        )
        .await
    }

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

    /// Reveal an AVSS share in the exponent: reconstructs `[secret] * generator`
    /// via Lagrange interpolation in the group using integer evaluation points (1, 2, ...).
    ///
    /// Each party computes `share_value * generator`, broadcasts its partial point,
    /// and waits until `t+1` contributions are available.
    fn open_share_in_exp_impl(
        &self,
        _ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        let share = Self::decode_feldman_share(share_bytes)?;
        let generator = G::deserialize_compressed(generator_bytes)
            .map_err(|e| format!("deserialize generator: {}", e))?;

        let share_value = share.feldmanshare.share[0];
        let share_id = share.feldmanshare.id;

        let partial_point = generator * share_value;
        let partial_bytes =
            Self::encode_verified_exp_contribution(&share, generator, partial_point)?;

        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_avss_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share_id,
            &partial_bytes,
        )?;
        self.broadcast_open_avss_exp_payload_sync(wire_message)?;

        let required_valid = self.topology.threshold() + 1;
        let required = Self::byzantine_open_contribution_count(
            self.topology.n_parties(),
            self.topology.threshold(),
        )?;
        self.open_registry.exp_open_wait(
            ExpOpenRequest {
                kind: ExpOpenRegistryKind::G1,
                sequence: Some(seq),
                party_id: self.topology.party_id(),
                share_id,
                partial_point: &partial_bytes,
                required,
                timeout_message: "Timeout waiting for AVSS open_share_in_exp contributions",
            },
            |partial_points| {
                let verified_points = Self::filter_verified_exp_points(
                    share_bytes,
                    generator,
                    partial_points,
                    required_valid,
                    "AVSS open_share_in_exp",
                )?;
                crate::net::group_interpolation::interpolate_compressed_group_points::<F, G, _>(
                    &verified_points,
                    |id| field_from_usize::<F>(id, "AVSS evaluation point"),
                    "deserialize partial point",
                    "zero denominator in AVSS Lagrange",
                    "serialize result",
                )
            },
        )
    }

    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_feldman_share(share_bytes)?;
        let generator = G::deserialize_compressed(generator_bytes)
            .map_err(|e| format!("deserialize generator: {}", e))?;

        let share_value = share.feldmanshare.share[0];
        let share_id = share.feldmanshare.id;

        let partial_point = generator * share_value;
        let partial_bytes =
            Self::encode_verified_exp_contribution(&share, generator, partial_point)?;

        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_avss_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share_id,
            &partial_bytes,
        )?;
        self.broadcast_open_avss_exp_payload(wire_message).await?;

        let required_valid = self.topology.threshold() + 1;
        let required = Self::byzantine_open_contribution_count(
            self.topology.n_parties(),
            self.topology.threshold(),
        )?;
        self.open_registry
            .exp_open_async(
                ExpOpenRequest {
                    kind: ExpOpenRegistryKind::G1,
                    sequence: Some(seq),
                    party_id: self.topology.party_id(),
                    share_id,
                    partial_point: &partial_bytes,
                    required,
                    timeout_message: "Timeout waiting for AVSS open_share_in_exp contributions",
                },
                |partial_points| {
                    let verified_points = Self::filter_verified_exp_points(
                        share_bytes,
                        generator,
                        partial_points,
                        required_valid,
                        "AVSS async_open_share_in_exp",
                    )?;
                    crate::net::group_interpolation::interpolate_compressed_group_points::<F, G, _>(
                        &verified_points,
                        |id| field_from_usize::<F>(id, "AVSS evaluation point"),
                        "deserialize partial point",
                        "zero denominator in AVSS Lagrange",
                        "serialize result",
                    )
                },
            )
            .await
    }

    fn open_share_in_exp_bls12381_g2(
        &self,
        share_bytes: &[u8],
        generator_g2_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        use ark_bls12_381::{Fr, G2Projective};
        use ark_serialize::CanonicalDeserialize as _;

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

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

        let mut share_value_bytes = Vec::new();
        share.feldmanshare.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 share_id: usize = share.feldmanshare.id;

        let partial_point: G2Projective = generator_g2 * share_value;
        let partial_bytes = Self::encode_verified_g2_exp_contribution(partial_point)?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G2,
            self.topology.party_id(),
            share_id,
            partial_bytes.clone(),
        )?;
        let wire_payload = crate::net::open_registry::encode_avss_g2_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share_id,
            &partial_bytes,
        )?;

        crate::net::block_on_current(crate::net::broadcast::broadcast_to_other_parties(
            self.net.as_ref(),
            self.topology.n_parties(),
            self.topology.party_id(),
            &wire_payload,
            "broadcast avss g2 open-exp to",
        ))?;

        let required_valid = self.topology.threshold() + 1;
        let required = Self::byzantine_open_contribution_count(
            self.topology.n_parties(),
            self.topology.threshold(),
        )?;
        self.open_registry.exp_open_wait(
            ExpOpenRequest {
                kind: ExpOpenRegistryKind::G2,
                sequence: Some(seq),
                party_id: self.topology.party_id(),
                share_id,
                partial_point: &partial_bytes,
                required,
                timeout_message: "Timeout waiting for AVSS G2 open_share_in_exp contributions",
            },
            |partial_points| {
                let verified_points = Self::filter_verified_bls12381_g2_exp_points(
                    share_bytes,
                    generator_g2,
                    partial_points,
                    required_valid,
                    "AVSS G2 open_share_in_exp",
                )?;
                crate::net::group_interpolation::interpolate_compressed_group_points::<
                    Fr,
                    G2Projective,
                    _,
                >(
                    &verified_points,
                    |id| usize_seed(id, "AVSS G2 evaluation point").map(Fr::from),
                    "deserialize G2 partial point",
                    "zero denominator in AVSS G2 Lagrange",
                    "serialize G2 result",
                )
            },
        )
    }

    async fn open_share_in_exp_bls12381_g2_async(
        &self,
        share_bytes: &[u8],
        generator_g2_bytes: &[u8],
    ) -> Result<Vec<u8>, String> {
        use ark_bls12_381::{Fr, G2Projective};
        use ark_serialize::CanonicalDeserialize as _;

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

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

        let mut share_value_bytes = Vec::new();
        share.feldmanshare.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 share_id: usize = share.feldmanshare.id;

        let partial_point: G2Projective = generator_g2 * share_value;
        let partial_bytes = Self::encode_verified_g2_exp_contribution(partial_point)?;

        let seq = self.open_registry.insert_exp_next(
            ExpOpenRegistryKind::G2,
            self.topology.party_id(),
            share_id,
            partial_bytes.clone(),
        )?;
        let wire_payload = crate::net::open_registry::encode_avss_g2_open_exp_wire_message(
            self.topology.instance_id(),
            seq,
            self.topology.party_id(),
            share_id,
            &partial_bytes,
        )?;

        crate::net::broadcast::broadcast_to_other_parties(
            self.net.as_ref(),
            self.topology.n_parties(),
            self.topology.party_id(),
            &wire_payload,
            "broadcast avss g2 open-exp to",
        )
        .await?;

        let required_valid = self.topology.threshold() + 1;
        let required = Self::byzantine_open_contribution_count(
            self.topology.n_parties(),
            self.topology.threshold(),
        )?;
        self.open_registry
            .exp_open_async(
                ExpOpenRequest {
                    kind: ExpOpenRegistryKind::G2,
                    sequence: Some(seq),
                    party_id: self.topology.party_id(),
                    share_id,
                    partial_point: &partial_bytes,
                    required,
                    timeout_message: "Timeout waiting for AVSS G2 open_share_in_exp contributions",
                },
                |partial_points| {
                    let verified_points = Self::filter_verified_bls12381_g2_exp_points(
                        share_bytes,
                        generator_g2,
                        partial_points,
                        required_valid,
                        "AVSS G2 async_open_share_in_exp",
                    )?;
                    crate::net::group_interpolation::interpolate_compressed_group_points::<
                        Fr,
                        G2Projective,
                        _,
                    >(
                        &verified_points,
                        |id| usize_seed(id, "AVSS G2 evaluation point").map(Fr::from),
                        "deserialize G2 partial point",
                        "zero denominator in AVSS G2 Lagrange",
                        "serialize G2 result",
                    )
                },
            )
            .await
    }
}

impl<F, G> MpcEngineMultiplication for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn multiply_share(
        &self,
        _ty: ShareType,
        left: &[u8],
        right: &[u8],
    ) -> MpcEngineResult<ShareData> {
        (|| -> Result<ShareData, String> {
            let avss_node = self.avss_node.clone();
            let net = self.net.clone();
            let left_bytes = left.to_vec();
            let right_bytes = right.to_vec();

            let fut = Self::run_multiply_round(avss_node, net, left_bytes, right_bytes);

            match tokio::runtime::Handle::try_current() {
                Ok(handle) => {
                    #[allow(deprecated)]
                    let runtime_flavor = handle.runtime_flavor();
                    match runtime_flavor {
                        tokio::runtime::RuntimeFlavor::MultiThread => {
                            tokio::task::block_in_place(|| handle.block_on(fut))
                        }
                        tokio::runtime::RuntimeFlavor::CurrentThread => {
                            std::thread::spawn(move || {
                                let rt = tokio::runtime::Builder::new_current_thread()
                                    .enable_all()
                                    .build()
                                    .map_err(|e| format!("failed to create Tokio runtime: {e}"))?;
                                rt.block_on(fut)
                            })
                            .join()
                            .map_err(|_| "AVSS multiply worker thread panicked".to_string())?
                        }
                        _ => Err("operation requires a multi-thread Tokio runtime".to_string()),
                    }
                }
                Err(_) => {
                    let rt = tokio::runtime::Builder::new_current_thread()
                        .enable_all()
                        .build()
                        .map_err(|e| format!("failed to create Tokio runtime: {e}"))?;
                    rt.block_on(fut)
                }
            }
        })()
        .map_mpc_engine_operation("multiply_share")
    }
}

impl<F, G> MpcEnginePreprocPersistence for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn set_preproc_store(
        &self,
        store: Arc<dyn PreprocStore>,
        program_hash: [u8; 32],
    ) -> MpcEngineResult<()> {
        let field_kind = self.curve_config().field_kind();
        crate::net::try_block_on_current(async {
            *self.preproc_store.write().await = Some(store);
            *self.preproc_config.write().await = Some((program_hash, field_kind));
            Ok(())
        })
        .map_mpc_engine_operation("set_preproc_store")
    }
}

impl<F, G> MpcEngineFieldOpen for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn open_share_as_field(&self, ty: ShareType, share_bytes: &[u8]) -> MpcEngineResult<Vec<u8>> {
        (|| -> Result<Vec<u8>, String> {
            let type_key = match ty {
                ShareType::SecretInt { bit_length } => format!("avss-field-int-{bit_length}"),
                ShareType::SecretUInt { bit_length } => format!("avss-field-uint-{bit_length}"),
                ShareType::SecretFixedPoint { precision } => {
                    format!("avss-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_sync(wire_message)?;

            let n = self.topology.n_parties();
            let t = self.topology.threshold();
            let required = Self::byzantine_open_contribution_count(n, t)?;

            self.open_registry.open_bytes_at_wait(
                self.topology.party_id(),
                &type_key,
                seq,
                share_bytes,
                required,
                |collected| {
                    let secret = Self::reconstruct_verified_secret(
                        share_bytes,
                        collected,
                        n,
                        t,
                        "AVSS open_share_as_field",
                    )?;
                    let mut out = Vec::new();
                    secret
                        .serialize_compressed(&mut out)
                        .map_err(|e| format!("serialize field element: {}", e))?;
                    Ok(out)
                },
            )
        })()
        .map_mpc_engine_operation("open_share_as_field")
    }
}

impl<F, G> MpcEngineRandomness for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn random_share(&self, _ty: ShareType) -> MpcEngineResult<ShareData> {
        (|| -> Result<ShareData, String> {
            let share = crate::net::block_on_current(async {
                let mut node_clone = self.clone_avss_node().await;
                MPCProtocol::<F, FeldmanShamirShare<F, G>, QuicNetworkManager>::rand(
                    &mut node_clone,
                    self.net.clone(),
                )
                .await
                .map_err(|e| format!("random_share (multi-dealer RanSha) failed: {:?}", e))
            })?;
            Self::share_to_share_data(&share)
        })()
        .map_mpc_engine_operation("random_share")
    }
}

impl<F, G> MpcEngineOpenInExponent for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn open_share_in_exp(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> MpcEngineResult<Vec<u8>> {
        self.open_share_in_exp_impl(ty, share_bytes, generator_bytes)
            .map_mpc_engine_operation("open_share_in_exp")
    }

    fn native_exponent_group(&self) -> MpcExponentGroup {
        if TypeId::of::<G>() == TypeId::of::<ark_bls12_381::G1Projective>() {
            MpcExponentGroup::Bls12381G1
        } else if TypeId::of::<G>() == TypeId::of::<ark_bn254::G1Projective>() {
            MpcExponentGroup::Bn254G1
        } else if TypeId::of::<G>() == TypeId::of::<ark_curve25519::EdwardsProjective>() {
            MpcExponentGroup::Curve25519Edwards
        } else if TypeId::of::<G>() == TypeId::of::<ark_ed25519::EdwardsProjective>() {
            MpcExponentGroup::Ed25519Edwards
        } else if TypeId::of::<G>() == TypeId::of::<ark_secp256k1::Projective>() {
            MpcExponentGroup::Secp256k1
        } else if TypeId::of::<G>() == TypeId::of::<ark_secp256r1::Projective>() {
            MpcExponentGroup::P256
        } else {
            MpcExponentGroup::native_for_curve(self.curve_config())
        }
    }

    fn supports_exponent_group(&self, group: MpcExponentGroup) -> bool {
        match group {
            MpcExponentGroup::Bls12381G2 => TypeId::of::<F>() == TypeId::of::<ark_bls12_381::Fr>(),
            _ => self.native_exponent_group() == group,
        }
    }

    fn open_share_in_exp_group(
        &self,
        group: MpcExponentGroup,
        ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> MpcEngineResult<Vec<u8>> {
        if !self.supports_exponent_group(group) {
            return Err(MpcEngineError::operation_failed(
                "open_share_in_exp_group",
                group.unsupported_error(self.protocol_name()),
            ));
        }

        let result = match group {
            MpcExponentGroup::Bls12381G2 => {
                self.open_share_in_exp_bls12381_g2(share_bytes, generator_bytes)
            }
            _ => self.open_share_in_exp_impl(ty, share_bytes, generator_bytes),
        };

        result.map_mpc_engine_operation("open_share_in_exp_group")
    }
}

impl<F, G> MpcEngineClientOutput for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn send_output_to_client(
        &self,
        client_id: ClientId,
        shares: &[u8],
        output_share_count: ClientOutputShareCount,
    ) -> MpcEngineResult<()> {
        crate::net::try_block_on_current(self.send_output_to_client_async_impl(
            client_id,
            shares,
            output_share_count,
        ))
        .map_mpc_engine_operation("send_output_to_client")
    }
}

impl<F, G> MpcEngineClientOps for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn get_client_ids_sync(&self) -> Vec<ClientId> {
        match tokio::runtime::Handle::try_current() {
            Ok(handle) => {
                #[allow(deprecated)]
                let runtime_flavor = handle.runtime_flavor();
                match runtime_flavor {
                    tokio::runtime::RuntimeFlavor::MultiThread => {
                        tokio::task::block_in_place(|| handle.block_on(self.get_client_ids()))
                    }
                    _ => Vec::new(),
                }
            }
            Err(_) => {
                let rt = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                    .ok();
                rt.map(|rt| rt.block_on(self.get_client_ids()))
                    .unwrap_or_default()
            }
        }
    }

    fn hydrate_client_inputs_sync(
        &self,
        store: &ClientInputStore,
    ) -> MpcEngineResult<ClientInputHydrationCount> {
        crate::net::try_block_on_current(self.hydrate_client_inputs(store))
            .map_mpc_engine_operation("hydrate_client_inputs_sync")
    }

    fn hydrate_client_inputs_for_sync(
        &self,
        store: &ClientInputStore,
        client_ids: &[ClientId],
    ) -> MpcEngineResult<ClientInputHydrationCount> {
        crate::net::try_block_on_current(self.hydrate_client_inputs_for(store, client_ids))
            .map_mpc_engine_operation("hydrate_client_inputs_for_sync")
    }
}

#[async_trait::async_trait]
impl<F, G> AsyncMpcEngineClientOps for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    async fn get_client_ids_async(&self) -> Vec<ClientId> {
        self.get_client_ids().await
    }

    async fn hydrate_client_inputs_async(
        &self,
        store: &ClientInputStore,
    ) -> MpcEngineResult<ClientInputHydrationCount> {
        self.hydrate_client_inputs(store)
            .await
            .map_mpc_engine_operation("hydrate_client_inputs_async")
    }

    async fn hydrate_client_inputs_for_async(
        &self,
        store: &ClientInputStore,
        client_ids: &[ClientId],
    ) -> MpcEngineResult<ClientInputHydrationCount> {
        self.hydrate_client_inputs_for(store, client_ids)
            .await
            .map_mpc_engine_operation("hydrate_client_inputs_for_async")
    }
}

#[async_trait::async_trait]
impl<F, G> AsyncMpcEngine for AvssMpcEngine<F, G>
where
    F: SupportedMpcField,
    G: CurveGroup<ScalarField = F> + Send + Sync + 'static,
{
    fn as_async_client_ops(&self) -> Option<&dyn AsyncMpcEngineClientOps> {
        Some(self)
    }

    async fn input_share_async(&self, clear: ClearShareInput) -> MpcEngineResult<ShareData> {
        async {
            let secret = Self::clear_input_to_field(clear)?;
            let share = self.local_constant_share(secret).await?;
            Self::share_to_share_data(&share)
        }
        .await
        .map_mpc_engine_operation("async_input_share")
    }

    async fn multiply_share_async(
        &self,
        _ty: ShareType,
        left: &[u8],
        right: &[u8],
    ) -> MpcEngineResult<ShareData> {
        Self::run_multiply_round(
            self.avss_node.clone(),
            self.net.clone(),
            left.to_vec(),
            right.to_vec(),
        )
        .await
        .map_mpc_engine_operation("async_multiply_share")
    }

    async fn open_share_async(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
    ) -> MpcEngineResult<ClearShareValue> {
        async {
            let type_key = match ty {
                ShareType::SecretInt { bit_length } => format!("avss-int-{bit_length}"),
                ShareType::SecretUInt { bit_length } => format!("avss-uint-{bit_length}"),
                ShareType::SecretFixedPoint { precision } => {
                    format!("avss-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 n = self.topology.n_parties();
            let t = self.topology.threshold();
            let required = Self::byzantine_open_contribution_count(n, t)?;

            self.open_registry
                .open_share_at_async(
                    self.topology.party_id(),
                    type_key,
                    seq,
                    share_bytes.to_vec(),
                    required,
                    |collected| {
                        let secret = Self::reconstruct_verified_secret(
                            share_bytes,
                            collected,
                            n,
                            t,
                            "AVSS async_open_share",
                        )?;
                        Self::field_to_clear_share_value(ty, secret)
                    },
                )
                .await
        }
        .await
        .map_mpc_engine_operation("async_open_share")
    }

    async fn batch_open_shares_async(
        &self,
        ty: ShareType,
        shares: &[Vec<u8>],
    ) -> MpcEngineResult<Vec<ClearShareValue>> {
        async {
            let type_key = match ty {
                ShareType::SecretInt { bit_length } => format!("avss-batch-int-{bit_length}"),
                ShareType::SecretUInt { bit_length } => format!("avss-batch-uint-{bit_length}"),
                ShareType::SecretFixedPoint { precision } => {
                    format!("avss-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 n = self.topology.n_parties();
            let t = self.topology.threshold();
            let required = Self::byzantine_open_contribution_count(n, t)?;

            self.open_registry
                .batch_open_at_async(
                    self.topology.party_id(),
                    type_key,
                    Some(seq),
                    shares.to_vec(),
                    required,
                    |collected, pos| {
                        let expected_share = shares.get(pos).ok_or_else(|| {
                            format!(
                                "AVSS async_batch_open_shares missing local share at position {pos}"
                            )
                        })?;
                        let secret = Self::reconstruct_verified_secret(
                            expected_share,
                            collected,
                            n,
                            t,
                            &format!("AVSS async_batch_open_shares pos {pos}"),
                        )?;
                        Self::field_to_clear_share_value(ty, secret)
                    },
                )
                .await
        }
        .await
        .map_mpc_engine_operation("async_batch_open_shares")
    }

    async fn random_share_async(&self, _ty: ShareType) -> MpcEngineResult<ShareData> {
        async {
            let mut node_clone = self.clone_avss_node().await;
            let share = MPCProtocol::<F, FeldmanShamirShare<F, G>, QuicNetworkManager>::rand(
                &mut node_clone,
                self.net.clone(),
            )
            .await
            .map_err(|e| format!("random_share (multi-dealer RanSha) failed: {:?}", e))?;
            Self::share_to_share_data(&share)
        }
        .await
        .map_mpc_engine_operation("async_random_share")
    }

    async fn open_share_as_field_async(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
    ) -> MpcEngineResult<Vec<u8>> {
        async {
            let type_key = match ty {
                ShareType::SecretInt { bit_length } => format!("avss-field-int-{bit_length}"),
                ShareType::SecretUInt { bit_length } => format!("avss-field-uint-{bit_length}"),
                ShareType::SecretFixedPoint { precision } => {
                    format!("avss-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 n = self.topology.n_parties();
            let t = self.topology.threshold();
            let required = Self::byzantine_open_contribution_count(n, t)?;

            self.open_registry
                .open_bytes_at_async(
                    self.topology.party_id(),
                    type_key,
                    seq,
                    share_bytes.to_vec(),
                    required,
                    |collected| {
                        let secret = Self::reconstruct_verified_secret(
                            share_bytes,
                            collected,
                            n,
                            t,
                            "AVSS async_open_share_as_field",
                        )?;
                        let mut out = Vec::new();
                        secret
                            .serialize_compressed(&mut out)
                            .map_err(|e| format!("serialize field element: {}", e))?;
                        Ok(out)
                    },
                )
                .await
        }
        .await
        .map_mpc_engine_operation("async_open_share_as_field")
    }

    async fn open_share_in_exp_async(
        &self,
        ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> MpcEngineResult<Vec<u8>> {
        self.open_share_in_exp_async_impl(ty, share_bytes, generator_bytes)
            .await
            .map_mpc_engine_operation("async_open_share_in_exp")
    }

    async fn open_share_in_exp_group_async(
        &self,
        group: MpcExponentGroup,
        ty: ShareType,
        share_bytes: &[u8],
        generator_bytes: &[u8],
    ) -> MpcEngineResult<Vec<u8>> {
        if !self.supports_exponent_group(group) {
            return Err(MpcEngineError::operation_failed(
                "async_open_share_in_exp_group",
                group.unsupported_error(self.protocol_name()),
            ));
        }

        let result = match group {
            MpcExponentGroup::Bls12381G2 => {
                self.open_share_in_exp_bls12381_g2_async(share_bytes, generator_bytes)
                    .await
            }
            _ => {
                self.open_share_in_exp_async_impl(ty, share_bytes, generator_bytes)
                    .await
            }
        };

        result.map_mpc_engine_operation("async_open_share_in_exp_group")
    }

    async fn send_output_to_client_async(
        &self,
        client_id: ClientId,
        shares: &[u8],
        output_share_count: ClientOutputShareCount,
    ) -> MpcEngineResult<()> {
        self.send_output_to_client_async_impl(client_id, shares, output_share_count)
            .await
            .map_mpc_engine_operation("async_send_output_to_client")
    }
}