iota_types/
committee.rs

1// Copyright (c) 2021, Facebook, Inc. and its affiliates
2// Copyright (c) Mysten Labs, Inc.
3// Modifications Copyright (c) 2024 IOTA Stiftung
4// SPDX-License-Identifier: Apache-2.0
5
6use 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
33// TODO: the stake and voting power of a validator can be different so
34// in some places when we are actually referring to the voting power, we
35// should use a different type alias, field name, etc.
36pub type StakeUnit = u64;
37
38pub type CommitteeDigest = [u8; 32];
39
40// The voting power, quorum threshold and max voting power are defined in the
41// `voting_power.move` module. We're following the very same convention in the
42// validator binaries.
43
44/// Set total_voting_power as 10_000 by convention. Individual voting powers can
45/// be interpreted as easily understandable basis points (e.g., voting_power:
46/// 100 = 1%, voting_power: 1 = 0.01%). Fixing the total voting power allows
47/// clients to hardcode the quorum threshold and total_voting power rather
48/// than recomputing these.
49pub const TOTAL_VOTING_POWER: StakeUnit = 10_000;
50
51/// Quorum threshold for our fixed voting power--any message signed by this much
52/// voting power can be trusted up to BFT assumptions
53pub const QUORUM_THRESHOLD: StakeUnit = 6_667;
54
55/// Validity threshold defined by f+1
56pub 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    /// Normalize the given weights to TOTAL_VOTING_POWER and create the
89    /// committee. Used for testing only: a production system is using the
90    /// voting weights of the Iota System object.
91    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; // adjust the weights following the normalization coef
103                total_sum += *weight;
104            } else {
105                // the last element is taking all the rest
106                *weight = TOTAL_VOTING_POWER - total_sum;
107            }
108        }
109
110        Self::new(epoch, voting_weights)
111    }
112
113    // We call this if these have not yet been computed
114    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    /// Samples authorities by weight
165    pub fn sample(&self) -> &AuthorityName {
166        // unwrap safe unless committee is empty
167        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        // unwrap is safe because we validate the committee composition in `new` above.
178        // See https://docs.rs/rand/latest/rand/distributions/weighted/enum.WeightedError.html
179        // for possible errors.
180        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    /// Derive a seed deterministically from the transaction digest and shuffle
241    /// the validators.
242    pub fn shuffle_by_stake_from_tx_digest(
243        &self,
244        tx_digest: &TransactionDigest,
245    ) -> Vec<AuthorityName> {
246        // the 32 is as requirement of the default StdRng::from_seed choice
247        let digest_bytes = tx_digest.into_inner();
248
249        // permute the validators deterministically, based on the digest
250        let mut rng = StdRng::from_seed(digest_bytes);
251        self.shuffle_by_stake_with_rng(None, None, &mut rng)
252    }
253
254    // ===== Testing-only methods =====
255    //
256    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()), /* voting right */ 1)
266                })
267                .collect(),
268        );
269        (committee, key_pairs)
270    }
271
272    /// Generate a simple committee with 4 validators each with equal voting
273    /// stake of 1.
274    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        // try these authorities first
283        preferences: Option<&BTreeSet<AuthorityName>>,
284        // only attempt from these authorities.
285        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        // try these authorities first
351        preferences: Option<&BTreeSet<K>>,
352        // only attempt from these authorities.
353        restrict_to: Option<&BTreeSet<K>>,
354        rng: &mut impl Rng,
355    ) -> Vec<K>;
356
357    fn shuffle_by_stake(
358        &self,
359        // try these authorities first
360        preferences: Option<&BTreeSet<K>>,
361        // only attempt from these authorities.
362        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        // preference always comes first
457        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        // empty preferences are valid
477        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}