Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add state machine #7

Merged
merged 11 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ jobs:
with:
cache-on-failure: "true"
- name: Run clippy
run: cargo clippy --all --lib
run: cargo clippy --all --lib --all-features -- -D clippy::all

build-wasm-nostd:
runs-on: ubuntu-latest
Expand Down
12 changes: 12 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion examples/random-generation-protocol/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ thiserror = { version = "1", optional = true }
generic-array = { version = "0.14", features = ["serde"] }

[dev-dependencies]
round-based = { path = "../../round-based", features = ["derive", "dev"] }
round-based = { path = "../../round-based", features = ["derive", "dev", "state-machine"] }
tokio = { version = "1.15", features = ["macros", "rt"] }
futures = "0.3"
hex = "0.4"
rand_dev = "0.1"
rand = "0.8"

[features]
std = ["thiserror"]
153 changes: 150 additions & 3 deletions examples/random-generation-protocol/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#![no_std]
#![forbid(unused_crate_dependencies, missing_docs)]

#[cfg(feature = "std")]
#[cfg(any(feature = "std", test))]
extern crate std;

extern crate alloc;
Expand Down Expand Up @@ -173,14 +173,16 @@ pub struct Blame {

#[cfg(test)]
mod tests {
use alloc::vec;
use alloc::{vec, vec::Vec};

use rand::Rng;
use round_based::simulation::Simulation;
use sha2::{Digest, Sha256};

use super::{protocol_of_random_generation, Msg};

#[tokio::test]
async fn main() {
async fn simulation_async() {
let mut rng = rand_dev::DevRng::new();

let n: u16 = 5;
Expand All @@ -203,4 +205,149 @@ mod tests {

std::println!("Output randomness: {}", hex::encode(output[0]));
}

#[test]
fn simulation_sync() {
let mut rng = rand_dev::DevRng::new();

let simulation = round_based::simulation::SimulationSync::from_async_fn(5, |i, party| {
protocol_of_random_generation(party, i, 5, rng.fork())
});

let outputs = simulation
.run()
.unwrap()
.into_iter()
.collect::<Result<Vec<_>, _>>()
.unwrap();
for output_i in &outputs {
assert_eq!(*output_i, outputs[0]);
}
}

// Emulate the protocol using the state machine interface
#[test]
fn state_machine() {
use super::{CommitMsg, DecommitMsg, Msg};
use round_based::{
state_machine::{ProceedResult, StateMachine},
Incoming, Outgoing,
};

let mut rng = rand_dev::DevRng::new();

let party1_rng: [u8; 32] = rng.gen();
let party1_com = Sha256::digest(party1_rng);

let party2_rng: [u8; 32] = rng.gen();
let party2_com = Sha256::digest(party2_rng);

// Start the protocol
let mut party0 = round_based::state_machine::wrap_protocol(|party| async {
protocol_of_random_generation(party, 0, 3, rng).await
});

// Round 1

// Party sends its commitment
let ProceedResult::SendMsg(Outgoing {
msg: Msg::CommitMsg(party0_com),
..
}) = party0.proceed()
else {
panic!("unexpected response")
};

// Round 2

// Party needs messages sent by other parties in round 1
let ProceedResult::NeedsOneMoreMessage = party0.proceed() else {
panic!("unexpected response")
};
// Provide message from party 1
party0
.received_msg(Incoming {
id: 0,
sender: 1,
msg_type: round_based::MessageType::Broadcast,
msg: Msg::CommitMsg(CommitMsg {
commitment: party1_com,
}),
})
.unwrap();
let ProceedResult::NeedsOneMoreMessage = party0.proceed() else {
panic!("unexpected response")
};
// Provide message from party 2
party0
.received_msg(Incoming {
id: 1,
sender: 2,
msg_type: round_based::MessageType::Broadcast,
msg: Msg::CommitMsg(CommitMsg {
commitment: party2_com,
}),
})
.unwrap();

// Party sends message in round 2
let ProceedResult::SendMsg(Outgoing {
msg: Msg::DecommitMsg(party0_rng),
..
}) = party0.proceed()
else {
panic!("unexpected response")
};

{
// Check that commitment matches the revealed randomness
let expected = Sha256::digest(party0_rng.randomness);
assert_eq!(party0_com.commitment, expected);
}

// Final round

// Party needs messages sent by other parties in round 2
let ProceedResult::NeedsOneMoreMessage = party0.proceed() else {
panic!("unexpected response")
};
// Provide message from party 1
party0
.received_msg(Incoming {
id: 3,
sender: 1,
msg_type: round_based::MessageType::Broadcast,
msg: Msg::DecommitMsg(DecommitMsg {
randomness: party1_rng,
}),
})
.unwrap();
let ProceedResult::NeedsOneMoreMessage = party0.proceed() else {
panic!("unexpected response")
};
// Provide message from party 2
party0
.received_msg(Incoming {
id: 3,
sender: 2,
msg_type: round_based::MessageType::Broadcast,
msg: Msg::DecommitMsg(DecommitMsg {
randomness: party2_rng,
}),
})
.unwrap();
// Obtain the protocol result
let ProceedResult::Output(Ok(output_rng)) = party0.proceed() else {
panic!("unexpected response")
};

let output_expected = party0_rng
.randomness
.iter()
.zip(&party1_rng)
.zip(&party2_rng)
.map(|((a, b), c)| a ^ b ^ c)
.collect::<alloc::vec::Vec<_>>();
assert_eq!(output_rng, output_expected.as_slice());
}
}
2 changes: 2 additions & 0 deletions round-based/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
## v0.3.0
* Add no_std and wasm support [#6]
* Add state machine wrapper that provides sync API to carry out the protocol defined as async function [#7]

[#6]: https://github.com/dfns/round-based/pull/6
[#7]: https://github.com/dfns/round-based/pull/7

## v0.2.2

Expand Down
3 changes: 2 additions & 1 deletion round-based/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ tokio = { version = "1", features = ["macros"] }

[features]
default = ["std"]
dev = ["tokio/sync", "tokio-stream"]
state-machine = []
dev = ["std", "tokio/sync", "tokio-stream"]
derive = ["round-based-derive"]
runtime-tokio = ["tokio"]
std = ["thiserror"]
Expand Down
2 changes: 2 additions & 0 deletions round-based/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ mod delivery;
pub mod party;
pub mod rounds_router;
pub mod runtime;
#[cfg(feature = "state-machine")]
pub mod state_machine;

#[cfg(feature = "dev")]
pub mod simulation;
Expand Down
2 changes: 0 additions & 2 deletions round-based/src/party.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ pub struct MpcParty<M, D, R = runtime::DefaultRuntime> {

impl<M, D> MpcParty<M, D>
where
M: Send + 'static,
D: Delivery<M>,
{
/// Party connected to the network
Expand All @@ -123,7 +122,6 @@ where

impl<M, D, X> MpcParty<M, D, X>
where
M: Send + 'static,
D: Delivery<M>,
{
/// Specifies a [async runtime](runtime)
Expand Down
2 changes: 2 additions & 0 deletions round-based/src/rounds_router/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ where
}
}

#[allow(clippy::type_complexity)]
fn retrieve_round_output_if_its_completed<R>(
&mut self,
) -> Option<Result<R::Output, CompleteRoundError<R::Error, E>>>
Expand Down Expand Up @@ -321,6 +322,7 @@ trait ProcessRoundMessage {
/// * `Ok(Ok(any))` — round is successfully completed, `any` needs to be downcasted to `MessageStore::Output`
/// * `Ok(Err(any))` — round has terminated with an error, `any` needs to be downcasted to `CompleteRoundError<MessageStore::Error>`
/// * `Err(err)` — couldn't retrieve the output, see [`TakeOutputError`]
#[allow(clippy::type_complexity)]
fn take_output(&mut self) -> Result<Result<Box<dyn Any>, Box<dyn Any>>, TakeOutputError>;
}

Expand Down
2 changes: 1 addition & 1 deletion round-based/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
/// function.
pub trait AsyncRuntime {
/// Future type returned by [yield_now](Self::yield_now)
type YieldNowFuture: core::future::Future<Output = ()> + Send + 'static;
type YieldNowFuture: core::future::Future<Output = ()>;

/// Yields the execution back to the runtime
///
Expand Down
49 changes: 49 additions & 0 deletions round-based/src/simulation/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//! Multiparty protocol simulation
//!
//! [`Simulation`] is an essential developer tool for testing the multiparty protocol locally.
//! It covers most of the boilerplate by mocking networking.
//!
//! ## Example
//!
//! ```rust
//! use round_based::{Mpc, PartyIndex};
//! use round_based::simulation::Simulation;
//! use futures::future::try_join_all;
//!
//! # type Result<T, E = ()> = std::result::Result<T, E>;
//! # type Randomness = [u8; 32];
//! # type Msg = ();
//! // Any MPC protocol you want to test
//! pub async fn protocol_of_random_generation<M>(party: M, i: PartyIndex, n: u16) -> Result<Randomness>
//! where M: Mpc<ProtocolMessage = Msg>
//! {
//! // ...
//! # todo!()
//! }
//!
//! async fn test_randomness_generation() {
//! let n = 3;
//!
//! let mut simulation = Simulation::<Msg>::new();
//! let mut outputs = vec![];
//! for i in 0..n {
//! let party = simulation.add_party();
//! outputs.push(protocol_of_random_generation(party, i, n));
//! }
//!
//! // Waits each party to complete the protocol
//! let outputs = try_join_all(outputs).await.expect("protocol wasn't completed successfully");
//! // Asserts that all parties output the same randomness
//! for output in outputs.iter().skip(1) {
//! assert_eq!(&outputs[0], output);
//! }
//! }
//! ```

mod sim_async;
#[cfg(feature = "state-machine")]
mod sim_sync;

pub use sim_async::*;
#[cfg(feature = "state-machine")]
pub use sim_sync::*;
Loading
Loading