ark-mpc 0.1.2

Malicious-secure SPDZ style two party secure computation
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
//! Defines the base polynomial representation, modeled after the
//! `ark_poly::DensePolynomial` type

use std::{
    cmp, iter,
    ops::{Add, Div, Mul, Neg, Sub},
    pin::Pin,
    task::{Context, Poll},
};

use ark_ec::CurveGroup;
use ark_ff::{Field, One, Zero};
use ark_poly::{
    univariate::{DenseOrSparsePolynomial, DensePolynomial},
    DenseUVPolynomial,
};
use futures::FutureExt;
use futures::{ready, Future};
use itertools::Itertools;

use crate::{
    algebra::{
        macros::{impl_borrow_variants, impl_commutative},
        AuthenticatedScalarResult, Scalar, ScalarResult,
    },
    MpcFabric, ResultValue,
};

use super::AuthenticatedDensePoly;

// -----------
// | Helpers |
// -----------

/// Return a representation of x^t as a `DensePolynomial`
fn x_to_t<C: CurveGroup>(t: usize) -> DensePolynomial<C::ScalarField> {
    let mut coeffs = vec![C::ScalarField::zero(); t];
    coeffs.push(C::ScalarField::one());
    DensePolynomial::from_coefficients_vec(coeffs)
}

// ------------------
// | Implementation |
// ------------------

/// A dense polynomial representation allocated in an MPC circuit
#[derive(Clone, Debug, Default)]
pub struct DensePolynomialResult<C: CurveGroup> {
    /// The coefficients of the polynomial, the `i`th coefficient is the
    /// coefficient of `x^i`
    pub coeffs: Vec<ScalarResult<C>>,
}

impl<C: CurveGroup> DensePolynomialResult<C> {
    /// Constructor
    pub fn from_coeffs(coeffs: Vec<ScalarResult<C>>) -> Self {
        assert!(!coeffs.is_empty(), "cannot construct an empty polynomial");
        Self { coeffs }
    }

    /// Construct the zero polynomial (additive identity)
    pub fn zero(fabric: &MpcFabric<C>) -> Self {
        Self::from_coeffs(vec![fabric.zero()])
    }

    /// Construct the one polynomial (multiplicative identity)
    pub fn one(fabric: &MpcFabric<C>) -> Self {
        Self::from_coeffs(vec![fabric.one()])
    }

    /// Returns the degree of the polynomial
    pub fn degree(&self) -> usize {
        self.coeffs.len() - 1
    }

    /// Get a reference to the fabric that the polynomial is allocated within
    pub(crate) fn fabric(&self) -> &MpcFabric<C> {
        self.coeffs[0].fabric()
    }

    /// Evaluate the polynomial at a given point
    pub fn eval(&self, point: ScalarResult<C>) -> ScalarResult<C> {
        let fabric = self.fabric();
        let mut deps = self.coeffs.iter().map(|coeff| coeff.id()).collect_vec();
        deps.push(point.id());

        let n_coeffs = self.coeffs.len();
        fabric.new_gate_op(deps, move |mut args| {
            let coeffs: Vec<Scalar<C>> = args.drain(..n_coeffs).map(|res| res.into()).collect_vec();
            let point: Scalar<C> = args.pop().unwrap().into();

            let mut res = Scalar::zero();
            for coeff in coeffs.iter().rev() {
                res = res * point + coeff;
            }

            ResultValue::Scalar(res)
        })
    }
}

/// Modular inversion implementation
impl<C: CurveGroup> DensePolynomialResult<C> {
    /// Compute the multiplicative inverse of the polynomial mod x^t
    ///
    /// Done using the extended Euclidean algorithm
    pub fn mul_inverse_mod_t(&self, t: usize) -> Self {
        let ids = self.coeffs.iter().map(|c| c.id()).collect_vec();
        let n_result_coeffs = t;

        let res_coeffs = self.fabric().new_batch_gate_op(
            ids,
            n_result_coeffs, // output_arity
            move |args| {
                let x_to_t = x_to_t::<C>(t);

                let self_coeffs = args
                    .into_iter()
                    .map(|res| Scalar::<C>::from(res).inner())
                    .collect_vec();
                let self_poly = DensePolynomial::from_coefficients_vec(self_coeffs);

                // Compute the bezout coefficients of the two polynomials
                let (inverse_poly, _) = Self::compute_bezout_polynomials(&self_poly, &x_to_t);

                // In a polynomial ring, gcd is defined only up to scalar multiplication, so we
                // multiply the result by the inverse of the resultant first
                // coefficient to uniquely define the inverse as f^{-1}(x) such that
                // f * f^{-1}(x) = 1 \in F[x] / (x^t)
                let self_constant_coeff = self_poly.coeffs[0];
                let inverse_constant_coeff = inverse_poly.coeffs[0];
                let constant_coeff_inv = (self_constant_coeff * inverse_constant_coeff)
                    .inverse()
                    .unwrap();

                inverse_poly
                    .coeffs
                    .into_iter()
                    .take(n_result_coeffs)
                    .map(|c| c * constant_coeff_inv)
                    .map(Scalar::new)
                    .map(ResultValue::Scalar)
                    .collect_vec()
            },
        );

        Self::from_coeffs(res_coeffs)
    }

    /// A helper to compute the Bezout coefficients of the two given polynomials
    ///
    /// I.e. for a(x), b(x) as input, we compute f(x), g(x) such that:
    ///     f(x) * a(x) + g(x) * b(x) = gcd(a, b)
    /// This is done using the extended Euclidean method
    fn compute_bezout_polynomials(
        a: &DensePolynomial<C::ScalarField>,
        b: &DensePolynomial<C::ScalarField>,
    ) -> (
        DensePolynomial<C::ScalarField>,
        DensePolynomial<C::ScalarField>,
    ) {
        if b.is_zero() {
            return (
                DensePolynomial::from_coefficients_vec(vec![C::ScalarField::one()]), // f(x) = 1
                DensePolynomial::zero(),                                             // f(x) = 0
            );
        }

        let a_transformed = DenseOrSparsePolynomial::from(a);
        let b_transformed = DenseOrSparsePolynomial::from(b);
        let (quotient, remainder) = a_transformed.divide_with_q_and_r(&b_transformed).unwrap();

        let (f, g) = Self::compute_bezout_polynomials(b, &remainder);
        let next_g = &f - &(&quotient * &g);

        (g, next_g)
    }
}

impl<C: CurveGroup> Future for DensePolynomialResult<C>
where
    C::ScalarField: Unpin,
{
    type Output = DensePolynomial<C::ScalarField>;
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut coeffs = Vec::with_capacity(self.coeffs.len());
        for coeff in self.coeffs.iter_mut() {
            let ready_coeff = ready!(coeff.poll_unpin(cx));
            coeffs.push(ready_coeff.inner());
        }

        Poll::Ready(DensePolynomial::from_coefficients_vec(coeffs))
    }
}

// --------------
// | Arithmetic |
// --------------

// --- Addition --- //

impl<C: CurveGroup> Add<&DensePolynomial<C::ScalarField>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;
    fn add(self, rhs: &DensePolynomial<C::ScalarField>) -> Self::Output {
        assert!(!self.coeffs.is_empty(), "cannot add an empty polynomial");
        let fabric = self.coeffs[0].fabric();

        let mut coeffs = Vec::new();
        let max_degree = cmp::max(self.coeffs.len(), rhs.coeffs.len());

        // Pad the coefficients to be of the same length
        let padded_coeffs0 = self
            .coeffs
            .iter()
            .cloned()
            .chain(iter::repeat(fabric.zero()));
        let padded_coeffs1 = rhs
            .coeffs
            .iter()
            .copied()
            .map(Scalar::<C>::new)
            .chain(iter::repeat(Scalar::zero()));

        // Add component-wise
        for (lhs_coeff, rhs_coeff) in padded_coeffs0.zip(padded_coeffs1).take(max_degree) {
            coeffs.push(lhs_coeff + rhs_coeff);
        }

        DensePolynomialResult::from_coeffs(coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Add, add, +, DensePolynomial<C::ScalarField>, C: CurveGroup);
impl_commutative!(DensePolynomialResult<C>, Add, add, +, DensePolynomial<C::ScalarField>, C: CurveGroup);

impl<C: CurveGroup> Add<&DensePolynomialResult<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;
    fn add(self, rhs: &DensePolynomialResult<C>) -> Self::Output {
        // We do not pad the coefficients here, it requires fewer gates if we avoid
        // padding
        let mut coeffs = Vec::new();
        let (shorter, longer) = if self.coeffs.len() < rhs.coeffs.len() {
            (&self.coeffs, &rhs.coeffs)
        } else {
            (&rhs.coeffs, &self.coeffs)
        };

        for (i, longer_coeff) in longer.iter().enumerate() {
            let new_coeff = if i < shorter.len() {
                &shorter[i] + longer_coeff
            } else {
                longer_coeff.clone()
            };

            coeffs.push(new_coeff);
        }

        DensePolynomialResult::from_coeffs(coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Add, add, +, DensePolynomialResult<C>, C: CurveGroup);

// --- Negation --- //
impl<C: CurveGroup> Neg for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;
    fn neg(self) -> Self::Output {
        let mut coeffs = Vec::with_capacity(self.coeffs.len());
        for coeff in self.coeffs.iter() {
            coeffs.push(-coeff);
        }

        DensePolynomialResult::from_coeffs(coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Neg, neg, -, C: CurveGroup);

// --- Subtraction --- //
#[allow(clippy::suspicious_arithmetic_impl)]
impl<C: CurveGroup> Sub<&DensePolynomial<C::ScalarField>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;
    fn sub(self, rhs: &DensePolynomial<C::ScalarField>) -> Self::Output {
        let negated_rhs_coeffs = rhs.coeffs.iter().map(|coeff| -(*coeff)).collect();
        let negated_rhs = DensePolynomial::from_coefficients_vec(negated_rhs_coeffs);

        self + negated_rhs
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Sub, sub, -, DensePolynomial<C::ScalarField>, C: CurveGroup);

#[allow(clippy::suspicious_arithmetic_impl)]
impl<C: CurveGroup> Sub<&DensePolynomialResult<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;
    fn sub(self, rhs: &DensePolynomialResult<C>) -> Self::Output {
        // Negate the rhs then use the `Add` impl
        self + (-rhs)
    }
}

// --- Multiplication --- //

// TODO: For each of the following implementations, we can await all
// coefficients to be available and then perform an FFT-based polynomial
// multiplication. This is left as an optimization
impl<C: CurveGroup> Mul<&DensePolynomial<C::ScalarField>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;

    fn mul(self, rhs: &DensePolynomial<C::ScalarField>) -> Self::Output {
        let fabric = self.coeffs[0].fabric();

        let mut coeffs = Vec::with_capacity(self.coeffs.len() + rhs.coeffs.len() - 1);
        for _ in 0..self.coeffs.len() + rhs.coeffs.len() - 1 {
            coeffs.push(fabric.zero());
        }

        for (i, lhs_coeff) in self.coeffs.iter().enumerate() {
            for (j, rhs_coeff) in rhs.coeffs.iter().copied().map(Scalar::new).enumerate() {
                coeffs[i + j] = &coeffs[i + j] + lhs_coeff * rhs_coeff;
            }
        }

        DensePolynomialResult::from_coeffs(coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Mul, mul, *, DensePolynomial<C::ScalarField>, C: CurveGroup);
impl_commutative!(DensePolynomialResult<C>, Mul, mul, *, DensePolynomial<C::ScalarField>, C: CurveGroup);

impl<C: CurveGroup> Mul<&DensePolynomialResult<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;

    fn mul(self, rhs: &DensePolynomialResult<C>) -> Self::Output {
        let fabric = self.coeffs[0].fabric();

        let mut coeffs = Vec::with_capacity(self.coeffs.len() + rhs.coeffs.len() - 1);
        for _ in 0..self.coeffs.len() + rhs.coeffs.len() - 1 {
            coeffs.push(fabric.zero());
        }

        for (i, lhs_coeff) in self.coeffs.iter().enumerate() {
            for (j, rhs_coeff) in rhs.coeffs.iter().enumerate() {
                coeffs[i + j] = &coeffs[i + j] + lhs_coeff * rhs_coeff;
            }
        }

        DensePolynomialResult::from_coeffs(coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Mul, mul, *, DensePolynomialResult<C>, C: CurveGroup);

// --- Scalar Multiplication --- //

impl<C: CurveGroup> Mul<&Scalar<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;

    fn mul(self, rhs: &Scalar<C>) -> Self::Output {
        let new_coeffs = self.coeffs.iter().map(|coeff| coeff * rhs).collect_vec();
        DensePolynomialResult::from_coeffs(new_coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Mul, mul, *, Scalar<C>, C: CurveGroup);
impl_commutative!(DensePolynomialResult<C>, Mul, mul, *, Scalar<C>, C: CurveGroup);

impl<C: CurveGroup> Mul<&ScalarResult<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;

    fn mul(self, rhs: &ScalarResult<C>) -> Self::Output {
        let new_coeffs = self.coeffs.iter().map(|coeff| coeff * rhs).collect_vec();
        DensePolynomialResult::from_coeffs(new_coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Mul, mul, *, ScalarResult<C>, C: CurveGroup);
impl_commutative!(DensePolynomialResult<C>, Mul, mul, *, ScalarResult<C>, C: CurveGroup);

impl<C: CurveGroup> Mul<&AuthenticatedScalarResult<C>> for &DensePolynomialResult<C> {
    type Output = AuthenticatedDensePoly<C>;

    fn mul(self, rhs: &AuthenticatedScalarResult<C>) -> Self::Output {
        let new_coeffs = self.coeffs.iter().map(|coeff| coeff * rhs).collect_vec();
        AuthenticatedDensePoly::from_coeffs(new_coeffs)
    }
}
impl_borrow_variants!(DensePolynomialResult<C>, Mul, mul, *, AuthenticatedScalarResult<C>, Output=AuthenticatedDensePoly<C>, C: CurveGroup);
impl_commutative!(DensePolynomialResult<C>, Mul, mul, *, AuthenticatedScalarResult<C>, Output=AuthenticatedDensePoly<C>, C: CurveGroup);

// --- Division --- //

// Floor division, i.e. truncated remainder
#[allow(clippy::suspicious_arithmetic_impl)]
impl<C: CurveGroup> Div<&DensePolynomialResult<C>> for &DensePolynomialResult<C> {
    type Output = DensePolynomialResult<C>;

    fn div(self, rhs: &DensePolynomialResult<C>) -> Self::Output {
        let fabric = self.coeffs[0].fabric();
        if self.degree() < rhs.degree() {
            return DensePolynomialResult::zero(fabric);
        }

        let n_lhs_coeffs = self.coeffs.len();
        let n_rhs_coeffs = rhs.coeffs.len();

        let mut deps = self.coeffs.iter().map(|coeff| coeff.id()).collect_vec();
        deps.extend(rhs.coeffs.iter().map(|coeff| coeff.id()));

        // Allocate a gate to return the coefficients of the quotient polynomial
        let result_degree = self.degree().saturating_sub(rhs.degree());
        let coeff_results =
            fabric.new_batch_gate_op(deps, result_degree + 1 /* arity */, move |mut args| {
                let lhs_coeffs: Vec<C::ScalarField> = args
                    .drain(..n_lhs_coeffs)
                    .map(|res| Scalar::<C>::from(res).inner())
                    .collect_vec();
                let rhs_coeffs = args
                    .drain(..n_rhs_coeffs)
                    .map(|res| Scalar::<C>::from(res).inner())
                    .collect_vec();

                let lhs_poly = DensePolynomial::from_coefficients_vec(lhs_coeffs);
                let rhs_poly = DensePolynomial::from_coefficients_vec(rhs_coeffs);

                let res = &lhs_poly / &rhs_poly;
                res.coeffs
                    .iter()
                    .map(|coeff| ResultValue::Scalar(Scalar::new(*coeff)))
                    .collect_vec()
            });

        DensePolynomialResult::from_coeffs(coeff_results)
    }
}

#[cfg(test)]
pub(crate) mod test {
    use ark_ff::{One, Zero};
    use ark_poly::Polynomial;
    use itertools::Itertools;
    use rand::{thread_rng, Rng};

    use crate::{
        algebra::{
            poly_test_helpers::{allocate_poly, random_poly},
            Scalar,
        },
        test_helpers::execute_mock_mpc,
        PARTY0,
    };

    /// Degree bound on polynomials used for testing
    const DEGREE_BOUND: usize = 100;

    /// Test addition between a constant and result polynomial
    ///
    /// That is, we only allocate one of the polynomials
    #[tokio::test]
    async fn test_constant_poly_add() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 + &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let res = &poly1 + &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Test addition between two allocated polynomials
    #[tokio::test]
    async fn test_poly_add() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 + &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let poly2 = allocate_poly(&poly2, &fabric);
                let res = &poly1 + &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Test subtraction between a constant and result polynomial
    #[tokio::test]
    async fn test_poly_sub_constant() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 - &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let res = &poly1 - &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests subtraction between two allocated polynomials
    #[tokio::test]
    async fn test_poly_sub() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 - &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let poly2 = allocate_poly(&poly2, &fabric);
                let res = &poly1 - &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests multiplication between a constant and result polynomial
    #[tokio::test]
    async fn test_poly_mul_constant() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 * &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let res = &poly1 * &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests multiplication between two allocated polynomials
    #[tokio::test]
    async fn test_poly_mul() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 * &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let poly2 = allocate_poly(&poly2, &fabric);
                let res = &poly1 * &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests dividing one polynomial by another
    #[tokio::test]
    async fn test_poly_div() {
        let poly1 = random_poly(DEGREE_BOUND);
        let poly2 = random_poly(DEGREE_BOUND);

        let expected_res = &poly1 / &poly2;

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly1 = poly1.clone();
            let poly2 = poly2.clone();

            async move {
                let poly1 = allocate_poly(&poly1, &fabric);
                let poly2 = allocate_poly(&poly2, &fabric);
                let res = &poly1 / &poly2;

                res.await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests scalar multiplication with a constant value
    #[tokio::test]
    async fn test_scalar_mul_constant() {
        let poly = random_poly(DEGREE_BOUND);

        let mut rng = thread_rng();
        let scaling_factor = Scalar::random(&mut rng);

        let expected_res = &poly * scaling_factor.inner();

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly = poly.clone();
            async move {
                let poly = allocate_poly(&poly, &fabric);

                (poly * scaling_factor).await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests scalar multiplication with a public result value
    #[tokio::test]
    async fn test_scalar_mul() {
        let poly = random_poly(DEGREE_BOUND);

        let mut rng = thread_rng();
        let scaling_factor = Scalar::random(&mut rng);

        let expected_res = &poly * scaling_factor.inner();

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly = poly.clone();
            async move {
                let poly = allocate_poly(&poly, &fabric);
                let scaling_factor = fabric.allocate_scalar(scaling_factor);

                (poly * scaling_factor).await
            }
        })
        .await;

        assert_eq!(res, expected_res);
    }

    /// Tests scalar multiplication with a shared result value
    #[tokio::test]
    async fn test_scalar_mul_shared() {
        let poly = random_poly(DEGREE_BOUND);

        let mut rng = thread_rng();
        let scaling_factor = Scalar::random(&mut rng);

        let expected_res = &poly * scaling_factor.inner();

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly = poly.clone();
            async move {
                let poly = allocate_poly(&poly, &fabric);
                let scaling_factor = fabric.share_scalar(scaling_factor, PARTY0);

                (poly * scaling_factor).open_authenticated().await
            }
        })
        .await;

        assert!(res.is_ok());
        assert_eq!(res.unwrap(), expected_res);
    }

    /// Test evaluating a polynomial in the computation graph
    #[tokio::test]
    async fn test_eval() {
        let poly = random_poly(DEGREE_BOUND);

        let mut rng = thread_rng();
        let eval_point = Scalar::random(&mut rng);

        let expected_eval = poly.evaluate(&eval_point.inner());

        let (eval, _) = execute_mock_mpc(|fabric| {
            let poly = poly.clone();
            async move {
                let point_res = fabric.allocate_scalar(eval_point);
                let poly = allocate_poly(&poly, &fabric);

                poly.eval(point_res).await
            }
        })
        .await;

        assert_eq!(eval.inner(), expected_eval);
    }

    /// Tests computing the modular inverse of a polynomial
    #[tokio::test]
    async fn test_mod_inv() {
        let poly = random_poly(DEGREE_BOUND);

        let mut rng = thread_rng();
        let t = rng.gen_range(1..(DEGREE_BOUND * 2));

        let (res, _) = execute_mock_mpc(|fabric| {
            let poly = poly.clone();
            async move {
                let poly = allocate_poly(&poly, &fabric);

                poly.mul_inverse_mod_t(t).await
            }
        })
        .await;

        // Check that the result is correct
        let inverted = &poly * &res;
        let mut first_t_coeffs = inverted.coeffs.into_iter().take(t).collect_vec();

        assert!(first_t_coeffs.remove(0).is_one());
        assert!(first_t_coeffs.into_iter().all(|coeff| coeff.is_zero()));
    }
}