1use std::{
7 collections::{BTreeMap, BTreeSet, HashMap},
8 fmt::{Display, Formatter, Write},
9 hash::{Hash, Hasher},
10};
11
12use fastcrypto::traits::KeyPair;
13pub use iota_protocol_config::ProtocolVersion;
14use once_cell::sync::OnceCell;
15use rand::{
16 Rng, SeedableRng,
17 rngs::{StdRng, ThreadRng},
18 seq::SliceRandom,
19};
20use serde::{Deserialize, Serialize};
21
22use super::base_types::*;
23use crate::{
24 crypto::{
25 AuthorityKeyPair, AuthorityPublicKey, NetworkPublicKey, random_committee_key_pairs_of_size,
26 },
27 error::{IotaError, IotaResult},
28 multiaddr::Multiaddr,
29};
30
31pub type EpochId = u64;
32
33pub type StakeUnit = u64;
37
38pub type CommitteeDigest = [u8; 32];
39
40pub const TOTAL_VOTING_POWER: StakeUnit = 10_000;
50
51pub const QUORUM_THRESHOLD: StakeUnit = 6_667;
54
55pub const VALIDITY_THRESHOLD: StakeUnit = 3_334;
57
58#[derive(Clone, Debug, Serialize, Deserialize, Eq)]
59pub struct Committee {
60 pub epoch: EpochId,
61 pub voting_rights: Vec<(AuthorityName, StakeUnit)>,
62 expanded_keys: HashMap<AuthorityName, AuthorityPublicKey>,
63 index_map: HashMap<AuthorityName, usize>,
64}
65
66impl Committee {
67 pub fn new(epoch: EpochId, voting_rights: BTreeMap<AuthorityName, StakeUnit>) -> Self {
68 let mut voting_rights: Vec<(AuthorityName, StakeUnit)> =
69 voting_rights.iter().map(|(a, s)| (*a, *s)).collect();
70
71 assert!(!voting_rights.is_empty());
72 assert!(voting_rights.iter().any(|(_, s)| *s != 0));
73
74 voting_rights.sort_by_key(|(a, _)| *a);
75 let total_votes: StakeUnit = voting_rights.iter().map(|(_, votes)| *votes).sum();
76 assert_eq!(total_votes, TOTAL_VOTING_POWER);
77
78 let (expanded_keys, index_map) = Self::load_inner(&voting_rights);
79
80 Committee {
81 epoch,
82 voting_rights,
83 expanded_keys,
84 index_map,
85 }
86 }
87
88 pub fn new_for_testing_with_normalized_voting_power(
92 epoch: EpochId,
93 mut voting_weights: BTreeMap<AuthorityName, StakeUnit>,
94 ) -> Self {
95 let num_nodes = voting_weights.len();
96 let total_votes: StakeUnit = voting_weights.values().cloned().sum();
97
98 let normalization_coef = TOTAL_VOTING_POWER as f64 / total_votes as f64;
99 let mut total_sum = 0;
100 for (idx, (_auth, weight)) in voting_weights.iter_mut().enumerate() {
101 if idx < num_nodes - 1 {
102 *weight = (*weight as f64 * normalization_coef).floor() as u64; total_sum += *weight;
104 } else {
105 *weight = TOTAL_VOTING_POWER - total_sum;
107 }
108 }
109
110 Self::new(epoch, voting_weights)
111 }
112
113 pub fn load_inner(
115 voting_rights: &[(AuthorityName, StakeUnit)],
116 ) -> (
117 HashMap<AuthorityName, AuthorityPublicKey>,
118 HashMap<AuthorityName, usize>,
119 ) {
120 let expanded_keys: HashMap<AuthorityName, AuthorityPublicKey> = voting_rights
121 .iter()
122 .map(|(addr, _)| {
123 (
124 *addr,
125 (*addr)
126 .try_into()
127 .expect("Validator pubkey is always verified on-chain"),
128 )
129 })
130 .collect();
131
132 let index_map: HashMap<AuthorityName, usize> = voting_rights
133 .iter()
134 .enumerate()
135 .map(|(index, (addr, _))| (*addr, index))
136 .collect();
137 (expanded_keys, index_map)
138 }
139
140 pub fn authority_index(&self, author: &AuthorityName) -> Option<u32> {
141 self.index_map.get(author).map(|i| *i as u32)
142 }
143
144 pub fn authority_by_index(&self, index: u32) -> Option<&AuthorityName> {
145 self.voting_rights.get(index as usize).map(|(name, _)| name)
146 }
147
148 pub fn epoch(&self) -> EpochId {
149 self.epoch
150 }
151
152 pub fn public_key(&self, authority: &AuthorityName) -> IotaResult<&AuthorityPublicKey> {
153 debug_assert_eq!(self.expanded_keys.len(), self.voting_rights.len());
154 match self.expanded_keys.get(authority) {
155 Some(v) => Ok(v),
156 None => Err(IotaError::InvalidCommittee(format!(
157 "Authority #{} not found, committee size {}",
158 authority,
159 self.expanded_keys.len()
160 ))),
161 }
162 }
163
164 pub fn sample(&self) -> &AuthorityName {
166 Self::choose_multiple_weighted(&self.voting_rights[..], 1, &mut ThreadRng::default())
168 .next()
169 .unwrap()
170 }
171
172 fn choose_multiple_weighted<'a>(
173 slice: &'a [(AuthorityName, StakeUnit)],
174 count: usize,
175 rng: &mut impl Rng,
176 ) -> impl Iterator<Item = &'a AuthorityName> {
177 slice
181 .choose_multiple_weighted(rng, count, |(_, weight)| *weight as f64)
182 .unwrap()
183 .map(|(a, _)| a)
184 }
185
186 pub fn choose_multiple_weighted_iter(
187 &self,
188 count: usize,
189 ) -> impl Iterator<Item = &AuthorityName> {
190 self.voting_rights
191 .choose_multiple_weighted(&mut ThreadRng::default(), count, |(_, weight)| {
192 *weight as f64
193 })
194 .unwrap()
195 .map(|(a, _)| a)
196 }
197
198 pub fn total_votes(&self) -> StakeUnit {
199 TOTAL_VOTING_POWER
200 }
201
202 pub fn quorum_threshold(&self) -> StakeUnit {
203 QUORUM_THRESHOLD
204 }
205
206 pub fn validity_threshold(&self) -> StakeUnit {
207 VALIDITY_THRESHOLD
208 }
209
210 pub fn threshold<const STRENGTH: bool>(&self) -> StakeUnit {
211 if STRENGTH {
212 QUORUM_THRESHOLD
213 } else {
214 VALIDITY_THRESHOLD
215 }
216 }
217
218 pub fn num_members(&self) -> usize {
219 self.voting_rights.len()
220 }
221
222 pub fn members(&self) -> impl Iterator<Item = &(AuthorityName, StakeUnit)> {
223 self.voting_rights.iter()
224 }
225
226 pub fn names(&self) -> impl Iterator<Item = &AuthorityName> {
227 self.voting_rights.iter().map(|(name, _)| name)
228 }
229
230 pub fn stakes(&self) -> impl Iterator<Item = StakeUnit> + '_ {
231 self.voting_rights.iter().map(|(_, stake)| *stake)
232 }
233
234 pub fn authority_exists(&self, name: &AuthorityName) -> bool {
235 self.voting_rights
236 .binary_search_by_key(name, |(a, _)| *a)
237 .is_ok()
238 }
239
240 pub fn shuffle_by_stake_from_tx_digest(
243 &self,
244 tx_digest: &TransactionDigest,
245 ) -> Vec<AuthorityName> {
246 let digest_bytes = tx_digest.into_inner();
248
249 let mut rng = StdRng::from_seed(digest_bytes);
251 self.shuffle_by_stake_with_rng(None, None, &mut rng)
252 }
253
254 pub fn new_simple_test_committee_of_size(size: usize) -> (Self, Vec<AuthorityKeyPair>) {
257 let key_pairs: Vec<_> = random_committee_key_pairs_of_size(size)
258 .into_iter()
259 .collect();
260 let committee = Self::new_for_testing_with_normalized_voting_power(
261 0,
262 key_pairs
263 .iter()
264 .map(|key| {
265 (AuthorityName::from(key.public()), 1)
266 })
267 .collect(),
268 );
269 (committee, key_pairs)
270 }
271
272 pub fn new_simple_test_committee() -> (Self, Vec<AuthorityKeyPair>) {
275 Self::new_simple_test_committee_of_size(4)
276 }
277}
278
279impl CommitteeTrait<AuthorityName> for Committee {
280 fn shuffle_by_stake_with_rng(
281 &self,
282 preferences: Option<&BTreeSet<AuthorityName>>,
284 restrict_to: Option<&BTreeSet<AuthorityName>>,
286 rng: &mut impl Rng,
287 ) -> Vec<AuthorityName> {
288 let restricted = self
289 .voting_rights
290 .iter()
291 .filter(|(name, _)| {
292 if let Some(restrict_to) = restrict_to {
293 restrict_to.contains(name)
294 } else {
295 true
296 }
297 })
298 .cloned();
299
300 let (preferred, rest): (Vec<_>, Vec<_>) = if let Some(preferences) = preferences {
301 restricted.partition(|(name, _)| preferences.contains(name))
302 } else {
303 (Vec::new(), restricted.collect())
304 };
305
306 Self::choose_multiple_weighted(&preferred, preferred.len(), rng)
307 .chain(Self::choose_multiple_weighted(&rest, rest.len(), rng))
308 .cloned()
309 .collect()
310 }
311
312 fn weight(&self, author: &AuthorityName) -> StakeUnit {
313 match self.voting_rights.binary_search_by_key(author, |(a, _)| *a) {
314 Err(_) => 0,
315 Ok(idx) => self.voting_rights[idx].1,
316 }
317 }
318}
319
320impl PartialEq for Committee {
321 fn eq(&self, other: &Self) -> bool {
322 self.epoch == other.epoch && self.voting_rights == other.voting_rights
323 }
324}
325
326impl Hash for Committee {
327 fn hash<H: Hasher>(&self, state: &mut H) {
328 self.epoch.hash(state);
329 self.voting_rights.hash(state);
330 }
331}
332
333impl Display for Committee {
334 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
335 let mut voting_rights = String::new();
336 for (name, vote) in &self.voting_rights {
337 write!(voting_rights, "{}: {}, ", name.concise(), vote)?;
338 }
339 write!(
340 f,
341 "Committee (epoch={:?}, voting_rights=[{}])",
342 self.epoch, voting_rights
343 )
344 }
345}
346
347pub trait CommitteeTrait<K: Ord> {
348 fn shuffle_by_stake_with_rng(
349 &self,
350 preferences: Option<&BTreeSet<K>>,
352 restrict_to: Option<&BTreeSet<K>>,
354 rng: &mut impl Rng,
355 ) -> Vec<K>;
356
357 fn shuffle_by_stake(
358 &self,
359 preferences: Option<&BTreeSet<K>>,
361 restrict_to: Option<&BTreeSet<K>>,
363 ) -> Vec<K> {
364 self.shuffle_by_stake_with_rng(preferences, restrict_to, &mut ThreadRng::default())
365 }
366
367 fn weight(&self, author: &K) -> StakeUnit;
368}
369
370#[derive(Clone, Debug, Serialize, Deserialize)]
371pub struct NetworkMetadata {
372 pub network_address: Multiaddr,
373 pub primary_address: Multiaddr,
374 pub network_public_key: Option<NetworkPublicKey>,
375}
376
377#[derive(Clone, Debug, Serialize, Deserialize)]
378pub struct CommitteeWithNetworkMetadata {
379 epoch_id: EpochId,
380 validators: BTreeMap<AuthorityName, (StakeUnit, NetworkMetadata)>,
381
382 #[serde(skip)]
383 committee: OnceCell<Committee>,
384}
385
386impl CommitteeWithNetworkMetadata {
387 pub fn new(
388 epoch_id: EpochId,
389 validators: BTreeMap<AuthorityName, (StakeUnit, NetworkMetadata)>,
390 ) -> Self {
391 Self {
392 epoch_id,
393 validators,
394 committee: OnceCell::new(),
395 }
396 }
397 pub fn epoch(&self) -> EpochId {
398 self.epoch_id
399 }
400
401 pub fn validators(&self) -> &BTreeMap<AuthorityName, (StakeUnit, NetworkMetadata)> {
402 &self.validators
403 }
404
405 pub fn committee(&self) -> &Committee {
406 self.committee.get_or_init(|| {
407 Committee::new(
408 self.epoch_id,
409 self.validators
410 .iter()
411 .map(|(name, (stake, _))| (*name, *stake))
412 .collect(),
413 )
414 })
415 }
416}
417
418impl Display for CommitteeWithNetworkMetadata {
419 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
420 write!(
421 f,
422 "CommitteeWithNetworkMetadata (epoch={}, validators={:?})",
423 self.epoch_id, self.validators
424 )
425 }
426}
427
428#[cfg(test)]
429mod test {
430 use fastcrypto::traits::KeyPair;
431
432 use super::*;
433 use crate::crypto::{AuthorityKeyPair, get_key_pair};
434
435 #[test]
436 fn test_shuffle_by_weight() {
437 let (_, sec1): (_, AuthorityKeyPair) = get_key_pair();
438 let (_, sec2): (_, AuthorityKeyPair) = get_key_pair();
439 let (_, sec3): (_, AuthorityKeyPair) = get_key_pair();
440 let a1: AuthorityName = sec1.public().into();
441 let a2: AuthorityName = sec2.public().into();
442 let a3: AuthorityName = sec3.public().into();
443
444 let mut authorities = BTreeMap::new();
445 authorities.insert(a1, 1);
446 authorities.insert(a2, 1);
447 authorities.insert(a3, 1);
448
449 let committee = Committee::new_for_testing_with_normalized_voting_power(0, authorities);
450
451 assert_eq!(committee.shuffle_by_stake(None, None).len(), 3);
452
453 let mut pref = BTreeSet::new();
454 pref.insert(a2);
455
456 for _ in 0..100 {
458 assert_eq!(
459 a2,
460 *committee
461 .shuffle_by_stake(Some(&pref), None)
462 .first()
463 .unwrap()
464 );
465 }
466
467 let mut restrict = BTreeSet::new();
468 restrict.insert(a2);
469
470 for _ in 0..100 {
471 let res = committee.shuffle_by_stake(None, Some(&restrict));
472 assert_eq!(1, res.len());
473 assert_eq!(a2, res[0]);
474 }
475
476 let res = committee.shuffle_by_stake(Some(&BTreeSet::new()), None);
478 assert_eq!(3, res.len());
479
480 let res = committee.shuffle_by_stake(None, Some(&BTreeSet::new()));
481 assert_eq!(0, res.len());
482 }
483}