Skip to content

Commit

Permalink
Completed test and renamed ValidatorSet to ValidatorCommittee
Browse files Browse the repository at this point in the history
  • Loading branch information
ElFantasma committed Mar 15, 2024
1 parent b48ec12 commit 0707c46
Show file tree
Hide file tree
Showing 8 changed files with 52 additions and 50 deletions.
2 changes: 1 addition & 1 deletion node/actors/network/src/gossip/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ async fn test_validator_addrs() {
let rng = &mut ctx::test_root(&ctx::RealClock).rng();

let keys: Vec<validator::SecretKey> = (0..8).map(|_| rng.gen()).collect();
let validators = validator::ValidatorSet::new(keys.iter().map(|k| WeightedValidator {
let validators = validator::ValidatorCommittee::new(keys.iter().map(|k| WeightedValidator {
key: k.public(),
weight: 1250,
}))
Expand Down
4 changes: 2 additions & 2 deletions node/actors/network/src/gossip/validator_addrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl ValidatorAddrs {
/// Returns true iff some new entry was added.
pub(super) fn update(
&mut self,
validators: &validator::ValidatorSet,
validators: &validator::ValidatorCommittee,
data: &[Arc<validator::Signed<validator::NetAddress>>],
) -> anyhow::Result<bool> {
let mut changed = false;
Expand Down Expand Up @@ -97,7 +97,7 @@ impl ValidatorAddrsWatch {
/// invalid entry should be banned.
pub(crate) async fn update(
&self,
validators: &validator::ValidatorSet,
validators: &validator::ValidatorCommittee,
data: &[Arc<validator::Signed<validator::NetAddress>>],
) -> anyhow::Result<()> {
let this = self.0.lock().await;
Expand Down
5 changes: 3 additions & 2 deletions node/libs/roles/src/validator/conv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use super::{
AggregateSignature, BlockHeader, BlockHeaderHash, BlockNumber, CommitQC, ConsensusMsg,
FinalBlock, Fork, ForkNumber, Genesis, GenesisHash, LeaderCommit, LeaderPrepare, Msg, MsgHash,
NetAddress, Payload, PayloadHash, Phase, PrepareQC, ProtocolVersion, PublicKey, ReplicaCommit,
ReplicaPrepare, Signature, Signed, Signers, ValidatorSet, View, ViewNumber, WeightedValidator,
ReplicaPrepare, Signature, Signed, Signers, ValidatorCommittee, View, ViewNumber,
WeightedValidator,
};
use crate::{node::SessionId, proto::validator as proto};
use anyhow::Context as _;
Expand Down Expand Up @@ -41,7 +42,7 @@ impl ProtoFmt for Genesis {
.context("validators")?;
Ok(Self {
fork: read_required(&r.fork).context("fork")?,
validators: ValidatorSet::new(validators.into_iter()).context("validators")?,
validators: ValidatorCommittee::new(validators.into_iter()).context("validators")?,
})
}
fn build(&self) -> Self::Proto {
Expand Down
6 changes: 3 additions & 3 deletions node/libs/roles/src/validator/messages/consensus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,13 @@ impl Default for Fork {
/// A struct that represents a set of validators. It is used to store the current validator set.
/// We represent each validator by its validator public key.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidatorSet {
pub struct ValidatorCommittee {
vec: Vec<validator::PublicKey>,
indexes: BTreeMap<validator::PublicKey, usize>,
weights: BTreeMap<validator::PublicKey, usize>,
}

impl ValidatorSet {
impl ValidatorCommittee {
/// Creates a new ValidatorSet from a list of validator public keys.
pub fn new(validators: impl IntoIterator<Item = WeightedValidator>) -> anyhow::Result<Self> {
let mut set = BTreeSet::new();
Expand Down Expand Up @@ -194,7 +194,7 @@ pub fn faulty_replicas(n: usize) -> usize {
pub struct Genesis {
// TODO(gprusak): add blockchain id here.
/// Set of validators of the chain.
pub validators: ValidatorSet,
pub validators: ValidatorCommittee,
/// Fork of the chain to follow.
pub fork: Fork,
}
Expand Down
2 changes: 1 addition & 1 deletion node/libs/roles/src/validator/messages/leader_commit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl CommitQC {

// Verify the signer's weights is enough.
// TODO replace threshold check
let weight = genesis.validators.weight(self.signers.clone());
let _weight = genesis.validators.weight(self.signers.clone());

// Verify that we have enough signers.
let num_signers = self.signers.count();
Expand Down
4 changes: 4 additions & 0 deletions node/libs/roles/src/validator/messages/leader_prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ impl PrepareQC {
pub fn verify(&self, genesis: &Genesis) -> Result<(), PrepareQCVerifyError> {
use PrepareQCVerifyError as Error;
let mut sum = Signers::new(genesis.validators.len());

// Check the ReplicaPrepare messages.
for (i, (msg, signers)) in self.map.iter().enumerate() {
if msg.view != self.view {
Expand All @@ -126,6 +127,9 @@ impl PrepareQC {
sum |= signers;
}

let weight = genesis.validators.weight(sum.clone());
dbg!(weight);

// Verify that we have enough signers.
let threshold = genesis.validators.threshold();
if sum.count() < threshold {
Expand Down
10 changes: 5 additions & 5 deletions node/libs/roles/src/validator/testonly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use super::{
AggregateSignature, BlockHeader, BlockHeaderHash, BlockNumber, CommitQC, ConsensusMsg,
FinalBlock, Fork, ForkNumber, Genesis, GenesisHash, LeaderCommit, LeaderPrepare, Msg, MsgHash,
NetAddress, Payload, PayloadHash, Phase, PrepareQC, ProtocolVersion, PublicKey, ReplicaCommit,
ReplicaPrepare, SecretKey, Signature, Signed, Signers, ValidatorSet, View, ViewNumber,
ReplicaPrepare, SecretKey, Signature, Signed, Signers, ValidatorCommittee, View, ViewNumber,
WeightedValidator,
};
use bit_vec::BitVec;
Expand All @@ -25,7 +25,7 @@ impl Setup {
let keys: Vec<SecretKey> = (0..validators).map(|_| rng.gen()).collect();
let weight = (10000 / validators) as u32;
let genesis = Genesis {
validators: ValidatorSet::new(keys.iter().map(|k| WeightedValidator {
validators: ValidatorCommittee::new(keys.iter().map(|k| WeightedValidator {
key: k.public(),
weight,
}))
Expand Down Expand Up @@ -305,14 +305,14 @@ impl Distribution<Signers> for Standard {
}
}

impl Distribution<ValidatorSet> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ValidatorSet {
impl Distribution<ValidatorCommittee> for Standard {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ValidatorCommittee {
let count = rng.gen_range(1..11);
let public_keys = (0..count).map(|_| WeightedValidator {
key: rng.gen(),
weight: 1000,
});
ValidatorSet::new(public_keys).unwrap()
ValidatorCommittee::new(public_keys).unwrap()
}
}

Expand Down
69 changes: 33 additions & 36 deletions node/libs/roles/src/validator/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,8 +215,10 @@ fn test_commit_qc() {
let setup1 = Setup::new(rng, 6);
let setup2 = Setup::new(rng, 6);
let genesis3 = Genesis {
validators: ValidatorSet::new(setup1.genesis.validators.weighted_validators_iter().take(3))
.unwrap(),
validators: ValidatorCommittee::new(
setup1.genesis.validators.weighted_validators_iter().take(3),
)
.unwrap(),
fork: setup1.genesis.fork.clone(),
};

Expand Down Expand Up @@ -250,8 +252,10 @@ fn test_prepare_qc() {
let setup1 = Setup::new(rng, 6);
let setup2 = Setup::new(rng, 6);
let genesis3 = Genesis {
validators: ValidatorSet::new(setup1.genesis.validators.weighted_validators_iter().take(3))
.unwrap(),
validators: ValidatorCommittee::new(
setup1.genesis.validators.weighted_validators_iter().take(3),
)
.unwrap(),
fork: setup1.genesis.fork.clone(),
};

Expand Down Expand Up @@ -284,43 +288,36 @@ fn test_prepare_qc() {
}

#[test]
fn test_validator_set_weights() {
use PrepareQCVerifyError as Error;
fn test_validator_committee_weights() {
let ctx = ctx::test_root(&ctx::RealClock);
let rng = &mut ctx.rng();

let setup1 = Setup::new(rng, 6);
let setup2 = Setup::new(rng, 6);
let genesis3 = Genesis {
validators: ValidatorSet::new(setup1.genesis.validators.weighted_validators_iter().take(3))
.unwrap(),
fork: setup1.genesis.fork.clone(),
};

let view: ViewNumber = rng.gen();
let msgs: Vec<_> = (0..3)
.map(|_| make_replica_prepare(rng, view, &setup1))
let setup = Setup::new(rng, 6);
// Validators weights
let weights = [800, 800, 800, 6000, 800, 800];
// Expected sum of the validators weights
let sums = [800, 1600, 2400, 8400, 9200, 10000];
let validators: Vec<WeightedValidator> = weights
.iter()
.enumerate()
.map(|(i, w)| WeightedValidator {
key: setup.keys[i].public(),
weight: *w,
})
.collect();

for n in 0..setup1.keys.len() + 1 {
let mut qc = PrepareQC::new(msgs[0].view.clone());
for key in &setup1.keys[0..n] {
qc.add(
&key.sign_msg(msgs.choose(rng).unwrap().clone()),
&setup1.genesis,
);
}
if n >= setup1.genesis.validators.threshold() {
qc.verify(&setup1.genesis).unwrap();
} else {
assert_matches!(
qc.verify(&setup1.genesis),
Err(Error::NotEnoughSigners { .. })
);
}
let genesis = Genesis {
validators: ValidatorCommittee::new(validators).unwrap(),
fork: setup.genesis.fork.clone(),
};

// Mismatching validator sets.
assert!(qc.verify(&setup2.genesis).is_err());
assert!(qc.verify(&genesis3).is_err());
let view: ViewNumber = rng.gen();
let msg = make_replica_prepare(rng, view, &setup);
let mut qc = PrepareQC::new(msg.view.clone());
for n in 0..6 {
let key = &setup.keys[n];
qc.add(&key.sign_msg(msg.clone()), &setup.genesis);
let signers = &qc.map[&msg];
assert_eq!(genesis.validators.weight(signers.clone()), sums[n]);
}
}

0 comments on commit 0707c46

Please sign in to comment.