Skip to main content

stoffel_mpc_coordinator_shared/
lib.rs

1// The coordinator is generic over the share type `S` used to represent shares in the underlying
2// MPC protocol. Concretely, `S` must implement `ShareBound`, which is `stoffelcrypto`'s
3// `SecretSharingScheme` plus some additional bounds to make the code work.
4// Every struct and trait in this library that touches shares is parametrized as `<F: FftField, S: ShareBound<F>>`;
5// the generic type `F` comes directly from the definition of `SecretSharingScheme`.
6//
7// Two share types are already contained and can be selected by choosing the concrete `S`
8// at coordinator startup:
9//
10// * **`RobustShare<F>`**: the plain Shamir share used by HoneyBadger MPC.
11// * **`FeldmanShamirShare<F, G>`**: a Shamir share augmented with group elements that
12// enable verifiable secret sharing.
13
14/// Self-signed certificates used for tests.
15pub mod self_signed_certs;
16
17/// Things related to JSON-RPC interfaces.
18pub mod rpc;
19
20/// Things for testing the coordinator when deployed, using Docker, for example.
21pub mod tests;
22
23use ark_ec::CurveGroup;
24use ark_ff::FftField;
25use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
26use serde::{Deserialize, Serialize};
27use std::collections::HashMap;
28use std::fmt;
29use std::future::Future;
30use std::str::FromStr;
31use std::sync::Once;
32use stoffelmpc_mpc::common::share::feldman::FeldmanShamirShare;
33use stoffelmpc_mpc::common::share::ShareError;
34use stoffelmpc_mpc::common::SecretSharingScheme;
35use stoffelmpc_mpc::honeybadger::robust_interpolate::robust_interpolate::RobustShare;
36use thiserror::Error;
37
38/// Uniquely identifies one MPC program invocation.
39///
40/// A program hash is deliberately not used as the execution identity: two invocations of the
41/// same program must be able to overlap without sharing coordinator or node state. The all-zero
42/// value is reserved and rejected by persistent/concurrent RPC paths.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(transparent)]
45pub struct ExecutionId([u8; 32]);
46
47impl ExecutionId {
48    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
49        Self(bytes)
50    }
51
52    pub const fn as_bytes(&self) -> &[u8; 32] {
53        &self.0
54    }
55
56    pub fn is_zero(self) -> bool {
57        self.0 == [0; 32]
58    }
59}
60
61impl fmt::Display for ExecutionId {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.write_str(&hex::encode(self.0))
64    }
65}
66
67impl FromStr for ExecutionId {
68    type Err = String;
69
70    fn from_str(value: &str) -> Result<Self, Self::Err> {
71        if value.len() != 64 {
72            return Err(format!(
73                "execution ID must contain exactly 64 hexadecimal characters, got {}",
74                value.len()
75            ));
76        }
77        let bytes = hex::decode(value).map_err(|error| format!("invalid execution ID: {error}"))?;
78        Ok(Self(
79            bytes.try_into().expect("validated execution ID length"),
80        ))
81    }
82}
83
84#[cfg(test)]
85mod execution_id_tests {
86    use super::*;
87
88    #[test]
89    fn hex_round_trip_is_strict_and_stable() {
90        let id = ExecutionId::from_bytes([0xab; 32]);
91        let encoded = id.to_string();
92        assert_eq!(encoded.len(), 64);
93        assert_eq!(encoded.parse::<ExecutionId>().unwrap(), id);
94        assert!("ab".parse::<ExecutionId>().is_err());
95        assert!(format!("{}z", &encoded[..63])
96            .parse::<ExecutionId>()
97            .is_err());
98    }
99}
100
101pub trait ShareBound<F: FftField>:
102    SecretSharingScheme<F, SecretType = Self::ValueType>
103    + CanonicalSerialize
104    + CanonicalDeserialize
105    + Clone
106    + Send
107    + 'static
108{
109    type ValueType: CanonicalSerialize + CanonicalDeserialize + Clone + Send;
110
111    fn compute_masked_input(input: Self::ValueType, mask_share: &Self) -> Result<Self, ShareError>;
112
113    fn min_shares(t: usize) -> usize;
114}
115
116impl<F: FftField> ShareBound<F> for RobustShare<F> {
117    type ValueType = Self::SecretType;
118
119    fn compute_masked_input(input: Self::ValueType, mask_share: &Self) -> Result<Self, ShareError> {
120        Ok(RobustShare::new(
121            input - mask_share.share[0],
122            mask_share.id,
123            mask_share.degree,
124        ))
125    }
126
127    fn min_shares(t: usize) -> usize {
128        2 * t + 1
129    }
130}
131
132impl<F: FftField, G: CurveGroup<ScalarField = F>> ShareBound<F> for FeldmanShamirShare<F, G> {
133    type ValueType = Self::SecretType;
134
135    fn compute_masked_input(input: Self::ValueType, mask_share: &Self) -> Result<Self, ShareError> {
136        let neg_mask_share = (mask_share.clone() * (-F::one()))?;
137        neg_mask_share + input
138    }
139
140    fn min_shares(t: usize) -> usize {
141        t + 1
142    }
143}
144
145#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
146pub enum Round {
147    Idle,
148    Preprocessing,
149    InputMaskReservation,
150    InputCollection,
151    MPCExecution,
152    OutputDistribution,
153    ProgramFinished,
154}
155
156/// The position of a round in the fixed protocol order. Rounds only ever advance, so this
157/// lets a coordinator recognise a proposal for a round it has already passed.
158pub fn round_index(round: Round) -> u8 {
159    match round {
160        Round::Idle => 0,
161        Round::Preprocessing => 1,
162        Round::InputMaskReservation => 2,
163        Round::InputCollection => 3,
164        Round::MPCExecution => 4,
165        Round::OutputDistribution => 5,
166        Round::ProgramFinished => 6,
167    }
168}
169
170pub fn round_before(current: Round) -> Option<Round> {
171    match current {
172        Round::Idle => None,
173        Round::Preprocessing => Some(Round::Idle),
174        Round::InputMaskReservation => Some(Round::Preprocessing),
175        Round::InputCollection => Some(Round::InputMaskReservation),
176        Round::MPCExecution => Some(Round::InputCollection),
177        Round::OutputDistribution => Some(Round::MPCExecution),
178        Round::ProgramFinished => Some(Round::OutputDistribution),
179    }
180}
181
182pub trait Coordinator<F: FftField, S: ShareBound<F>> {
183    type ClientIdentity;
184
185    fn start_preprocessing(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
186    fn reserve_input_masks(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
187    fn collect_inputs(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
188    fn start_mpc(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
189    fn send_output(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
190    fn finalize(&self) -> impl Future<Output = Result<(), CoordinatorError>>;
191
192    fn wait_for_round(&self, round: Round) -> impl Future<Output = Result<(), CoordinatorError>>;
193
194    fn reserve_mask_index(&mut self, i: u64) -> impl Future<Output = Result<(), CoordinatorError>>;
195
196    /// Reserves several input-mask indices in one call. The default implementation just calls
197    /// `reserve_mask_index` in a loop, so implementors get this for free; `off-chain` overrides
198    /// it with a single round trip, since reserving indices one at a time is what makes clients
199    /// with many inputs blow past the RPC timeout under load.
200    fn reserve_mask_indices(
201        &mut self,
202        indices: &[u64],
203    ) -> impl Future<Output = Result<(), CoordinatorError>> {
204        async move {
205            for &i in indices {
206                self.reserve_mask_index(i).await?;
207            }
208            Ok(())
209        }
210    }
211
212    fn send_masked_input(
213        &self,
214        masked_input: S::ValueType,
215        i: u64,
216    ) -> impl Future<Output = Result<(), CoordinatorError>>;
217
218    /// Submits several masked inputs in one call. The default implementation just calls
219    /// `send_masked_input` in a loop, so implementors get this for free; `off-chain` overrides
220    /// it with a single round trip, for the same reason `reserve_mask_indices` overrides
221    /// `reserve_mask_index`: submitting inputs one at a time is what makes clients with many
222    /// inputs blow past the RPC timeout under load.
223    fn send_masked_inputs(
224        &self,
225        inputs: &[(u64, S::ValueType)],
226    ) -> impl Future<Output = Result<(), CoordinatorError>> {
227        async move {
228            for (i, masked_input) in inputs {
229                self.send_masked_input(masked_input.clone(), *i).await?;
230            }
231            Ok(())
232        }
233    }
234
235    fn wait_for_inputs(
236        &self,
237        n_inputs: u64,
238        mask_shares: Vec<S>,
239    ) -> impl Future<Output = Result<HashMap<Self::ClientIdentity, Vec<S>>, CoordinatorError>>;
240
241    fn wait_for_indices(
242        &self,
243        n_inputs: u64,
244    ) -> impl Future<Output = Result<HashMap<Self::ClientIdentity, Vec<u64>>, CoordinatorError>>;
245
246    fn obtain_outputs(&self) -> impl Future<Output = Result<Vec<S::ValueType>, CoordinatorError>>;
247
248    fn send_output_shares(
249        &self,
250        client_id: Self::ClientIdentity,
251        key: Vec<u8>,
252        output_shares: Vec<S>,
253    ) -> impl Future<Output = Result<(), CoordinatorError>>;
254}
255
256#[derive(Error, Clone, Debug, Serialize, Deserialize)]
257pub enum CoordinatorError {
258    #[error("The index {0:?} is already reserved.")]
259    IndexAlreadyReserved(usize),
260    #[error("The masked input for index {0:?} has already been sent.")]
261    MaskedInputAlreadySent(usize),
262    #[error("Mask reconstruction from {0:?} shares failed.")]
263    MaskReconstructionFailed(usize),
264    #[error("Interaction with Ethereum blockchain failed: {0}")]
265    EthereumError(String),
266    #[error("U256 value out of range for Fr")]
267    U256ToFrError,
268    #[error("U256 value out of range for u64")]
269    U256ToU64Error,
270    #[error("U64 value out of range for usize")]
271    U64ToUsizeError,
272    #[error("Parsing DER-encoded key as PKCS#8 failed")]
273    ParsingDERAsPKCS8Failed,
274    #[error("Parsing private key failed")]
275    ParsingPrivateKeyFailed,
276    #[error("Deserialization failed")]
277    DeserializationError,
278    #[error("Serialization failed")]
279    SerializationError,
280    #[error("Parsing public key failed")]
281    ParsingPublicKeyFailed,
282    #[error("Encryption failed")]
283    EncryptionError,
284    #[error("Decryption failed")]
285    DecryptionError,
286    #[error("JSON error: {0}")]
287    JSONError(String),
288    #[error("Subscription error: {0}")]
289    SubscriptionError(String),
290    #[error("Parsing an encapsulated key failed")]
291    ParsingEncapsulatedKeyFailed,
292    #[error("Cannot transition to Idle round")]
293    CannotTransitionToIdle,
294    #[error("Calculating a share failed")]
295    ShareError,
296    #[error("Failed to bind to address {0}")]
297    BindError(String),
298    #[error("Failed to connect: {0}")]
299    ConnectError(String),
300    #[error("TLS configuration error: {0}")]
301    TlsConfigError(String),
302}
303
304#[derive(Error, Clone, Debug)]
305pub enum NodeRPCError {
306    #[error("Execution is not registered or is ambiguous")]
307    ExecutionNotFound,
308    #[error("Index already added")]
309    IndexAlreadyAdded,
310    #[error("Index not added")]
311    IndexNotAdded,
312    #[error("JSON error")]
313    JSONError,
314    #[error("Serialization error")]
315    SerializationError,
316    #[error("Ethereum error: {0}")]
317    EthereumError(String),
318    #[error("Authentication failed for client with TLS identity {0:?}")]
319    AuthenticationFailed(Vec<u8>),
320}
321
322static INIT: Once = Once::new();
323
324pub fn setup_test() {
325    INIT.call_once(|| {
326        // Installing a crypto provider is process-global. Another dependency may
327        // have installed one before this helper runs, which is already a valid
328        // test setup and must not poison the initializer.
329        let _ = rustls::crypto::ring::default_provider().install_default();
330    });
331}