mithril_stm/
parameters.rs

1use serde::{Deserialize, Serialize};
2
3use crate::error::RegisterError;
4
5/// Used to set protocol parameters.
6// todo: this is the criteria to consider parameters valid:
7// Let A = max assumed adversarial stake
8// Let a = A / max_stake
9// Let p = φ(a)  // f needs tuning, something close to 0.2 is reasonable
10// Then, we're secure if SUM[from i=k to i=m] Binomial(i successes, m experiments, p chance of success) <= 2^-100 or thereabouts.
11// The latter turns to 1 - BinomialCDF(k-1,m,p)
12#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
13pub struct StmParameters {
14    /// Security parameter, upper bound on indices.
15    pub m: u64,
16    /// Quorum parameter.
17    pub k: u64,
18    /// `f` in phi(w) = 1 - (1 - f)^w, where w is the stake of a participant..
19    pub phi_f: f64,
20}
21
22impl StmParameters {
23    /// Convert to bytes
24    /// # Layout
25    /// * Security parameter, `m` (as u64)
26    /// * Quorum parameter, `k` (as u64)
27    /// * Phi f, as (f64)
28    pub fn to_bytes(&self) -> [u8; 24] {
29        let mut out = [0; 24];
30        out[..8].copy_from_slice(&self.m.to_be_bytes());
31        out[8..16].copy_from_slice(&self.k.to_be_bytes());
32        out[16..].copy_from_slice(&self.phi_f.to_be_bytes());
33        out
34    }
35
36    /// Extract the `StmParameters` from a byte slice.
37    /// # Error
38    /// The function fails if the given string of bytes is not of required size.
39    pub fn from_bytes(bytes: &[u8]) -> Result<Self, RegisterError> {
40        let mut u64_bytes = [0u8; 8];
41        u64_bytes.copy_from_slice(bytes.get(..8).ok_or(RegisterError::SerializationError)?);
42        let m = u64::from_be_bytes(u64_bytes);
43        u64_bytes.copy_from_slice(bytes.get(8..16).ok_or(RegisterError::SerializationError)?);
44        let k = u64::from_be_bytes(u64_bytes);
45        u64_bytes.copy_from_slice(bytes.get(16..24).ok_or(RegisterError::SerializationError)?);
46        let phi_f = f64::from_be_bytes(u64_bytes);
47
48        Ok(Self { m, k, phi_f })
49    }
50}