mpc_manager/state/
parameters.rs

1//! Parameters state
2//!
3//! This module contains all the logic related to parameters management.
4
5use super::session::SessionKind;
6use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10/// Parameters error.
11#[derive(Error, Debug)]
12pub enum ParametersError {
13    #[error("invalid threshold {0}")]
14    InvalidThreshold(u16),
15    #[error("invalid number of parties {0}")]
16    InvalidParties(u16),
17}
18
19/// Parameters for the secret sharing scheme.
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct Parameters {
22    /// Number of parties `n`.
23    n: u16,
24
25    /// Threshold for the secret sharing scheme `t`.
26    ///
27    /// Threshold must be in range `0 < t < n`.
28    /// `t + 1` shares are required for the secret sharing scheme.
29    t: u16,
30}
31
32impl Parameters {
33    /// Creates new parameters for the secret sharing scheme.
34    ///
35    /// # Errors
36    ///
37    /// * Returns an error if `t` is not in range `0 < t < n`.
38    /// * Returns an error if `n` is less than 2.
39    pub fn new(n: u16, t: u16) -> Result<Self> {
40        let params = Self { n, t };
41        params.validate()?;
42        Ok(params)
43    }
44
45    /// Returns the number of parties `n`.
46    pub fn n(&self) -> u16 {
47        self.n
48    }
49
50    /// Returns the threshold `t`.
51    pub fn t(&self) -> u16 {
52        self.t
53    }
54
55    /// Checks if parameters are valid.
56    pub fn validate(&self) -> Result<()> {
57        if self.n < 2 {
58            return Err(ParametersError::InvalidParties(self.n).into());
59        }
60        if self.t == 0 || self.t >= self.n {
61            return Err(ParametersError::InvalidThreshold(self.t).into());
62        }
63        Ok(())
64    }
65
66    /// Returns boolean indicating if threshold has been reached.
67    pub fn threshold_reached(&self, kind: SessionKind, parties: usize) -> bool {
68        match kind {
69            SessionKind::Keygen => parties == self.n as usize,
70            SessionKind::Sign => parties > self.t as usize,
71        }
72    }
73}