arcium-core-utils 0.4.1

Arcium core utils
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
use primitives::algebra::elliptic_curve::Curve;

use crate::{
    circuit::{
        errors::{CircuitError, ConversionError},
        gate::Gate,
        AlgebraicType,
        BitShareBinaryOp,
        BitShareUnaryOp,
        FieldShareBinaryOp,
        FieldShareUnaryOp,
        FieldType,
        GateIndex,
        Input,
        PointPlaintextBinaryOp,
        PointShareBinaryOp,
        PointShareUnaryOp,
        ShareOrPlaintext,
    },
    key_recovery::{MXE_KEY_RECOVERY_D, MXE_KEY_RECOVERY_N},
};

/// A circuit composed of a sequence of gates, input and output identifiers.
///
/// Each circuit gate contains additional information about its output characteristics, refer to
///  the ` GateExt ` struct for more details.
///
/// The circuit is always valid because the gate addition is validated.
#[derive(Default, PartialEq, Debug, Clone)]
pub struct Circuit<C: Curve> {
    /// The circuit gates.
    pub(super) gates: Vec<GateExt<C>>,
    /// The input gates in order of definition
    pub(super) inputs: Vec<GateIndex>,
    /// The output gates in order of definition
    pub(super) outputs: Vec<GateIndex>,
}

/// A circuit gate together with additional information about its output.
/// The additional information is automatically deduced when the gate is added to the circuit.
#[derive(Clone, Debug, PartialEq)]
pub struct GateExt<C: Curve> {
    pub gate: Gate<C>,
    pub output: GateOutput,
    pub level: GateLevel,
}

/// Gate output characteristics like algebraic type, visibility, and batch size
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct GateOutput {
    pub(super) algebraic_type: AlgebraicType,
    pub(super) form: ShareOrPlaintext,
    pub(super) batch_size: u32,
}

/// The level of a gate in a circuit. All gates with the same level can be executed in parallel as
/// they do not depend on each other.
///
/// The gate level is a pair of integers: the first one is the communication round (level), and the
/// second one is a relative level within the same communication round. The gate communication round
/// is the number of communications rounds which have passed after the gate execution.
#[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Default)]
pub struct GateLevel {
    comm_level: usize,
    level: usize, // relative counter for ordering gates within a multiplicative level
}

impl<C: Curve> GateExt<C> {
    pub fn new(gate: Gate<C>, output: GateOutput, level: GateLevel) -> Self {
        Self {
            gate,
            output,
            level,
        }
    }
}

impl GateOutput {
    pub fn get_type(&self) -> AlgebraicType {
        self.algebraic_type
    }

    pub fn get_field_type(&self) -> Result<FieldType, ConversionError> {
        FieldType::try_from(self.algebraic_type)
    }

    pub fn get_field_type_unchecked(&self) -> FieldType {
        self.get_field_type().unwrap()
    }

    pub fn get_form(&self) -> ShareOrPlaintext {
        self.form
    }

    pub fn get_batch_size(&self) -> u32 {
        self.batch_size
    }

    fn is_field(&self) -> bool {
        FieldType::try_from(self.algebraic_type).is_ok()
    }

    fn is_bit(&self) -> bool {
        self.algebraic_type == AlgebraicType::Bit
    }

    fn is_point(&self) -> bool {
        self.algebraic_type == AlgebraicType::Point
    }

    fn is_base_field(&self) -> bool {
        self.algebraic_type == AlgebraicType::BaseField
    }

    fn is_scalar_field(&self) -> bool {
        self.algebraic_type == AlgebraicType::ScalarField
    }

    fn is_share(&self) -> bool {
        self.form == ShareOrPlaintext::Share
    }

    pub fn is_plaintext(&self) -> bool {
        self.form == ShareOrPlaintext::Plaintext
    }

    fn with_new_form(self, form: ShareOrPlaintext) -> Self {
        let mut res = self;
        res.form = form;
        res
    }

    fn with_new_type(self, algebraic_type: AlgebraicType) -> Self {
        let mut res = self;
        res.algebraic_type = algebraic_type;
        res
    }

    fn with_new_batch_size(self, batch_size: u32) -> Self {
        let mut res = self;
        res.batch_size = batch_size;
        res
    }
}

impl GateLevel {
    fn next(&self, comm_rounds: usize) -> GateLevel {
        if comm_rounds > 0 {
            GateLevel {
                comm_level: self.comm_level + comm_rounds,
                level: 0,
            }
        } else {
            GateLevel {
                comm_level: self.comm_level,
                level: self.level + 1,
            }
        }
    }

    pub fn comm_level(&self) -> usize {
        self.comm_level
    }
}

impl<C: Curve> Circuit<C> {
    pub fn new() -> Self {
        Self::default()
    }

    /// Tries to add a gate to the circuit.
    ///
    /// This function validates the gate before adding the gate or fails otherwise.
    pub fn add_gate(&mut self, gate: Gate<C>) -> Result<GateIndex, CircuitError<C>> {
        self.validate_gate(&gate)?;

        let index = self.nb_gates();
        if index == GateIndex::MAX {
            return Err(CircuitError::CircuitTooBig);
        }

        let gate_output = self.comp_gate_output(&gate);
        let level = self.comp_gate_level(&gate);

        if gate.is_input() {
            self.inputs.push(index);
        }
        self.gates.push(GateExt::new(gate, gate_output?, level));

        Ok(index)
    }

    /// Tries to set a gate as circuit output.
    ///
    /// This function fails if there is no gate with the given index.
    pub fn add_output(&mut self, index: GateIndex) -> Result<(), CircuitError<C>> {
        if index < self.nb_gates() {
            self.outputs.push(index);
            Ok(())
        } else {
            Err(CircuitError::GateIndexOutOfBounds(index, self.nb_gates()))
        }
    }

    pub fn nb_gates(&self) -> GateIndex {
        self.gates.len() as GateIndex
    }

    pub fn nb_inputs(&self) -> GateIndex {
        self.inputs.len() as GateIndex
    }

    pub fn nb_outputs(&self) -> GateIndex {
        self.outputs.len() as GateIndex
    }

    /// Consumes the circuit and returns the list of gates.
    pub fn into_gates(self) -> Vec<GateExt<C>> {
        self.gates
    }

    pub fn iter_gates_ext(
        &self,
    ) -> impl ExactSizeIterator<Item = &GateExt<C>> + DoubleEndedIterator {
        self.gates.iter()
    }

    pub fn iter_gates(&self) -> impl ExactSizeIterator<Item = &Gate<C>> + DoubleEndedIterator {
        self.gates.iter().map(|g| &g.gate)
    }

    pub fn iter_output_indices(&self) -> impl ExactSizeIterator<Item = &GateIndex> {
        self.outputs.iter()
    }

    pub fn iter_input_indices(&self) -> impl ExactSizeIterator<Item = &GateIndex> {
        self.inputs.iter()
    }

    pub fn gate_ext(&self, index: GateIndex) -> Result<&GateExt<C>, CircuitError<C>> {
        if index < self.nb_gates() {
            Ok(&self.gates[index as usize])
        } else {
            Err(CircuitError::GateIndexOutOfBounds(index, self.nb_gates()))
        }
    }

    pub fn gate_ext_unchecked(&self, index: GateIndex) -> &GateExt<C> {
        &self.gates[index as usize]
    }

    pub fn gate(&self, index: GateIndex) -> Result<&Gate<C>, CircuitError<C>> {
        self.gate_ext(index).map(|g| &g.gate)
    }

    pub fn gate_unchecked(&self, index: GateIndex) -> &Gate<C> {
        &self.gate_ext_unchecked(index).gate
    }

    pub fn gate_output(&self, index: GateIndex) -> Result<GateOutput, CircuitError<C>> {
        self.gate_ext(index).map(|g| g.output)
    }

    pub fn gate_output_unchecked(&self, index: GateIndex) -> GateOutput {
        self.gate_ext_unchecked(index).output
    }

    pub fn gate_level(&self, index: GateIndex) -> Result<GateLevel, CircuitError<C>> {
        self.gate_ext(index).map(|g| g.level)
    }

    pub fn gate_level_unchecked(&self, index: GateIndex) -> GateLevel {
        self.gate_ext_unchecked(index).level
    }
}

macro_rules! check_algebraic_type {
    ($exp_type:expr, $found_type:expr) => {
        if $exp_type != $found_type {
            return Err(CircuitError::InvalidGateAlgebraicType {
                expected: $exp_type,
                found: $found_type,
            });
        }
    };
}

impl<C: Curve> Circuit<C> {
    /// Opens and outputs as scalar field a given gate
    pub fn open_and_output_scalar(&mut self, x: GateIndex) -> Result<(), CircuitError<C>> {
        check_algebraic_type!(AlgebraicType::ScalarField, self.gate_output(x)?.get_type());
        let opening_index = self.add_gate(Gate::FieldShareUnaryOp {
            x,
            op: FieldShareUnaryOp::Open,
        })?;
        self.add_output(opening_index)
    }

    /// Opens and outputs as base field a given gate
    pub fn open_and_output_base_field(&mut self, x: GateIndex) -> Result<(), CircuitError<C>> {
        check_algebraic_type!(AlgebraicType::BaseField, self.gate_output(x)?.get_type());
        let opening_index = self.add_gate(Gate::FieldShareUnaryOp {
            x,
            op: FieldShareUnaryOp::Open,
        })?;
        self.add_output(opening_index)
    }

    /// Opens and outputs as Mersenne107 a given gate
    pub fn open_and_output_mersenne107(&mut self, x: GateIndex) -> Result<(), CircuitError<C>> {
        check_algebraic_type!(AlgebraicType::Mersenne107, self.gate_output(x)?.get_type());
        let opening_index = self.add_gate(Gate::FieldShareUnaryOp {
            x,
            op: FieldShareUnaryOp::Open,
        })?;
        self.add_output(opening_index)
    }

    /// Opens and outputs as point a given gate
    pub fn open_and_output_point(&mut self, p: GateIndex) -> Result<(), CircuitError<C>> {
        check_algebraic_type!(AlgebraicType::Point, self.gate_output(p)?.get_type());
        let opening_index = self.add_gate(Gate::PointShareUnaryOp {
            p,
            op: PointShareUnaryOp::Open,
        })?;
        self.add_output(opening_index)
    }

    /// Opens and outputs as bit a given gate
    pub fn open_and_output_bit(&mut self, x: GateIndex) -> Result<(), CircuitError<C>> {
        check_algebraic_type!(AlgebraicType::Bit, self.gate_output(x)?.get_type());
        let opening_index = self.add_gate(Gate::BitShareUnaryOp {
            x,
            op: BitShareUnaryOp::Open,
        })?;
        self.add_output(opening_index)
    }
}

impl<C: Curve> Circuit<C> {
    /// Validates a gate.
    ///
    /// Checks that:
    ///     - gate inputs are present in the circuit
    ///     - gate input types correspond to the specification
    ///     - gate input batch sizes are compatible
    ///     - gate parameters are valid
    fn validate_gate(&self, gate: &Gate<C>) -> Result<(), CircuitError<C>> {
        macro_rules! check_op {
            ($msg:expr, $gate:expr => $($val1:expr, $op:tt, $val2:expr);+$(;)?) => {
                $(if !($val1 $op $val2) {
                    return Err(CircuitError::InvalidGate(
                        $gate.clone(),
                        format!("{}: {:?} {:?} {:?}", $msg, $val1, stringify!($op), $val2),
                    ));
                })+
            };
        }

        macro_rules! check_gate_properties {
            ($gate:expr, $($func:ident),* $(,)?) => {
                $(if !($gate.output.$func()) {
                    return Err(CircuitError::InvalidGate(
                        $gate.gate.clone(),
                        format!("{:?} fails - {}", $gate.output, stringify!($func)))); }
                )*
            };
        }

        match gate {
            Gate::Input(input) => {
                check_op!(
                    "input batch size must be non-zero",
                    gate =>
                    0, <, input.batch_size();
                );
            }
            Gate::Constant(constant) => {
                check_op!(
                    "constant batch size must be non-zero",
                    gate =>
                     0, <, constant.batch_size()?;
                );
            }
            Gate::Random { batch_size, .. } => {
                check_op!(
                    "random batch size must be non-zero",
                    gate =>
                     0, <, *batch_size;
                );
            }
            Gate::FieldShareUnaryOp { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_field, is_share);
            }
            Gate::FieldShareBinaryOp { x, y, .. } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                check_gate_properties!(gx, is_field, is_share);
                check_gate_properties!(gy, is_field);
                check_op!(
                    "inputs must have same batch-size and field type",
                    gate =>
                    gx.output.batch_size, ==, gy.output.batch_size;
                    gx.output.algebraic_type, ==, gy.output.algebraic_type
                );
            }
            Gate::BatchSummation { x } => {
                self.gate_ext(*x)?;
            }
            Gate::BitShareUnaryOp { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_bit, is_share);
            }
            Gate::BitShareBinaryOp { x, y, .. } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                check_gate_properties!(gx, is_bit, is_share);
                check_gate_properties!(gy, is_bit);
                check_op!(
                    "inputs must have same batch-size",
                    gate =>
                    gx.output.batch_size, ==, gy.output.batch_size
                );
            }
            Gate::PointShareUnaryOp { p: x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_point, is_share);
            }
            Gate::PointShareBinaryOp { p: x, y, op } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                if gx.output.is_plaintext() && gy.output.is_plaintext() {
                    return Err(CircuitError::InvalidGate(
                        gate.clone(),
                        "at least one input must be share".to_string(),
                    ));
                }
                check_gate_properties!(gx, is_point);
                match op {
                    PointShareBinaryOp::Add => {
                        check_gate_properties!(gy, is_point);
                    }
                    PointShareBinaryOp::ScalarMul => {
                        check_gate_properties!(gy, is_scalar_field);
                    }
                };
                check_op!(
                    "inputs must have same batch-size",
                    gate =>
                    gx.output.batch_size, ==, gy.output.batch_size
                );
            }
            Gate::FieldPlaintextUnaryOp { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_field, is_plaintext);
            }
            Gate::FieldPlaintextBinaryOp { x, y, .. } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                check_gate_properties!(gx, is_field, is_plaintext);
                check_gate_properties!(gy, is_field, is_plaintext);
                check_op!(
                    "inputs must have same field type",
                    gate =>
                    gx.output.algebraic_type, ==, gy.output.algebraic_type;
                    gx.output.batch_size, ==, gy.output.batch_size
                );
            }
            Gate::BitPlaintextUnaryOp { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_bit, is_plaintext);
            }
            Gate::BitPlaintextBinaryOp { x, y, .. } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                check_gate_properties!(gx, is_bit, is_plaintext);
                check_gate_properties!(gy, is_bit, is_plaintext);
                check_op!(
                    "inputs must have same batch-size",
                    gate =>
                    gx.output.batch_size, ==, gy.output.batch_size
                );
            }
            Gate::PointPlaintextUnaryOp { p: x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_point, is_plaintext);
            }
            Gate::PointPlaintextBinaryOp { p: x, y, op } => {
                let (gx, gy) = (self.gate_ext(*x)?, self.gate_ext(*y)?);
                check_gate_properties!(gx, is_point, is_plaintext);
                match op {
                    PointPlaintextBinaryOp::Add => {
                        check_gate_properties!(gy, is_point, is_plaintext);
                    }
                    PointPlaintextBinaryOp::ScalarMul => {
                        check_gate_properties!(gy, is_scalar_field, is_plaintext);
                    }
                }
                check_op!(
                    "inputs must have same batch-size",
                    gate =>
                    gx.output.batch_size, ==, gy.output.batch_size
                );
            }
            Gate::DaBit { batch_size, .. } => {
                check_op!(
                    "input batch size must be non-zero",
                    gate =>
                    0, <, *batch_size
                );
            }
            Gate::GetDaBitFieldShare { x, .. } => {
                // By convention, we suppose that the `DaBit` output is a field element
                check_gate_properties!(self.gate_ext(*x)?, is_field, is_share);
            }
            Gate::GetDaBitSharedBit { x, .. } => {
                // By convention, we suppose that the `DaBit` output is a field element
                check_gate_properties!(self.gate_ext(*x)?, is_field, is_share);
            }
            Gate::BaseFieldPow { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_base_field, is_share);
            }
            Gate::BitPlaintextToField { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_bit, is_plaintext);
            }
            Gate::FieldPlaintextToBit { x, .. } => {
                check_gate_properties!(self.gate_ext(*x)?, is_field, is_plaintext);
            }
            Gate::ExtractFromBatch { x, slice, .. } => {
                let gx = self.gate_ext(*x)?;
                if slice.is_empty() {
                    return Err(CircuitError::InvalidGate(
                        gate.clone(),
                        format!("slice must be non-empty: {slice:?}"),
                    ));
                }
                if slice.get_indices()
                    .into_iter()
                    .max()
                    .expect("non-empty slice expected") // never fails as we check that the slice is non-empty
                    >= gx.output.batch_size
                {
                    return Err(CircuitError::InvalidGate(
                        gate.clone(),
                        format!("slice indices out-of-range: {slice:?}"),
                    ));
                }
            }
            Gate::CollectToBatch { wires } => {
                check_op!("expected at least one input", gate => 0, <, wires.len());
                let first = self.gate_ext(wires[0])?.output;
                for x in wires.iter().skip(1) {
                    let gx = self.gate_ext(*x)?.output;
                    check_op!(
                        "all inputs must have the same type",
                        gate =>
                        first.algebraic_type, ==, gx.algebraic_type;
                        first.form, ==, gx.form
                    );
                }
            }
            Gate::PointFromPlaintextExtendedEdwards { wires } => {
                check_op!("expected exactly 4 inputs", gate => wires.len(), ==, 4);
                for x in wires {
                    let gx = self.gate_ext(*x)?;
                    check_gate_properties!(gx, is_base_field, is_plaintext);
                    check_op!("expected batch-size 1", gate => gx.output.batch_size, ==, 1);
                }
            }
            Gate::PlaintextPointToExtendedEdwards { point: x, .. } => {
                let gx = self.gate_ext(*x)?;
                check_gate_properties!(gx, is_point, is_plaintext);
                check_op!("expected batch-size 1", gate => gx.output.batch_size, ==, 1);
            }
            Gate::PlaintextKeccakF1600 { x } => {
                let gx = self.gate_ext(*x)?;
                check_gate_properties!(gx, is_bit, is_plaintext);
                check_op!("expected batch-size 1600", gate => gx.output.batch_size, ==, 1600);
            }
            Gate::CompressPlaintextPoint { point: x, .. } => {
                let gx = self.gate_ext(*x)?;
                check_gate_properties!(gx, is_point, is_plaintext);
                check_op!("expected batch-size 1", gate => gx.output.batch_size, ==, 1);
            }
            Gate::KeyRecoveryPlaintextComputeErrors {
                d_minus_one,
                syndromes,
            } => {
                let g1 = self.gate_ext(*d_minus_one)?;
                let g2 = self.gate_ext(*syndromes)?;
                check_gate_properties!(g1, is_base_field, is_plaintext);
                check_gate_properties!(g2, is_base_field, is_plaintext);

                check_op!("expected batch-size 1", gate => g1.output.batch_size, ==, 1);
                // TODO: Check that the batch size of `g2` is correct.
                check_op!(format!("expected batch-size {}", MXE_KEY_RECOVERY_D - 1),
                    gate => g2.output.batch_size, ==, MXE_KEY_RECOVERY_D as u32 - 1);
            }
        }

        Ok(())
    }

    /// Computes the output type of gate.
    ///
    /// **Note: ** This function can panic if the gate is not valid.
    fn comp_gate_output(&self, gate: &Gate<C>) -> Result<GateOutput, CircuitError<C>> {
        let r = match gate {
            Gate::Input(input_type) => GateOutput {
                batch_size: input_type.batch_size(),
                algebraic_type: input_type.algebraic_type(),
                form: input_type.share_or_plaintext(),
            },

            Gate::Constant(const_type) => GateOutput {
                batch_size: const_type.batch_size()?,
                algebraic_type: const_type.algebraic_type(),
                form: ShareOrPlaintext::Plaintext,
            },

            Gate::Random {
                algebraic_type,
                batch_size,
            } => GateOutput {
                batch_size: *batch_size,
                algebraic_type: *algebraic_type,
                form: ShareOrPlaintext::Share,
            },

            Gate::FieldShareUnaryOp { x, op } => match op {
                FieldShareUnaryOp::Neg | FieldShareUnaryOp::MulInverse => {
                    self.gate_output_unchecked(*x)
                }
                FieldShareUnaryOp::Open | FieldShareUnaryOp::IsZero => self
                    .gate_output_unchecked(*x)
                    .with_new_form(ShareOrPlaintext::Plaintext),
            },

            Gate::FieldShareBinaryOp { x, .. }
            | Gate::BitShareBinaryOp { x, .. }
            | Gate::FieldPlaintextUnaryOp { x, .. }
            | Gate::FieldPlaintextBinaryOp { x, .. }
            | Gate::BitPlaintextUnaryOp { x, .. }
            | Gate::BitPlaintextBinaryOp { x, .. }
            | Gate::PointPlaintextUnaryOp { p: x, .. }
            | Gate::PointPlaintextBinaryOp { p: x, .. }
            | Gate::GetDaBitFieldShare { x, .. }
            | Gate::BaseFieldPow { x, .. } => self.gate_output_unchecked(*x),

            Gate::BatchSummation { x, .. } => self.gate_output_unchecked(*x).with_new_batch_size(1),

            Gate::PointShareBinaryOp { p: x, .. } => self
                .gate_output_unchecked(*x)
                .with_new_form(ShareOrPlaintext::Share),

            Gate::BitShareUnaryOp { x, op } => match op {
                BitShareUnaryOp::Not => self.gate_output_unchecked(*x),
                BitShareUnaryOp::Open => self
                    .gate_output_unchecked(*x)
                    .with_new_form(ShareOrPlaintext::Plaintext),
            },

            Gate::PointShareUnaryOp { p: x, op } => match op {
                PointShareUnaryOp::Neg => self.gate_output_unchecked(*x),
                PointShareUnaryOp::Open => self
                    .gate_output_unchecked(*x)
                    .with_new_form(ShareOrPlaintext::Plaintext),
                PointShareUnaryOp::IsZero => self
                    .gate_output_unchecked(*x)
                    .with_new_form(ShareOrPlaintext::Plaintext)
                    .with_new_type(AlgebraicType::ScalarField),
            },

            Gate::DaBit {
                field_type,
                batch_size,
            } => GateOutput {
                batch_size: *batch_size,
                algebraic_type: AlgebraicType::from(*field_type),
                form: ShareOrPlaintext::Share,
            },

            Gate::GetDaBitSharedBit { x, .. } => self
                .gate_output_unchecked(*x)
                .with_new_type(AlgebraicType::Bit),

            Gate::BitPlaintextToField { x, field_type } => self
                .gate_output_unchecked(*x)
                .with_new_type(AlgebraicType::from(*field_type)),

            Gate::FieldPlaintextToBit { x } => self
                .gate_output_unchecked(*x)
                .with_new_type(AlgebraicType::Bit),

            Gate::ExtractFromBatch { x, slice } => self
                .gate_output_unchecked(*x)
                .with_new_batch_size(slice.len()),

            Gate::CollectToBatch { wires, .. } => {
                let batch_size = wires
                    .iter()
                    .map(|x| self.gate_output_unchecked(*x).batch_size)
                    .sum();
                self.gate_output_unchecked(wires[0])
                    .with_new_batch_size(batch_size)
            }

            Gate::PointFromPlaintextExtendedEdwards { .. } => GateOutput {
                algebraic_type: AlgebraicType::Point,
                form: ShareOrPlaintext::Plaintext,
                batch_size: 1,
            },
            Gate::PlaintextPointToExtendedEdwards { .. } => GateOutput {
                algebraic_type: AlgebraicType::BaseField,
                form: ShareOrPlaintext::Plaintext,
                batch_size: 4,
            },
            Gate::PlaintextKeccakF1600 { .. } => GateOutput {
                algebraic_type: AlgebraicType::Bit,
                form: ShareOrPlaintext::Plaintext,
                batch_size: 1600,
            },
            Gate::CompressPlaintextPoint { .. } => GateOutput {
                algebraic_type: AlgebraicType::Bit,
                form: ShareOrPlaintext::Plaintext,
                batch_size: 256,
            },
            Gate::KeyRecoveryPlaintextComputeErrors { .. } => GateOutput {
                algebraic_type: AlgebraicType::BaseField,
                form: ShareOrPlaintext::Plaintext,
                batch_size: MXE_KEY_RECOVERY_N as u32,
            },
        };

        Ok(r)
    }

    /// Computes the number of rounds required to evaluate the gate.
    ///
    /// **Note: ** This function can panic if the gate is not valid.
    fn comp_gate_comm_rounds(&self, gate: &Gate<C>) -> usize {
        match gate {
            Gate::Input(input_type) => match input_type {
                Input::SecretPlaintext { .. } => 1,
                _ => 0,
            },

            Gate::Constant(_) | Gate::Random { .. } => 0,

            Gate::FieldShareUnaryOp { op, .. } => match op {
                FieldShareUnaryOp::Neg => 0,
                FieldShareUnaryOp::MulInverse => 2,
                FieldShareUnaryOp::Open => 1,
                FieldShareUnaryOp::IsZero => 2,
            },
            Gate::FieldShareBinaryOp { op, y, .. } => {
                match (op, self.gate_output_unchecked(*y).form) {
                    (FieldShareBinaryOp::Mul, ShareOrPlaintext::Share) => 1,
                    (FieldShareBinaryOp::Mul, ShareOrPlaintext::Plaintext)
                    | (FieldShareBinaryOp::Add, _) => 0,
                }
            }
            Gate::BatchSummation { .. } => 0,
            Gate::BitShareUnaryOp { op, .. } => match op {
                BitShareUnaryOp::Not => 0,
                BitShareUnaryOp::Open => 1,
            },
            Gate::BitShareBinaryOp { op, y, .. } => {
                match (op, self.gate_output_unchecked(*y).form) {
                    (BitShareBinaryOp::Xor, _) => 0,
                    (_, ShareOrPlaintext::Share) => 1,
                    (_, ShareOrPlaintext::Plaintext) => 0,
                }
            }
            Gate::PointShareUnaryOp { op, .. } => match op {
                PointShareUnaryOp::Neg => 0,
                PointShareUnaryOp::Open => 1,
                PointShareUnaryOp::IsZero => 2,
            },
            Gate::PointShareBinaryOp { y, op, .. } => {
                match (op, self.gate_output_unchecked(*y).form) {
                    (PointShareBinaryOp::Add, _) => 0,
                    (PointShareBinaryOp::ScalarMul, ShareOrPlaintext::Share) => 1,
                    (PointShareBinaryOp::ScalarMul, ShareOrPlaintext::Plaintext) => 0,
                }
            }

            Gate::BaseFieldPow { .. } => 2,

            Gate::FieldPlaintextUnaryOp { .. }
            | Gate::FieldPlaintextBinaryOp { .. }
            | Gate::BitPlaintextUnaryOp { .. }
            | Gate::BitPlaintextBinaryOp { .. }
            | Gate::PointPlaintextUnaryOp { .. }
            | Gate::PointPlaintextBinaryOp { .. }
            | Gate::DaBit { .. }
            | Gate::GetDaBitFieldShare { .. }
            | Gate::GetDaBitSharedBit { .. }
            | Gate::BitPlaintextToField { .. }
            | Gate::FieldPlaintextToBit { .. }
            | Gate::ExtractFromBatch { .. }
            | Gate::CollectToBatch { .. }
            | Gate::PointFromPlaintextExtendedEdwards { .. }
            | Gate::PlaintextPointToExtendedEdwards { .. }
            | Gate::PlaintextKeccakF1600 { .. }
            | Gate::CompressPlaintextPoint { .. }
            | Gate::KeyRecoveryPlaintextComputeErrors { .. } => 0,
        }
    }

    /// Computes the communication level of the gate.
    ///
    /// **Note: ** This function can panic if the gate is not valid.
    fn comp_gate_level(&self, gate: &Gate<C>) -> GateLevel {
        let comm_rounds = self.comp_gate_comm_rounds(gate);
        match gate
            .get_inputs()
            .iter()
            .map(|pred| self.gate_level_unchecked(*pred))
            .max()
        {
            None => GateLevel::default(),
            Some(preds_level) => preds_level.next(comm_rounds),
        }
    }
}

#[cfg(test)]
mod tests {
    use primitives::algebra::elliptic_curve::Curve25519Ristretto as C;

    use crate::circuit::{AlgebraicType, Circuit, FieldShareBinaryOp, Gate, Input};

    #[test]
    fn test_circuit_new() {
        let mut circuit = Circuit::<C>::new();

        let x = circuit
            .add_gate(Gate::Input(Input::SecretPlaintext {
                inputer: 0,
                algebraic_type: AlgebraicType::Mersenne107,
                batch_size: 3,
            }))
            .unwrap();

        let y = circuit
            .add_gate(Gate::Input(Input::SecretPlaintext {
                inputer: 0,
                algebraic_type: AlgebraicType::Mersenne107,
                batch_size: 3,
            }))
            .unwrap();

        let z = circuit
            .add_gate(Gate::FieldShareBinaryOp {
                x,
                y,
                op: FieldShareBinaryOp::Mul,
            })
            .unwrap();

        circuit.add_output(z).unwrap();

        assert_eq!(circuit.nb_inputs(), 2);
        assert_eq!(circuit.nb_gates(), 2 + 1);
        assert_eq!(circuit.nb_outputs(), 1);
    }
}