mpc_stark/
network.rs

1//! The `network` module defines abstractions of the transport used to
2//! communicate during the course of an MPC
3mod cert_verifier;
4mod config;
5mod mock;
6mod quic;
7mod stream_buffer;
8
9pub use quic::*;
10
11use futures::{Sink, Stream};
12#[cfg(any(feature = "test_helpers", feature = "benchmarks", test))]
13pub use mock::{MockNetwork, NoRecvNetwork, UnboundedDuplexStream};
14
15use async_trait::async_trait;
16use serde::{Deserialize, Serialize};
17
18use crate::{
19    algebra::{scalar::Scalar, stark_curve::StarkPoint},
20    error::MpcNetworkError,
21    fabric::ResultId,
22};
23
24/// A type alias of the id of a party in an MPC for readability
25pub type PartyId = u64;
26
27// ---------
28// | Trait |
29// ---------
30
31/// The type that the network sender receives
32#[derive(Clone, Debug, Serialize, Deserialize)]
33pub struct NetworkOutbound {
34    /// The operation ID that generated this message
35    pub result_id: ResultId,
36    /// The body of the message
37    pub payload: NetworkPayload,
38}
39
40/// The payload of an outbound message
41#[derive(Clone, Debug, Serialize, Deserialize)]
42pub enum NetworkPayload {
43    /// A byte value
44    Bytes(Vec<u8>),
45    /// A scalar value
46    Scalar(Scalar),
47    /// A batch of scalar values
48    ScalarBatch(Vec<Scalar>),
49    /// A point on the curve
50    Point(StarkPoint),
51    /// A batch of points on the curve
52    PointBatch(Vec<StarkPoint>),
53}
54
55impl From<Vec<u8>> for NetworkPayload {
56    fn from(bytes: Vec<u8>) -> Self {
57        Self::Bytes(bytes)
58    }
59}
60
61impl From<Scalar> for NetworkPayload {
62    fn from(scalar: Scalar) -> Self {
63        Self::Scalar(scalar)
64    }
65}
66
67impl From<Vec<Scalar>> for NetworkPayload {
68    fn from(scalars: Vec<Scalar>) -> Self {
69        Self::ScalarBatch(scalars)
70    }
71}
72
73impl From<StarkPoint> for NetworkPayload {
74    fn from(point: StarkPoint) -> Self {
75        Self::Point(point)
76    }
77}
78
79impl From<Vec<StarkPoint>> for NetworkPayload {
80    fn from(value: Vec<StarkPoint>) -> Self {
81        Self::PointBatch(value)
82    }
83}
84
85/// The `MpcNetwork` trait defines shared functionality for a network implementing a
86/// connection between two parties in a 2PC
87///
88/// Values are sent as bytes, scalars, or curve points and always in batch form with the
89/// message length (measured in the number of elements sent) prepended to the message
90#[async_trait]
91pub trait MpcNetwork:
92    Send
93    + Stream<Item = Result<NetworkOutbound, MpcNetworkError>>
94    + Sink<NetworkOutbound, Error = MpcNetworkError>
95{
96    /// Get the party ID of the local party in the MPC
97    fn party_id(&self) -> PartyId;
98    /// Closes the connections opened in the handshake phase
99    async fn close(&mut self) -> Result<(), MpcNetworkError>;
100}
101
102// -----------
103// | Helpers |
104// -----------