Cache message instances

This commit is contained in:
Luke Parker
2024-05-09 20:52:00 -04:00
parent 90fa9c397c
commit 8469d18123
2 changed files with 16 additions and 16 deletions

View File

@@ -69,6 +69,17 @@ impl<B: Block, S: Signature> PartialEq for Data<B, S> {
}
}
impl<B: Block, S: Signature> core::hash::Hash for Data<B, S> {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
match self {
Data::Proposal(valid_round, block) => (0, valid_round, block.id().as_ref()).hash(state),
Data::Prevote(id) => (1, id.as_ref().map(AsRef::<[u8]>::as_ref)).hash(state),
Data::Precommit(None) => (2, 0).hash(state),
Data::Precommit(Some((id, _))) => (2, 1, id.as_ref()).hash(state),
}
}
}
impl<B: Block, S: Signature> Data<B, S> {
pub fn step(&self) -> Step {
match self {

View File

@@ -9,6 +9,7 @@ pub(crate) struct MessageLog<N: Network> {
weights: Arc<N::Weights>,
round_participation: HashMap<RoundNumber, u64>,
participation: HashMap<(RoundNumber, Step), u64>,
message_instances: HashMap<(RoundNumber, DataFor<N>), u64>,
pub(crate) log: HashMap<RoundNumber, RoundLog<N>>,
}
@@ -18,6 +19,7 @@ impl<N: Network> MessageLog<N> {
weights,
round_participation: HashMap::new(),
participation: HashMap::new(),
message_instances: HashMap::new(),
log: HashMap::new(),
}
}
@@ -48,26 +50,13 @@ impl<N: Network> MessageLog<N> {
*self.round_participation.entry(msg.round).or_insert_with(|| 0) += sender_weight;
}
*self.participation.entry((msg.round, step)).or_insert_with(|| 0) += sender_weight;
*self.message_instances.entry((msg.round, msg.data.clone())).or_insert_with(|| 0) +=
sender_weight;
msgs.insert(step, signed);
Ok(true)
}
// For a given round, return the weight agreeing with the data
fn message_instances(&self, round: RoundNumber, data: &DataFor<N>) -> u64 {
let mut weight = 0;
let Some(log) = self.log.get(&round) else { return 0 };
for (participant, msgs) in log {
if let Some(msg) = msgs.get(&data.step()) {
let validator_weight = self.weights.weight(*participant);
if data == &msg.msg.data {
weight += validator_weight;
}
}
}
weight
}
// Get the participation in a given round
pub(crate) fn round_participation(&self, round: RoundNumber) -> u64 {
*self.round_participation.get(&round).unwrap_or(&0)
@@ -80,6 +69,6 @@ impl<N: Network> MessageLog<N> {
// Check if consensus has been reached on a specific piece of data
pub(crate) fn has_consensus(&self, round: RoundNumber, data: &DataFor<N>) -> bool {
self.message_instances(round, data) >= self.weights.threshold()
*self.message_instances.get(&(round, data.clone())).unwrap_or(&0) >= self.weights.threshold()
}
}