Skip to content

Commit

Permalink
Merge pull request #1983 from dusk-network/max_iter_50
Browse files Browse the repository at this point in the history
  • Loading branch information
herr-seppia authored Jul 23, 2024
2 parents c76847c + 53a7874 commit 6a2b047
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 53 deletions.
19 changes: 11 additions & 8 deletions consensus/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ use tracing::{debug, error};
/// It ensures that no multiple votes for same voter are collected.
pub struct Aggregator<V> {
// Map between (step, vote) and (signature, voters)
votes: BTreeMap<(u16, Vote), (AggrSignature, Cluster<PublicKey>)>,
votes: BTreeMap<(u8, Vote), (AggrSignature, Cluster<PublicKey>)>,

// Map each step to the set of voters. We do this to ensure only one vote
// per voter is cast
uniqueness: BTreeMap<u16, HashMap<PublicKeyBytes, V>>,
uniqueness: BTreeMap<u8, HashMap<PublicKeyBytes, V>>,
}

impl<V> Default for Aggregator<V> {
Expand Down Expand Up @@ -122,16 +122,17 @@ impl<V: StepVote> Aggregator<V> {
// An committee member is allowed to vote only once per a single
// step. Its vote has a weight value depending on how many times it
// has been extracted in the sortition for this step.
let weight = cluster.add(signer, weight);
debug_assert!(weight.is_some());
let added = cluster
.add(signer, weight)
.expect("Vote to be added to cluster");

let total = cluster.total_occurrences();

debug!(
event = "vote aggregated",
?vote,
from = signer.to_bs58(),
added = weight,
added,
total,
majority = committee.majority_quorum(),
super_majority = committee.super_majority_quorum(),
Expand Down Expand Up @@ -220,7 +221,7 @@ mod tests {
use std::collections::HashMap;

impl<V> Aggregator<V> {
pub fn get_total(&self, step: u16, vote: Vote) -> Option<usize> {
pub fn get_total(&self, step: u8, vote: Vote) -> Option<usize> {
if let Some(value) = self.votes.get(&(step, vote)) {
return Some(value.1.total_occurrences());
}
Expand Down Expand Up @@ -304,8 +305,8 @@ mod tests {
dbg!("{:?}", p);

// Collect votes from expected committee members
let expected_members = vec![0, 1, 3, 4, 5];
let expected_votes = vec![1, 1, 1, 2, 3];
let expected_members = vec![1, 2, 3, 4];
let expected_votes = vec![1, 1, 2, 1];

// The index of the provisioner (inside expected_members) that let the
// quorum being reached
Expand All @@ -319,6 +320,7 @@ mod tests {
}
},
);
println!("winning index {winning_index}");
let mut collected_votes = 0;
for i in 0..expected_members.len() - 1 {
// Select provisioner
Expand All @@ -344,6 +346,7 @@ mod tests {
break;
}

println!("Collecting vote for index {i}");
// Check collected votes
let (_, quorum_reached) = a.collect_vote(&c, msg).unwrap();

Expand Down
8 changes: 4 additions & 4 deletions consensus/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use std::time::Duration;

/// Maximum number of iterations Consensus runs per a single round.
pub const CONSENSUS_MAX_ITER: u8 = 255;
pub const CONSENSUS_MAX_ITER: u8 = 50;

/// Percentage number that determines quorums.
pub const SUPERMAJORITY_THRESHOLD: f64 = 0.67;
Expand All @@ -25,10 +25,10 @@ pub const RATIFICATION_COMMITTEE_QUORUM: f64 =

pub const DEFAULT_BLOCK_GAS_LIMIT: u64 = 5 * 1_000_000_000;

pub const RELAX_ITERATION_THRESHOLD: u8 = 10;
pub const RELAX_ITERATION_THRESHOLD: u8 = 8;

/// Emergency mode is enabled only for the last N iterations
pub const EMERGENCY_MODE_ITERATION_THRESHOLD: u8 = CONSENSUS_MAX_ITER - 50;
/// Emergency mode is enabled after 16 iterations
pub const EMERGENCY_MODE_ITERATION_THRESHOLD: u8 = 16;

pub const MIN_STEP_TIMEOUT: Duration = Duration::from_secs(7);
pub const MAX_STEP_TIMEOUT: Duration = Duration::from_secs(40);
Expand Down
4 changes: 2 additions & 2 deletions consensus/src/execution_ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ impl<'a, DB: Database, T: Operations + 'static> ExecutionCtx<'a, DB, T> {
self.step
}

pub fn step(&self) -> u16 {
pub fn step(&self) -> u8 {
self.step.to_step(self.iteration)
}

Expand All @@ -106,7 +106,7 @@ impl<'a, DB: Database, T: Operations + 'static> ExecutionCtx<'a, DB, T> {
committee.is_member(&self.round_update.pubkey_bls)
}

pub(crate) fn save_committee(&mut self, step: u16, committee: Committee) {
pub(crate) fn save_committee(&mut self, step: u8, committee: Committee) {
self.iter_ctx.committees.insert(step, committee);
}

Expand Down
6 changes: 3 additions & 3 deletions consensus/src/iteration_ctx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,11 @@ use tracing::debug;
/// A pool of all generated committees
#[derive(Default)]
pub struct RoundCommittees {
committees: HashMap<u16, Committee>,
committees: HashMap<u8, Committee>,
}

impl RoundCommittees {
pub(crate) fn get_committee(&self, step: u16) -> Option<&Committee> {
pub(crate) fn get_committee(&self, step: u8) -> Option<&Committee> {
self.committees.get(&step)
}

Expand All @@ -53,7 +53,7 @@ impl RoundCommittees {
self.get_committee(step)
}

pub(crate) fn insert(&mut self, step: u16, committee: Committee) {
pub(crate) fn insert(&mut self, step: u8, committee: Committee) {
self.committees.insert(step, committee);
}
}
Expand Down
8 changes: 4 additions & 4 deletions consensus/src/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use std::collections::BTreeMap;
use std::fmt::Debug;

type StepMap<T> = BTreeMap<u16, Vec<T>>;
type StepMap<T> = BTreeMap<u8, Vec<T>>;
type RoundMap<T> = BTreeMap<u64, StepMap<T>>;

#[derive(Debug, Default)]
Expand All @@ -18,7 +18,7 @@ where
/// A message registry that stores messages based on their round and step.
impl<T: Debug + Clone> MsgRegistry<T> {
/// Inserts a message into the registry based on its round and step.
pub fn put_msg(&mut self, round: u64, step: u16, msg: T) {
pub fn put_msg(&mut self, round: u64, step: u8, msg: T) {
self.0
.entry(round)
.or_default()
Expand All @@ -32,7 +32,7 @@ impl<T: Debug + Clone> MsgRegistry<T> {
pub fn drain_msg_by_round_step(
&mut self,
round: u64,
step: u16,
step: u8,
) -> Option<Vec<T>> {
self.0
.get_mut(&round)
Expand Down Expand Up @@ -96,7 +96,7 @@ mod tests {
assert!(reg.drain_msg_by_round_step(4444, 2).is_none());

for i in 1..100 {
reg.put_msg(4444, i as u16, Item(i));
reg.put_msg(4444, i as u8, Item(i));
}

assert_eq!(reg.msg_count(), 100 + 2);
Expand Down
2 changes: 2 additions & 0 deletions consensus/src/user/cluster.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ where
}

/// Adds key with specified weight. Weight per key can be set only once.
///
/// Return None if `weight` is 0 or key is already set.
pub fn add(&mut self, key: &T, weight: usize) -> Option<usize> {
if weight == 0 {
return None;
Expand Down
27 changes: 12 additions & 15 deletions consensus/src/user/provisioners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,18 +187,15 @@ impl Provisioners {
sortition::generate_sortition_score(hash, &total_weight);

// NB: The public key can be extracted multiple times per committee.
match comm.extract_and_subtract_member(score) {
Some((pk, subtracted_stake)) => {
// append the public key to the committee set.
extracted.push(pk);

if total_weight > subtracted_stake {
total_weight -= subtracted_stake;
} else {
break;
}
}
None => panic!("invalid score"),
let (pk, subtracted_stake) =
comm.extract_and_subtract_member(score);
// append the public key to the committee set.
extracted.push(pk);

if total_weight > subtracted_stake {
total_weight -= subtracted_stake;
} else {
break;
}
}

Expand Down Expand Up @@ -277,9 +274,9 @@ impl<'a> CommitteeGenerator<'a> {
fn extract_and_subtract_member(
&mut self,
mut score: BigInt,
) -> Option<(PublicKey, BigInt)> {
) -> (PublicKey, BigInt) {
if self.members.is_empty() {
return None;
panic!("Cannot extract member from an empty committee");
}

loop {
Expand All @@ -290,7 +287,7 @@ impl<'a> CommitteeGenerator<'a> {
// accordingly.
let subtracted_stake = BigInt::from(stake.subtract(DUSK));

return Some((pk.clone(), subtracted_stake));
return (pk.clone(), subtracted_stake);
}

score -= total_stake;
Expand Down
26 changes: 13 additions & 13 deletions consensus/src/user/sortition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use crate::config::{
pub struct Config {
seed: Seed,
round: u64,
pub step: u16,
pub step: u8,
committee_credits: usize,
exclusion: Vec<PublicKeyBytes>,
}
Expand Down Expand Up @@ -52,7 +52,7 @@ impl Config {
self.committee_credits
}

pub fn step(&self) -> u16 {
pub fn step(&self) -> u8 {
self.step
}

Expand Down Expand Up @@ -108,7 +108,7 @@ mod tests {
pub fn raw(
seed: Seed,
round: u64,
step: u16,
step: u8,
committee_credits: usize,
exclusion: Vec<PublicKeyBytes>,
) -> Config {
Expand All @@ -125,9 +125,9 @@ mod tests {
#[test]
pub fn test_sortition_hash() {
let hash = [
102, 194, 89, 58, 228, 163, 25, 223, 222, 214, 246, 137, 213, 168,
65, 13, 83, 130, 73, 187, 213, 145, 71, 20, 64, 167, 93, 251, 151,
200, 167, 168,
74, 64, 238, 174, 226, 52, 11, 105, 93, 251, 204, 6, 137, 176, 14,
96, 77, 139, 92, 76, 7, 178, 38, 16, 132, 233, 13, 180, 78, 206,
204, 31,
];

assert_eq!(
Expand All @@ -142,8 +142,8 @@ mod tests {
#[test]
pub fn test_generate_sortition_score() {
let dataset = vec![
([3; 48], 123342342, 40818748),
([4; 48], 44443333, 26458886),
([3; 48], 123342342, 80689917),
([4; 48], 44443333, 20330495),
];

for (seed, total_weight, expected_score) in dataset {
Expand Down Expand Up @@ -177,7 +177,7 @@ mod tests {
);

// Verify expected distribution
assert_eq!(vec![8, 20, 14, 22], committee.get_occurrences());
assert_eq!(vec![4, 29, 9, 22], committee.get_occurrences());
}

#[test]
Expand All @@ -198,7 +198,7 @@ mod tests {
committee_credits,
committee.get_occurrences().iter().sum::<usize>()
);
assert_eq!(vec![3, 17, 9, 16], committee.get_occurrences());
assert_eq!(vec![6, 13, 11, 15], committee.get_occurrences());
}

#[test]
Expand All @@ -210,7 +210,7 @@ mod tests {
let committee_credits = 45;
let iteration = 2;
let relative_step = 2;
let step = iteration as u16 * 3 + relative_step;
let step = iteration * 3 + relative_step;

let cfg = Config::raw(seed, round, step, committee_credits, vec![]);
let generator = p.get_generator(iteration, seed, round);
Expand All @@ -224,7 +224,7 @@ mod tests {
committee_credits,
committee.get_occurrences().iter().sum::<usize>()
);
assert_eq!(vec![3, 17, 9, 16], committee.get_occurrences());
assert_eq!(vec![6, 13, 11, 15], committee.get_occurrences());

// Run the same extraction, with the generator excluded
let cfg =
Expand All @@ -242,7 +242,7 @@ mod tests {
committee_credits,
committee.get_occurrences().iter().sum::<usize>()
);
assert_eq!(vec![5, 23, 17], committee.get_occurrences());
assert_eq!(vec![8, 13, 24], committee.get_occurrences());
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions node-data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ pub enum StepName {
}

impl StepName {
pub fn to_step(self, iteration: u8) -> u16 {
iteration as u16 * 3 + (self as u16)
pub fn to_step(self, iteration: u8) -> u8 {
iteration * 3 + (self as u8)
}
}

Expand Down
4 changes: 2 additions & 2 deletions node-data/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ impl Message {
};
Some(signer)
}
pub fn get_step(&self) -> u16 {
pub fn get_step(&self) -> u8 {
match &self.payload {
Payload::Candidate(c) => c.get_step(),
Payload::Validation(v) => v.get_step(),
Expand Down Expand Up @@ -1152,7 +1152,7 @@ pub trait StepMessage {
fn sign_info(&self) -> &SignInfo;
fn sign_info_mut(&mut self) -> &mut SignInfo;

fn get_step(&self) -> u16 {
fn get_step(&self) -> u8 {
Self::STEP_NAME.to_step(self.header().iteration)
}

Expand Down

0 comments on commit 6a2b047

Please sign in to comment.