Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 87 additions & 5 deletions crates/consensus/src/hotstuff/vote_collector/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ impl Default for VoteStoreBound {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SaveVoteOutcome {
Saved,
/// A differently signed vote from the same signer was replaced because the caller's `supersedes` rule accepted it.
Replaced,
/// An identical vote is already held. The view's quorum is re-evaluated, so a quorum returned through
/// [`VoteCollector::return_votes`] is emitted again when one of its votes is resubmitted.
AlreadyHeld,
Expand Down Expand Up @@ -110,6 +112,25 @@ where V::AggregationKey: Clone
vote: V,
committee: &Committee<TAddr>,
) -> Result<Option<Vec<V>>, DuplicateVoteDetected<V>> {
self.collect_vote_replacing(sender_vn, current_epoch, current_height, vote, committee, |_, _| false)
.await
}

/// Like [`Self::collect_vote`], replacing a differently signed vote already held from the same signer for the same
/// view when `supersedes(held, incoming)` returns `true`.
pub async fn collect_vote_replacing<TAddr, F>(
&self,
sender_vn: &ValidatorNode<TAddr>,
current_epoch: Epoch,
current_height: NodeHeight,
vote: V,
committee: &Committee<TAddr>,
supersedes: F,
) -> Result<Option<Vec<V>>, DuplicateVoteDetected<V>>
where
TAddr: NodeAddressable,
F: FnOnce(&V, &V) -> bool,
{
let mut access_mut = self.store.write().await;
access_mut.clear_votes_before(current_epoch, current_height);

Expand Down Expand Up @@ -144,7 +165,7 @@ where V::AggregationKey: Clone
let height = vote.height();
let agg_key = vote.aggregation_key();
let vote_display = vote.to_string();
if access_mut.save_vote(vote)? == SaveVoteOutcome::BelowSenderFloor {
if access_mut.save_vote_replacing(vote, supersedes)? == SaveVoteOutcome::BelowSenderFloor {
return Ok(None);
}

Expand Down Expand Up @@ -279,12 +300,18 @@ impl<V: Vote + Display + Clone> VoteStoreInner<V> {
/// one — this node cannot tell which is — and it may already be counted towards a quorum an honest
/// committee is forming, so dropping it would let an equivocator erase a real vote.
pub fn save_vote(&mut self, vote: V) -> Result<SaveVoteOutcome, DuplicateVoteDetected<V>> {
self.save_vote_replacing(vote, |_, _| false)
}

fn save_vote_replacing<F>(&mut self, vote: V, supersedes: F) -> Result<SaveVoteOutcome, DuplicateVoteDetected<V>>
where F: FnOnce(&V, &V) -> bool {
let epoch_height = (vote.epoch(), vote.height());
let sender_pk = *vote.public_key();

if let Some(prev_vote) = self.store.get(&epoch_height).and_then(|vv| vv.votes.get(&sender_pk)) {
let is_same_vote = prev_vote.signature() == vote.signature();
if is_same_vote {
if let Some(view_votes) = self.store.get_mut(&epoch_height) &&
let Some(prev_vote) = view_votes.votes.get_mut(&sender_pk)
{
if prev_vote.signature() == vote.signature() {
debug!(
target: LOG_TARGET,
"ℹ️ Received identical duplicate vote {}. Ignoring.",
Expand All @@ -293,6 +320,18 @@ impl<V: Vote + Display + Clone> VoteStoreInner<V> {
return Ok(SaveVoteOutcome::AlreadyHeld);
}

if supersedes(prev_vote, &vote) {
debug!(
target: LOG_TARGET,
"ℹ️ Replacing held vote {} with superseding vote {}.",
prev_vote,
vote,
);
*prev_vote = vote;
return Ok(SaveVoteOutcome::Replaced);
}

let previous_vote = prev_vote.clone();
warn!(
target: LOG_TARGET,
"❓️ Received duplicate vote for {}. This could be malicious because a validator should only vote once for the same block.",
Expand All @@ -302,7 +341,7 @@ impl<V: Vote + Display + Clone> VoteStoreInner<V> {
epoch: vote.epoch(),
height: vote.height(),
public_key: sender_pk,
previous_vote: prev_vote.clone(),
previous_vote,
new_vote: vote,
});
}
Expand Down Expand Up @@ -1258,4 +1297,47 @@ mod tests {
fn with_per_sender_limit_rejects_zero() {
let _collector = VoteCollector::<TestVote>::with_per_sender_limit(0);
}

#[tokio::test]
async fn collect_vote_replacing_supersedes_held_vote_without_re_emitting_quorum() {
let collector = VoteCollector::<TestVote>::with_per_sender_limit(4);
let (epoch, current_height, view_height) = (Epoch(1), NodeHeight(5), NodeHeight(12));
let voters = [pubkey(1), pubkey(2), pubkey(3), pubkey(4)];
let committee = committee(&voters);
let mk = |public_key, nonce_byte| TestVote {
epoch,
height: view_height,
block_id: FixedHash::zero(),
decision: QuorumDecision::Accept,
sig: SchnorrSignatureBytes::new([nonce_byte; 32].into(), Scalar32Bytes::zero()),
public_key,
};
let higher_nonce = |held: &TestVote, incoming: &TestVote| {
incoming.sig.public_nonce().as_bytes()[0] > held.sig.public_nonce().as_bytes()[0]
};
let collect_replacing = |vote: TestVote| {
let (collector, committee) = (&collector, &committee);
let pk = vote.public_key;
async move {
collector
.collect_vote_replacing(&validator(pk), epoch, current_height, vote, committee, higher_nonce)
.await
}
};

assert!(collect_replacing(mk(voters[0], 1)).await.unwrap().is_none());
let v0_high = mk(voters[0], 5);
assert!(collect_replacing(v0_high.clone()).await.unwrap().is_none());
assert_eq!(collector.store.read().await.sender_views[&voters[0]].len(), 1);

// A non-superseding vote is still rejected without overwriting the higher vote.
let dup = collect_replacing(mk(voters[0], 3)).await.unwrap_err();
assert_eq!(dup.previous_vote, v0_high);

// Reaching quorum returns the superseding vote, and a further replacement after quorum emits no second quorum.
assert!(collect_replacing(mk(voters[1], 1)).await.unwrap().is_none());
let quorum = collect_replacing(mk(voters[2], 1)).await.unwrap().expect("quorum");
assert!(quorum.contains(&v0_high));
assert!(collect_replacing(mk(voters[0], 9)).await.unwrap().is_none());
}
}
Loading