Skip to main content

fedimint_core/
peer_id.rs

1#[cfg(test)]
2mod tests;
3
4use std::collections::{BTreeMap, BTreeSet};
5use std::fmt::Debug;
6use std::num::NonZeroUsize;
7use std::str::FromStr;
8
9use fedimint_core::config::PeerUrl;
10use serde::{Deserialize, Serialize};
11
12use crate::encoding::{Decodable, Encodable};
13
14#[derive(
15    Debug,
16    Clone,
17    Copy,
18    PartialEq,
19    Eq,
20    Hash,
21    PartialOrd,
22    Ord,
23    Serialize,
24    Deserialize,
25    Encodable,
26    Decodable,
27)]
28pub struct PeerId(u16);
29
30impl PeerId {
31    pub fn new(id: u16) -> Self {
32        Self(id)
33    }
34
35    pub fn to_usize(self) -> usize {
36        self.0 as usize
37    }
38}
39
40impl std::fmt::Display for PeerId {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        write!(f, "{}", self.0)
43    }
44}
45
46impl FromStr for PeerId {
47    type Err = <u16 as FromStr>::Err;
48
49    fn from_str(s: &str) -> Result<Self, Self::Err> {
50        s.parse().map(PeerId)
51    }
52}
53
54impl From<u16> for PeerId {
55    fn from(id: u16) -> Self {
56        Self(id)
57    }
58}
59
60impl From<PeerId> for u16 {
61    fn from(peer: PeerId) -> Self {
62        peer.0
63    }
64}
65
66/// The nonzero number of guardians in a federation.
67///
68/// Use [`Self::new`] for unchecked input. The legacy [`From`] conversions panic
69/// on zero; the standard blanket [`TryFrom`] conversions also use those paths
70/// and are not fallible validation.
71#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
72pub struct NumPeers(NonZeroUsize);
73
74impl NumPeers {
75    /// Constructs a guardian count, returning `None` when `total` is zero.
76    pub const fn new(total: usize) -> Option<Self> {
77        match NonZeroUsize::new(total) {
78            Some(total) => Some(Self(total)),
79            None => None,
80        }
81    }
82
83    /// Returns an iterator over all peer IDs in the federation.
84    pub fn peer_ids(self) -> impl Iterator<Item = PeerId> {
85        (0u16..(self.total() as u16)).map(PeerId)
86    }
87
88    /// Returns the total number of guardians in the federation.
89    pub fn total(self) -> usize {
90        self.0.get()
91    }
92
93    /// Returns the number of guardians that can be evil without disrupting the
94    /// federation.
95    pub fn max_evil(self) -> usize {
96        (self.total() - 1) / 3
97    }
98
99    /// Returns the number of guardians to select such that at least one is
100    /// honest (assuming the federation is not compromised).
101    pub fn one_honest(self) -> usize {
102        self.max_evil() + 1
103    }
104
105    /// Returns the degree of an underlying polynomial to require threshold
106    /// signatures.
107    pub fn degree(self) -> usize {
108        self.threshold() - 1
109    }
110
111    /// Returns the number of guardians required to achieve consensus and
112    /// produce valid signatures.
113    pub fn threshold(self) -> usize {
114        self.total() - self.max_evil()
115    }
116}
117
118impl From<usize> for NumPeers {
119    /// Converts a known nonzero count, panicking if it is zero.
120    fn from(value: usize) -> Self {
121        Self::new(value).expect("a federation must have at least one guardian")
122    }
123}
124
125/// Error returned when constructing [`NumPeers`] from a zero count.
126#[derive(Debug, Copy, Clone, PartialEq, Eq)]
127pub struct EmptyPeerSet;
128
129impl std::fmt::Display for EmptyPeerSet {
130    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131        f.write_str("a federation must have at least one guardian")
132    }
133}
134
135impl std::error::Error for EmptyPeerSet {}
136
137/// Types that can be easily converted to [`NumPeers`]
138pub trait NumPeersExt {
139    /// Tries to return the number of guardians in this collection.
140    ///
141    /// The default preserves existing implementations of this trait and relies
142    /// on their nonempty invariant. Implementations that can represent an empty
143    /// collection must override this method to return [`EmptyPeerSet`].
144    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
145        Ok(self.to_num_peers())
146    }
147
148    /// Returns the number of guardians in this non-empty collection.
149    ///
150    /// # Panics
151    ///
152    /// Panics if the collection is empty.
153    fn to_num_peers(&self) -> NumPeers;
154}
155
156impl<T: NumPeersExt> From<T> for NumPeers {
157    /// Converts a nonempty collection using its peer-count invariant.
158    fn from(value: T) -> Self {
159        value.to_num_peers()
160    }
161}
162
163impl<T> NumPeersExt for BTreeMap<PeerId, T> {
164    fn to_num_peers(&self) -> NumPeers {
165        NumPeers::from(self.len())
166    }
167
168    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
169        NumPeers::new(self.len()).ok_or(EmptyPeerSet)
170    }
171}
172
173impl NumPeersExt for &[PeerId] {
174    fn to_num_peers(&self) -> NumPeers {
175        NumPeers::from(self.len())
176    }
177
178    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
179        NumPeers::new(self.len()).ok_or(EmptyPeerSet)
180    }
181}
182
183impl NumPeersExt for Vec<PeerId> {
184    fn to_num_peers(&self) -> NumPeers {
185        NumPeers::from(self.len())
186    }
187
188    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
189        NumPeers::new(self.len()).ok_or(EmptyPeerSet)
190    }
191}
192
193impl NumPeersExt for Vec<PeerUrl> {
194    fn to_num_peers(&self) -> NumPeers {
195        NumPeers::from(self.len())
196    }
197
198    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
199        NumPeers::new(self.len()).ok_or(EmptyPeerSet)
200    }
201}
202
203impl NumPeersExt for BTreeSet<PeerId> {
204    fn to_num_peers(&self) -> NumPeers {
205        NumPeers::from(self.len())
206    }
207
208    fn try_num_peers(&self) -> Result<NumPeers, EmptyPeerSet> {
209        NumPeers::new(self.len()).ok_or(EmptyPeerSet)
210    }
211}