Skip to content

Commit

Permalink
Merge from main
Browse files Browse the repository at this point in the history
  • Loading branch information
akoshelev committed Mar 18, 2024
2 parents 21d7b98 + af58b0f commit 684e32e
Show file tree
Hide file tree
Showing 20 changed files with 927 additions and 379 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,9 @@ jobs:
- uses: actions/checkout@v4
- uses: ./.github/actions/rm
- uses: dtolnay/rust-toolchain@nightly
with:
# More recent nightlies don't work, probably https://github.com/rust-lang/rust/issues/122399
toolchain: nightly-2024-03-11
- name: Add Miri
run: rustup component add miri
- name: Setup Miri
Expand Down
2 changes: 1 addition & 1 deletion ipa-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ tower = { version = "0.4.13", optional = true }
tower-http = { version = "0.4.0", optional = true, features = ["trace"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
typenum = "1.16"
typenum = { version = "1.17", features = ["i128"] }
# hpke is pinned to it
x25519-dalek = "2.0.0-rc.3"

Expand Down
18 changes: 17 additions & 1 deletion ipa-core/src/ff/boolean_array.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::fmt::{Debug, Formatter};

use bitvec::{
prelude::{BitArr, Lsb0},
slice::Iter,
Expand Down Expand Up @@ -254,9 +256,16 @@ macro_rules! boolean_array_impl {
type Store = BitArr!(for $bits, in u8, Lsb0);

/// A Boolean array with $bits bits.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct $name(pub(super) Store);

impl Debug for $name {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(stringify!($name))?;
self.0.data.fmt(f)
}
}

impl $name {
#[cfg(all(test, unit_test))]
const STORE_LEN: usize = bitvec::mem::elts::<u8>($bits);
Expand Down Expand Up @@ -697,6 +706,13 @@ macro_rules! boolean_array_impl {
"Failed to deserialize a valid value: {ba:?}"
);
}

#[test]
fn debug() {
let expected = format!("{}{:?}", stringify!($name), $name::ZERO.0.data);
let actual = format!("{:?}", $name::ZERO);
assert_eq!(expected, actual);
}
}
}

Expand Down
46 changes: 45 additions & 1 deletion ipa-core/src/ff/prime_field.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Display;
use std::{fmt::Display, mem};

use generic_array::GenericArray;

Expand All @@ -14,6 +14,42 @@ pub trait PrimeField: Field + U128Conversions {
type PrimeInteger: Into<u128>;

const PRIME: Self::PrimeInteger;

/// Invert function that returns the multiplicative inverse
/// the default implementation uses the extended Euclidean algorithm,
/// follows inversion algorithm in
/// (with the modification that it works for unsigned integers by keeping track of `sign`):
/// `https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm`
///
/// The function operates on `u128` rather than field elements since we need divisions
///
/// ## Panics
/// When `self` is `Zero`
#[must_use]
fn invert(&self) -> Self {
assert_ne!(*self, Self::ZERO);

let mut t = 0u128;
let mut newt = 1u128;
let mut r = Self::PRIME.into();
let mut newr = self.as_u128();
let mut sign = 1u128;

while newr != 0 {
let quotient = r / newr;
mem::swap(&mut t, &mut newt);
mem::swap(&mut r, &mut newr);
newt += quotient * t;
newr -= quotient * r;

// flip sign
sign = 1 - sign;
}

// when sign is negative, output `PRIME-t` otherwise `t`
// unwrap is safe
Self::try_from((1 - sign) * t + sign * (Self::PRIME.into() - t)).unwrap()
}
}

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -295,6 +331,14 @@ macro_rules! field_impl {
let err = $field::deserialize(&buf).unwrap_err();
assert!(matches!(err, GreaterThanPrimeError(..)))
}

#[test]
fn invert(element: $field) {
if element != $field::ZERO
{
assert_eq!($field::ONE,element * element.invert() );
}
}
}
}

Expand Down
44 changes: 44 additions & 0 deletions ipa-core/src/helpers/futures.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};

use pin_project::pin_project;

#[pin_project(project = MaybeFutureProj)]
pub enum MaybeFuture<Fut: Future> {
Future(#[pin] Fut),
Value(Option<Fut::Output>),
}

impl<Fut: Future> Future for MaybeFuture<Fut> {
type Output = Fut::Output;

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.project() {
MaybeFutureProj::Future(fut) => fut.poll(cx),
MaybeFutureProj::Value(val) => Poll::Ready(val.take().unwrap()),
}
}
}

impl<Fut: Future> MaybeFuture<Fut> {
pub fn future(fut: Fut) -> Self {
MaybeFuture::Future(fut)
}

pub fn value(val: Fut::Output) -> Self {
MaybeFuture::Value(Some(val))
}
}

impl<Fut: Future<Output = Result<(), E>>, E> MaybeFuture<Fut> {
pub fn future_or_ok<F: FnOnce() -> Fut>(condition: bool, f: F) -> Self {
if condition {
MaybeFuture::Future(f())
} else {
MaybeFuture::Value(Some(Ok(())))
}
}
}
2 changes: 2 additions & 0 deletions ipa-core/src/helpers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use generic_array::GenericArray;

mod buffers;
mod error;
mod futures;
mod gateway;
pub(crate) mod prss_protocol;
mod transport;
Expand All @@ -18,6 +19,7 @@ use std::ops::{Index, IndexMut};
#[cfg(test)]
pub use buffers::OrderingSender;
pub use error::Error;
pub use futures::MaybeFuture;

#[cfg(feature = "stall-detection")]
mod gateway_exports {
Expand Down
2 changes: 1 addition & 1 deletion ipa-core/src/protocol/basics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub use check_zero::check_zero;
pub use if_else::{if_else, select};
pub use mul::{BooleanArrayMul, MultiplyZeroPositions, SecureMul, ZeroPositions};
pub use reshare::Reshare;
pub use reveal::Reveal;
pub use reveal::{reveal, Reveal};
pub use share_known_value::ShareKnownValue;
pub use sum_of_product::SumOfProducts;

Expand Down
Loading

0 comments on commit 684e32e

Please sign in to comment.