Skip to content

Commit

Permalink
chore: improve readability
Browse files Browse the repository at this point in the history
  • Loading branch information
grumbach committed Jul 19, 2022
1 parent 465bfe1 commit 8420b5f
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 33 deletions.
13 changes: 5 additions & 8 deletions src/knowledge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ impl Knowledge {
Ok(knowledge)
}

pub fn got_all_acks(&self, participants_len: usize) -> bool {
self.part_acks.len() == participants_len
pub fn got_all_acks(&self, num_participants: usize) -> bool {
self.part_acks.len() == num_participants
&& self
.part_acks
.iter()
.all(|(_, a)| a.len() == participants_len)
.all(|(_, a)| a.len() == num_participants)
}

fn handle_vote(&mut self, vote: DkgVote, id: NodeId) -> Result<(), KnowledgeFault> {
Expand All @@ -74,11 +74,8 @@ impl Knowledge {
return Err(KnowledgeFault::IncompatibleParts);
}
for (id_part, ack) in acked_parts {
if let Some(entry) = self.part_acks.get_mut(&id_part) {
entry.insert((id, ack));
} else {
self.part_acks.insert(id_part, BTreeSet::from([(id, ack)]));
}
let acks = self.part_acks.entry(id_part).or_default();
acks.insert((id, ack));
}
}
DkgVote::AllAcks(all_acks) => {
Expand Down
15 changes: 6 additions & 9 deletions src/sdkg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,16 +84,15 @@ use std::{
fmt::{self, Debug, Formatter},
hash::Hash,
ops::{AddAssign, Mul},
sync::Arc,
};
use thiserror::Error;

/// A peer node's unique identifier.
pub trait NodeIdT: Eq + Ord + Clone + Debug + Hash + Send + Sync {}
impl<N> NodeIdT for N where N: Eq + Ord + Clone + Debug + Hash + Send + Sync {}

/// A map assigning to each node ID a public key, wrapped in an `Arc`.
pub type PubKeyMap<N, PK = PublicKey> = Arc<BTreeMap<N, PK>>;
/// A map assigning to each node ID a public key
pub type PubKeyMap<N, PK = PublicKey> = BTreeMap<N, PK>;

/// Returns a `PubKeyMap` corresponding to the given secret keys.
///
Expand All @@ -104,7 +103,7 @@ where
I: IntoIterator<Item = (B, &'a SecretKey)>,
{
let to_pub = |(id, sk): I::Item| (id.borrow().clone(), sk.public_key());
Arc::new(sec_keys.into_iter().map(to_pub).collect())
sec_keys.into_iter().map(to_pub).collect()
}

/// A local error while handling an `Ack` or `Part` message, that was not caused by that message
Expand Down Expand Up @@ -506,7 +505,6 @@ mod tests {
use super::{AckOutcome, PartOutcome, SyncKeyGen};
use bls::{PublicKey, SecretKey, SignatureShare};
use std::collections::BTreeMap;
use std::sync::Arc;

#[test]
fn test_dkg() {
Expand All @@ -531,10 +529,9 @@ mod tests {
let mut parts = Vec::new();
for (id, sk) in sec_keys.into_iter().enumerate() {
let (sync_key_gen, opt_part) =
SyncKeyGen::new(id, sk, Arc::new(pub_keys.clone()), threshold, &mut rng)
.unwrap_or_else(|_| {
panic!("Failed to create `SyncKeyGen` instance for node #{}", id)
});
SyncKeyGen::new(id, sk, pub_keys.clone(), threshold, &mut rng).unwrap_or_else(
|_| panic!("Failed to create `SyncKeyGen` instance for node #{}", id),
);
nodes.insert(id, sync_key_gen);
parts.push((id, opt_part.unwrap())); // Would be `None` for observer nodes.
}
Expand Down
24 changes: 8 additions & 16 deletions src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

use bls::{PublicKey, PublicKeySet, SecretKey, SecretKeyShare};
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;

use crate::error::{Error, Result};
use crate::knowledge::{Knowledge, KnowledgeFault};
Expand Down Expand Up @@ -54,13 +53,8 @@ impl<R: bls::rand::RngCore + Clone> DkgState<R> {
threshold: usize,
rng: &mut R,
) -> Result<Self> {
let (sync_key_gen, opt_part) = SyncKeyGen::new(
our_id,
secret_key.clone(),
Arc::new(pub_keys.clone()),
threshold,
rng,
)?;
let (sync_key_gen, opt_part) =
SyncKeyGen::new(our_id, secret_key.clone(), pub_keys.clone(), threshold, rng)?;
Ok(DkgState {
id: our_id,
secret_key,
Expand Down Expand Up @@ -103,16 +97,16 @@ impl<R: bls::rand::RngCore + Clone> DkgState<R> {
Ok(k) => k,
};

let participants_len = self.pub_keys.len();
if knowledge.agreed_with_all_acks.len() == participants_len {
let num_participants = self.pub_keys.len();
if knowledge.agreed_with_all_acks.len() == num_participants {
DkgCurrentState::Termination(knowledge.part_acks)
} else if !knowledge.agreed_with_all_acks.is_empty() {
DkgCurrentState::WaitingForTotalAgreement
} else if knowledge.got_all_acks(participants_len) {
} else if knowledge.got_all_acks(num_participants) {
DkgCurrentState::GotAllAcks(knowledge.part_acks)
} else if !knowledge.part_acks.is_empty() {
DkgCurrentState::WaitingForMoreAcks
} else if knowledge.parts.len() == participants_len {
} else if knowledge.parts.len() == num_participants {
DkgCurrentState::GotAllParts(knowledge.parts)
} else {
DkgCurrentState::WaitingForMoreParts
Expand All @@ -134,8 +128,7 @@ impl<R: bls::rand::RngCore + Clone> DkgState<R> {
let outcome = self.keygen.handle_ack(&sender_id, ack.clone())?;
if let AckOutcome::Invalid(fault) = outcome {
return Err(Error::FaultyVote(format!(
"Ack fault: {:?} by {:?} for part by {:?}",
fault, sender_id, part_id
"Ack fault: {fault:?} by {sender_id:?} for part by {part_id:?}"
)));
}
}
Expand All @@ -156,8 +149,7 @@ impl<R: bls::rand::RngCore + Clone> DkgState<R> {
}
PartOutcome::Invalid(fault) => {
return Err(Error::FaultyVote(format!(
"Part fault: {:?} by {:?}",
fault, sender_id
"Part fault: {fault:?} by {sender_id:?}"
)));
}
PartOutcome::Valid(None) => {
Expand Down

0 comments on commit 8420b5f

Please sign in to comment.