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
//! Executor for a generic protocol.
use serde::{Deserialize, Serialize};
#[cfg(debug_assertions)]
use std::collections::HashSet;
use std::error::Error;
use std::fmt::Debug;
use std::future::Future;
use std::time::Instant;
use std::{iter, mem, vec};

use seec_channel::{Receiver, Sender};
use tracing::{debug, error, info, instrument, trace};

use crate::circuit::builder::SubCircuitGate;
use crate::circuit::{CircuitId, DefaultIdx, ExecutableCircuit, GateIdx};
use crate::errors::ExecutorError;
use crate::gate::base::BaseGate;
use crate::protocols::boolean_gmw::BooleanGmw;
use crate::protocols::{
    ErasedError, FunctionDependentSetup, Gate, Protocol, Share, ShareStorage, SimdShareOf,
};
use crate::utils::BoxError;

pub type BoolGmwExecutor<'c> = Executor<'c, BooleanGmw, DefaultIdx>;

pub struct Executor<'c, P: Protocol, Idx> {
    circuit: &'c ExecutableCircuit<P::Plain, P::Gate, Idx>,
    protocol_state: P,
    gate_outputs: GateOutputs<P::ShareStorage>,
    party_id: usize,
    setup: DynFDSetup<'c, P, Idx>,
}

pub type DynFDSetup<'c, P, Idx> =
    Box<dyn FunctionDependentSetup<P, Idx, Error = BoxError> + Send + 'c>;

#[derive(Debug, Clone)]
pub struct GateOutputs<Shares> {
    data: Vec<Input<Shares>>,
    // Used as a sanity check in debug builds. Stores for which gates we have set the output,
    // so that we can check if an output is set before accessing it.
    #[cfg(debug_assertions)]
    output_set: HashSet<SubCircuitGate<usize>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Input<Shares> {
    Scalar(Shares),
    Simd(Vec<Shares>),
}

pub type Output<Shares> = Input<Shares>;

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct ExecutorMsg<Msg, SimdMsg> {
    scalar: Msg,
    simd: Option<SimdMsg>,
}

pub type Message<P> = ExecutorMsg<<P as Protocol>::Msg, <P as Protocol>::SimdMsg>;

impl<'c, P, Idx> Executor<'c, P, Idx>
where
    P: Protocol + Default,
    Idx: GateIdx,
    P::Share: Share<SimdShare = P::ShareStorage>,
{
    // for some reason the manual future desugaring is needed here...
    // the send problem of async is so annoying...
    #[allow(clippy::manual_async_fn)]
    pub fn new<
        // FDError, // this little hack is needed to work around https://github.com/rust-lang/rust/issues/102211#issuecomment-1513931928
        FDSetup,
    >(
        circuit: &'c ExecutableCircuit<P::Plain, P::Gate, Idx>,
        party_id: usize,
        setup: FDSetup,
    ) -> impl Future<Output = Result<Executor<'c, P, Idx>, ExecutorError>> + Send
    where
        FDSetup: FunctionDependentSetup<P, Idx> + Send + 'c,
        FDSetup::Error: Error + Send + Sync + 'static,
    {
        async move { Self::new_with_state(P::default(), circuit, party_id, setup).await }
    }
}

// TODO Bug: There is currently a synchronization bug which can result in the last message
//  being dropped before sending. This occurs if the whole program terminates before the last
//  message is sent. One option to fix this would be to add an explicit synchronization msg
//  whose absence only results in a warning but no incorrect behaviour
impl<'c, P, Idx> Executor<'c, P, Idx>
where
    P: Protocol,
    Idx: GateIdx,
    P::Share: Share<SimdShare = P::ShareStorage>,
{
    pub async fn new_with_state<FDSetup>(
        mut protocol_state: P,
        circuit: &'c ExecutableCircuit<P::Plain, P::Gate, Idx>,
        party_id: usize,
        mut setup: FDSetup,
    ) -> Result<Executor<'c, P, Idx>, ExecutorError>
    where
        // FDError: Error + Send + Sync + 'static,
        FDSetup: FunctionDependentSetup<P, Idx> + Send + 'c,
        FDSetup::Error: Error + Send + Sync + 'static,
    {
        let gate_outputs = protocol_state.setup_gate_outputs(party_id, circuit);
        setup
            .setup(&gate_outputs, circuit)
            .await
            .map_err(|err| ExecutorError::Setup(BoxError::from_err(err)))?;
        let setup = Box::new(ErasedError(setup));
        Ok(Self {
            circuit,
            protocol_state,
            gate_outputs,
            party_id,
            setup,
        })
    }

    #[tracing::instrument(skip_all, fields(party_id = self.party_id), err)]
    pub async fn execute(
        &mut self,
        inputs: Input<P::ShareStorage>,
        sender: &mut Sender<Message<P>>,
        receiver: &mut Receiver<Message<P>>,
    ) -> Result<Output<P::ShareStorage>, ExecutorError> {
        info!("Executing circuit");
        if inputs.should_debug() {
            debug!(?inputs);
        } else {
            debug!("Inputs too large for debug printing. Use trace if necessary.");
            trace!(?inputs);
        }
        let now = Instant::now();
        let inp_len = match &inputs {
            Input::Scalar(shares) => shares.len(),
            Input::Simd(shares) => shares.len(),
        };

        assert_eq!(
            self.circuit.input_count(),
            inp_len,
            "Length of inputs must be equal to circuit input size"
        );
        let mut layer_count = 0;
        let mut interactive_count = 0;
        let main_is_simd = self.circuit.simd_size(0).is_some();
        // TODO provide the option to calculate next layer  during and communication
        //  take care to not block tokio threads -> use tokio rayon
        for layer in self.circuit.layer_iter() {
            for ((gate, sc_gate_id), mut parents) in
                layer.non_interactive_with_parents_iter(self.circuit)
            {
                trace!(?gate, ?sc_gate_id, "Evaluating");

                match gate.as_base_gate() {
                    Some(BaseGate::Input(_)) => {
                        assert_eq!(
                            sc_gate_id.circuit_id, 0,
                            "Input gate in SubCircuit. Use SubCircuitInput"
                        );
                        // TODO, ugh log(n) in loop... and i'm not even sure if this is correct
                        let inp_idx = self
                            .circuit
                            .input_gates()
                            .binary_search(&sc_gate_id.gate_id)
                            .expect("Input gate not contained in input_gates");
                        if main_is_simd {
                            let output = self.protocol_state.evaluate_non_interactive_simd(
                                self.party_id,
                                &gate,
                                iter::once(
                                    &inputs.as_simd().expect("main circ is simd but input not")
                                        [inp_idx],
                                ),
                            );
                            trace!(
                                ?output,
                                sc_gate_id = %sc_gate_id,
                                "Evaluated SIMD {:?} gate",
                                gate
                            );
                            self.gate_outputs.set_simd(sc_gate_id, output);
                        } else {
                            let output = self.protocol_state.evaluate_non_interactive(
                                self.party_id,
                                &gate,
                                iter::once(
                                    inputs
                                        .as_scalar()
                                        .expect("main circ is scalar but input is simd")
                                        .get(inp_idx),
                                ),
                            );
                            trace!(
                                ?output,
                                sc_gate_id = %sc_gate_id,
                                "Evaluated {:?} gate",
                                gate
                            );
                            self.gate_outputs.set(sc_gate_id, output);
                        }
                    }
                    Some(BaseGate::SubCircuitInput(_)) => {
                        let simd_size = self.circuit.simd_size(sc_gate_id.circuit_id);
                        match (main_is_simd, simd_size.is_some()) {
                            (true, true) => {
                                // simd to siimd
                                let inputs = self.simd_inputs(parents);
                                let simd_output = self
                                    .protocol_state
                                    .evaluate_non_interactive_simd(self.party_id, &gate, inputs);
                                trace!(
                                    ?simd_output,
                                    sc_gate_id = %sc_gate_id,
                                    "Evaluated SIMD {:?} gate",
                                    gate
                                );
                                self.gate_outputs.set_simd(sc_gate_id, simd_output);
                            }
                            (false, true) => {
                                // non-simd to simd
                                let output = self.inputs(parents).collect();
                                trace!(
                                    ?output,
                                    sc_gate_id = %sc_gate_id,
                                    "Evaluated {:?} gate",
                                    gate
                                );
                                self.gate_outputs.set_simd(sc_gate_id, output);
                            }
                            (false, false) => {
                                // non-simd to non-simd
                                let inputs = self.inputs(parents);
                                let output = self.protocol_state.evaluate_non_interactive(
                                    self.party_id,
                                    &gate,
                                    inputs,
                                );
                                trace!(
                                    ?output,
                                    sc_gate_id = %sc_gate_id,
                                    "Evaluated {:?} gate",
                                    gate
                                );
                                self.gate_outputs.set(sc_gate_id, output);
                            }
                            (true, false) => {
                                // simd to non-simd is illegal
                                return Err(ExecutorError::IllegalCircuit);
                            }
                        }
                    }
                    Some(BaseGate::ConnectToMainFromSimd((_, select))) => {
                        let input = self
                            .gate_outputs
                            .get_simd(parents.next().expect("Missing input"));
                        let output = input.get(*select as usize);
                        trace!(
                            ?output,
                            sc_gate_id = %sc_gate_id,
                            "Evaluated {:?} gate",
                            gate
                        );
                        self.gate_outputs.set(sc_gate_id, output);
                        continue;
                    }
                    other => {
                        let simd_size = self.circuit.simd_size(sc_gate_id.circuit_id);
                        if let Some(simd_size) = simd_size {
                            let output = if let Some(BaseGate::Constant(c)) = other {
                                // get unchecked because it was not set from a gate evaluation
                                // before. However, this value might have been initialized in
                                // setup_gate_outputs
                                let current_out = self.gate_outputs.get_simd_unchecked(sc_gate_id);
                                self.protocol_state.share_constant_simd(
                                    self.party_id,
                                    current_out,
                                    c.clone(),
                                    simd_size,
                                )
                            } else {
                                let inputs = self.simd_inputs(parents);
                                self.protocol_state.evaluate_non_interactive_simd(
                                    self.party_id,
                                    &gate,
                                    inputs,
                                )
                            };

                            trace!(
                                ?output,
                                sc_gate_id = %sc_gate_id,
                                "Evaluated SIMD {:?} gate",
                                gate
                            );
                            self.gate_outputs.set_simd(sc_gate_id, output);
                        } else {
                            let output = if let Some(BaseGate::Constant(c)) = other {
                                // get unchecked because it was not set from a gate evaluation
                                // before. However, this value might have been initialized in
                                // setup_gate_outputs
                                let current_out = self.gate_outputs.get_unchecked(sc_gate_id);
                                self.protocol_state.share_constant(
                                    self.party_id,
                                    current_out,
                                    c.clone(),
                                )
                            } else {
                                let inputs = self.inputs(parents);
                                self.protocol_state.evaluate_non_interactive(
                                    self.party_id,
                                    &gate,
                                    inputs,
                                )
                            };
                            trace!(
                                ?output,
                                sc_gate_id = %sc_gate_id,
                                "Evaluated {:?} gate",
                                gate
                            );
                            self.gate_outputs.set(sc_gate_id, output);
                        }
                    }
                };
            }

            let layer_int_cnt = layer.interactive_count_times_simd();
            if layer_int_cnt == 0 {
                trace!("Layer has no interactive gates. Current layer count {layer_count:?}");
                // If the layer does not contain and gates we continue
                continue;
            }
            // Only count layers with and gates
            layer_count += 1;
            interactive_count += layer_int_cnt;

            let mut setup_storage = self
                .setup
                .request_setup_output(layer_int_cnt)
                .await
                .unwrap();

            let (scalar, simd) = layer.split_simd();

            let scalar_gate_iter = scalar.interactive_gates().flatten().cloned();
            // interactive_parents_iter is !Send so we introduce a block s.t. it is not hold
            // over .await
            let scalar_msg = {
                let scalar_output_iter = scalar.interactive_indices().flat_map(|(sc, gate_ids)| {
                    let this = &*self;
                    gate_ids.iter().map(move |gate_id| {
                        this.gate_outputs
                            .get_unchecked(SubCircuitGate::new(sc, *gate_id))
                    })
                });
                let input_iter = scalar
                    .interactive_parents_iter(self.circuit)
                    .flat_map(|parents| self.inputs(parents));
                self.protocol_state.compute_msg(
                    self.party_id,
                    scalar_gate_iter.clone(),
                    scalar_output_iter,
                    input_iter,
                    &mut setup_storage,
                )
            };

            let simd_gate_iter = simd.interactive_gates().flatten().cloned();
            // interactive_parents_iter is !Send so we introduce a block s.t. it is not hold
            // over .await
            let simd_msg = P::SIMD_SUPPORT.then(|| {
                let simd_output_iter = simd.interactive_indices().flat_map(|(sc, gate_ids)| {
                    let this = &*self;
                    gate_ids.iter().map(move |gate_id| {
                        this.gate_outputs
                            .get_simd_unchecked(SubCircuitGate::new(sc, *gate_id))
                    })
                });
                let input_iter = simd
                    .interactive_parents_iter(self.circuit)
                    .flat_map(|parents| parents.map(|parent| self.gate_outputs.get_simd(parent)));
                self.protocol_state.compute_msg_simd(
                    self.party_id,
                    simd_gate_iter.clone(),
                    simd_output_iter,
                    input_iter,
                    &mut setup_storage,
                )
            });
            let msg = ExecutorMsg {
                scalar: scalar_msg.clone(),
                simd: simd_msg.clone(),
            };
            sender.send(msg).await.ok().unwrap();
            for gate in simd.freeable_simd_gates() {
                match &mut self.gate_outputs.data[gate.circuit_id as usize] {
                    Input::Scalar(_) => {
                        error!("BUG in freeable_simd_gates, please report this.")
                    }
                    Input::Simd(shares) => {
                        // take the vec element, which is likely some kind of vec
                        // for a simd share, and thus, free it
                        mem::take(&mut shares[gate.gate_id.as_usize()]);
                    }
                }
            }
            debug!("Sending interactive gates layer");
            let ExecutorMsg {
                scalar: resp_scalar,
                simd: resp_simd,
            } = receiver.recv().await.ok().unwrap().unwrap();

            // recreate iters afer .await point, for some reason holding them over that
            // results in a weird compile error. The iterators are Send, but if held over .await
            // the future is not... Seems like a compiler bug
            let scalar_output_iter = scalar.interactive_indices().flat_map(|(sc, gate_ids)| {
                let this = &*self;
                gate_ids.iter().map(move |gate_id| {
                    this.gate_outputs
                        .get_unchecked(SubCircuitGate::new(sc, *gate_id))
                })
            });
            let simd_output_iter = simd.interactive_indices().flat_map(|(sc, gate_ids)| {
                let this = &*self;
                gate_ids.iter().map(move |gate_id| {
                    this.gate_outputs
                        .get_simd_unchecked(SubCircuitGate::new(sc, *gate_id))
                })
            });

            let scalar_interactive_outputs = self.protocol_state.evaluate_interactive(
                self.party_id,
                scalar_gate_iter,
                scalar_output_iter,
                scalar_msg,
                resp_scalar,
                &mut setup_storage,
            );
            let simd_interactive_outputs = match (simd_msg, resp_simd) {
                (Some(simd_msg), Some(resp_simd)) => {
                    Some(self.protocol_state.evaluate_interactive_simd(
                        self.party_id,
                        simd_gate_iter,
                        simd_output_iter,
                        simd_msg,
                        resp_simd,
                        &mut setup_storage,
                    ))
                }
                (Some(_), None) | (None, Some(_)) => panic!("Sent and received simd msg differ"),
                (None, None) => None,
            };

            scalar
                .interactive_iter()
                .zip(scalar_interactive_outputs)
                .for_each(|((_, id), out)| {
                    self.gate_outputs.set(id, out.clone());
                    trace!(?out, gate_id = %id, "Evaluated interactive gate");
                });
            if let Some(simd_interactive_outputs) = simd_interactive_outputs {
                simd.interactive_iter()
                    .zip(simd_interactive_outputs)
                    .for_each(|((_, id), out)| {
                        self.gate_outputs.set_simd(id, out.clone());
                        trace!(?out, gate_id = %id, "Evaluated SIMD interactive gate");
                    });
            }
        }
        info!(
            layer_count,
            interactive_count,
            execution_time_s = now.elapsed().as_secs_f32()
        );

        let out_iter = self.circuit.output_gates().iter();
        if main_is_simd {
            let output_iter = out_iter.map(|id| {
                self.gate_outputs
                    .get_simd(SubCircuitGate::new(0, *id))
                    .clone()
            });
            Ok(Input::Simd(output_iter.collect()))
        } else {
            let output_iter = out_iter.map(|id| self.gate_outputs.get(SubCircuitGate::new(0, *id)));
            Ok(Input::Scalar(output_iter.collect()))
        }
    }

    pub fn gate_outputs(&self) -> &GateOutputs<P::ShareStorage> {
        &self.gate_outputs
    }

    pub fn setup_storage(&self) -> &P::SetupStorage {
        // &self.setup_storage
        todo!()
    }

    fn inputs<'s, 'p>(
        &'s self,
        parent_ids: impl Iterator<Item = SubCircuitGate<Idx>> + 'p,
    ) -> impl Iterator<Item = P::Share> + 'p
    where
        's: 'p,
    {
        parent_ids.map(move |parent_id| self.gate_outputs.get(parent_id))
    }

    fn simd_inputs<'s, 'p>(
        &'s self,
        parent_ids: impl Iterator<Item = SubCircuitGate<Idx>> + 'p,
    ) -> impl Iterator<Item = &SimdShareOf<P::Share>> + 'p
    where
        's: 'p,
    {
        parent_ids.map(move |parent_id| self.gate_outputs.get_simd(parent_id))
    }
}

impl<Shares> GateOutputs<Shares> {
    pub fn get_sc(&self, id: CircuitId) -> &Input<Shares> {
        &self.data[id as usize]
    }

    pub fn iter(&self) -> impl Iterator<Item = &Input<Shares>> {
        self.data.iter()
    }
}

impl<Shares> Input<Shares> {
    pub fn as_scalar(&self) -> Option<&Shares> {
        match self {
            Input::Scalar(scalar) => Some(scalar),
            Input::Simd(_) => None,
        }
    }

    pub fn as_simd(&self) -> Option<&Vec<Shares>> {
        match self {
            Input::Scalar(_) => None,
            Input::Simd(shares) => Some(shares),
        }
    }

    pub fn into_scalar(self) -> Option<Shares> {
        match self {
            Input::Scalar(scalar) => Some(scalar),
            Input::Simd(_) => None,
        }
    }

    pub fn into_simd(self) -> Option<Vec<Shares>> {
        match self {
            Input::Scalar(_) => None,
            Input::Simd(shares) => Some(shares),
        }
    }

    fn should_debug<Sh>(&self) -> bool
    where
        Shares: ShareStorage<Sh>,
    {
        match self {
            Input::Scalar(shares) if shares.len() <= 1024 => true,
            Input::Simd(simd_shares) if simd_shares.len() <= 256 => true,
            _ => false,
        }
    }
}

impl<Shares: Clone> GateOutputs<Shares> {
    pub fn new(data: Vec<Input<Shares>>) -> Self {
        Self {
            data,
            #[cfg(debug_assertions)]
            output_set: HashSet::new(),
        }
    }

    #[instrument(ret, level = "trace", skip(self))]
    pub fn get<Share: Debug, Idx: GateIdx>(&self, id: SubCircuitGate<Idx>) -> Share
    where
        Shares: ShareStorage<Share>,
    {
        #[cfg(debug_assertions)]
        assert!(
            self.output_set.contains(&id.into_usize()),
            "gate {id} not evaluated",
        );
        self.get_unchecked(id)
    }

    pub fn get_unchecked<Share, Idx: GateIdx>(&self, id: SubCircuitGate<Idx>) -> Share
    where
        Shares: ShareStorage<Share>,
    {
        match &self.data[id.circuit_id as usize] {
            Input::Scalar(data) => data.get(id.gate_id.as_usize()),
            Input::Simd(_) => {
                panic!("Called GateOutputs::get({id:?}) for Simd circ")
            }
        }
    }

    pub fn get_simd<Idx: GateIdx>(&self, id: SubCircuitGate<Idx>) -> &Shares {
        #[cfg(debug_assertions)]
        assert!(
            self.output_set.contains(&id.into_usize()),
            "SIMD parent {id} not set",
        );
        self.get_simd_unchecked(id)
    }

    pub fn get_simd_unchecked<Idx: GateIdx>(&self, id: SubCircuitGate<Idx>) -> &Shares {
        match &self.data[id.circuit_id as usize] {
            Input::Scalar(_) => {
                panic!("Called GateOutputs::get_simd({id:?}) for scalar circ")
            }
            Input::Simd(data) => &data[id.gate_id.as_usize()],
        }
    }

    pub fn set<Share, Idx: GateIdx>(&mut self, id: SubCircuitGate<Idx>, val: Share)
    where
        Shares: ShareStorage<Share>,
    {
        #[cfg(debug_assertions)]
        self.output_set.insert(id.into_usize());
        match &mut self.data[id.circuit_id as usize] {
            Input::Scalar(data) => data.set(id.gate_id.as_usize(), val),
            Input::Simd(_) => {
                panic!("Called GateOutputs::set for Simd circ")
            }
        }
    }

    pub fn set_simd<Idx: GateIdx>(&mut self, id: SubCircuitGate<Idx>, val: Shares) {
        #[cfg(debug_assertions)]
        self.output_set.insert(id.into_usize());
        match &mut self.data[id.circuit_id as usize] {
            Input::Scalar(_) => {
                panic!("Called GateOutputs::set_simd for scalar circ")
            }
            Input::Simd(data) => {
                data[id.gate_id.as_usize()] = val;
            }
        }
    }
}

impl<S> Default for GateOutputs<S> {
    fn default() -> Self {
        Self {
            data: vec![],
            output_set: Default::default(),
        }
    }
}

impl<Shares> IntoIterator for GateOutputs<Shares> {
    type Item = Output<Shares>;
    type IntoIter = vec::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        self.data.into_iter()
    }
}

impl<Shares> FromIterator<Input<Shares>> for GateOutputs<Shares> {
    fn from_iter<T: IntoIterator<Item = Input<Shares>>>(iter: T) -> Self {
        Self {
            data: iter.into_iter().collect(),
            output_set: Default::default(),
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::gate::base::BaseGate;
    use anyhow::Result;
    use bitvec::{bitvec, prelude::Lsb0};
    use tracing::debug;

    use crate::circuit::{BaseCircuit, DefaultIdx, ExecutableCircuit};
    use crate::common::BitVec;
    use crate::private_test_utils::{create_and_tree, execute_circuit, init_tracing, TestChannel};
    use crate::protocols::boolean_gmw::BooleanGmw;
    use crate::protocols::ScalarDim;
    use crate::secret::{inputs, Secret};
    use crate::{BooleanGate, Circuit, CircuitBuilder};

    #[tokio::test]
    async fn execute_simple_circuit() -> Result<()> {
        let _guard = init_tracing();
        use crate::protocols::boolean_gmw::BooleanGate::*;
        let mut circuit: BaseCircuit = BaseCircuit::new();
        let in_1 = circuit.add_gate(Base(BaseGate::Input(ScalarDim)));
        let in_2 = circuit.add_gate(Base(BaseGate::Input(ScalarDim)));
        let and_1 = circuit.add_wired_gate(And, &[in_1, in_2]);
        let xor_1 = circuit.add_wired_gate(Xor, &[in_2, and_1]);
        let and_2 = circuit.add_wired_gate(And, &[and_1, xor_1]);
        circuit.add_wired_gate(Base(BaseGate::Output(ScalarDim)), &[and_2]);

        let inputs = [BitVec::repeat(true, 2), BitVec::repeat(false, 2)];
        let out = execute_circuit::<BooleanGmw, _, _>(
            &ExecutableCircuit::DynLayers(circuit.into()),
            inputs,
            TestChannel::InMemory,
        )
        .await?;
        assert_eq!(1, out.len());
        assert!(!out[0]);
        Ok(())
    }

    #[tokio::test]
    async fn eval_and_tree() -> Result<()> {
        let _guard = init_tracing();
        let and_tree = create_and_tree(10);
        let inputs_0 = {
            let mut bits = BitVec::new();
            bits.resize(and_tree.input_count(), true);
            bits
        };
        let inputs_1 = !inputs_0.clone();
        let out = execute_circuit::<BooleanGmw, _, _>(
            &ExecutableCircuit::DynLayers(and_tree.into()),
            [inputs_0, inputs_1],
            TestChannel::InMemory,
        )
        .await?;
        assert_eq!(1, out.len());
        assert!(out[0]);
        Ok(())
    }

    #[tokio::test]
    async fn eval_2_bit_adder() -> Result<()> {
        let _guard = init_tracing();
        debug!("Test start");
        let inputs = inputs(4);
        debug!("Inputs");
        let [a0, a1, b0, b1]: [Secret; 4] = inputs.try_into().unwrap();
        let xor1 = a0.clone() ^ b0.clone();
        let and1 = a0 & b0;
        let xor2 = a1.clone() ^ b1.clone();
        let and2 = a1 & b1;
        let xor3 = xor2.clone() ^ and1.clone();
        let and3 = xor2 & and1;
        let or = and2 | and3;
        for share in [xor1, xor3, or] {
            share.output();
        }

        debug!("End Secret ops");
        let inputs_0 = bitvec![usize, Lsb0; 1, 1, 0, 0];
        let inputs_1 = bitvec![usize, Lsb0; 0, 1, 0, 1];
        let exp_output = bitvec![usize, Lsb0; 1, 1, 0];
        let adder: Circuit<bool, BooleanGate, DefaultIdx> = CircuitBuilder::global_into_circuit();

        debug!("Into circuit");
        let out = execute_circuit::<BooleanGmw, _, _>(
            &ExecutableCircuit::StaticLayers(adder.precompute_layers()),
            [inputs_0, inputs_1],
            TestChannel::InMemory,
        )
        .await?;
        debug!("Executed");
        assert_eq!(exp_output, out);
        Ok(())
    }
}